Chart.js 536 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962
  1. /*!
  2. * Chart.js
  3. * http://chartjs.org/
  4. * Version: 2.7.3
  5. *
  6. * Copyright 2018 Chart.js Contributors
  7. * Released under the MIT license
  8. * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
  9. */
  10. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Chart = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  11. /* MIT license */
  12. var colorNames = require(5);
  13. module.exports = {
  14. getRgba: getRgba,
  15. getHsla: getHsla,
  16. getRgb: getRgb,
  17. getHsl: getHsl,
  18. getHwb: getHwb,
  19. getAlpha: getAlpha,
  20. hexString: hexString,
  21. rgbString: rgbString,
  22. rgbaString: rgbaString,
  23. percentString: percentString,
  24. percentaString: percentaString,
  25. hslString: hslString,
  26. hslaString: hslaString,
  27. hwbString: hwbString,
  28. keyword: keyword
  29. }
  30. function getRgba(string) {
  31. if (!string) {
  32. return;
  33. }
  34. var abbr = /^#([a-fA-F0-9]{3})$/i,
  35. hex = /^#([a-fA-F0-9]{6})$/i,
  36. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  37. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  38. keyword = /(\w+)/;
  39. var rgb = [0, 0, 0],
  40. a = 1,
  41. match = string.match(abbr);
  42. if (match) {
  43. match = match[1];
  44. for (var i = 0; i < rgb.length; i++) {
  45. rgb[i] = parseInt(match[i] + match[i], 16);
  46. }
  47. }
  48. else if (match = string.match(hex)) {
  49. match = match[1];
  50. for (var i = 0; i < rgb.length; i++) {
  51. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  52. }
  53. }
  54. else if (match = string.match(rgba)) {
  55. for (var i = 0; i < rgb.length; i++) {
  56. rgb[i] = parseInt(match[i + 1]);
  57. }
  58. a = parseFloat(match[4]);
  59. }
  60. else if (match = string.match(per)) {
  61. for (var i = 0; i < rgb.length; i++) {
  62. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  63. }
  64. a = parseFloat(match[4]);
  65. }
  66. else if (match = string.match(keyword)) {
  67. if (match[1] == "transparent") {
  68. return [0, 0, 0, 0];
  69. }
  70. rgb = colorNames[match[1]];
  71. if (!rgb) {
  72. return;
  73. }
  74. }
  75. for (var i = 0; i < rgb.length; i++) {
  76. rgb[i] = scale(rgb[i], 0, 255);
  77. }
  78. if (!a && a != 0) {
  79. a = 1;
  80. }
  81. else {
  82. a = scale(a, 0, 1);
  83. }
  84. rgb[3] = a;
  85. return rgb;
  86. }
  87. function getHsla(string) {
  88. if (!string) {
  89. return;
  90. }
  91. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  92. var match = string.match(hsl);
  93. if (match) {
  94. var alpha = parseFloat(match[4]);
  95. var h = scale(parseInt(match[1]), 0, 360),
  96. s = scale(parseFloat(match[2]), 0, 100),
  97. l = scale(parseFloat(match[3]), 0, 100),
  98. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  99. return [h, s, l, a];
  100. }
  101. }
  102. function getHwb(string) {
  103. if (!string) {
  104. return;
  105. }
  106. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  107. var match = string.match(hwb);
  108. if (match) {
  109. var alpha = parseFloat(match[4]);
  110. var h = scale(parseInt(match[1]), 0, 360),
  111. w = scale(parseFloat(match[2]), 0, 100),
  112. b = scale(parseFloat(match[3]), 0, 100),
  113. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  114. return [h, w, b, a];
  115. }
  116. }
  117. function getRgb(string) {
  118. var rgba = getRgba(string);
  119. return rgba && rgba.slice(0, 3);
  120. }
  121. function getHsl(string) {
  122. var hsla = getHsla(string);
  123. return hsla && hsla.slice(0, 3);
  124. }
  125. function getAlpha(string) {
  126. var vals = getRgba(string);
  127. if (vals) {
  128. return vals[3];
  129. }
  130. else if (vals = getHsla(string)) {
  131. return vals[3];
  132. }
  133. else if (vals = getHwb(string)) {
  134. return vals[3];
  135. }
  136. }
  137. // generators
  138. function hexString(rgb) {
  139. return "#" + hexDouble(rgb[0]) + hexDouble(rgb[1])
  140. + hexDouble(rgb[2]);
  141. }
  142. function rgbString(rgba, alpha) {
  143. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  144. return rgbaString(rgba, alpha);
  145. }
  146. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  147. }
  148. function rgbaString(rgba, alpha) {
  149. if (alpha === undefined) {
  150. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  151. }
  152. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  153. + ", " + alpha + ")";
  154. }
  155. function percentString(rgba, alpha) {
  156. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  157. return percentaString(rgba, alpha);
  158. }
  159. var r = Math.round(rgba[0]/255 * 100),
  160. g = Math.round(rgba[1]/255 * 100),
  161. b = Math.round(rgba[2]/255 * 100);
  162. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  163. }
  164. function percentaString(rgba, alpha) {
  165. var r = Math.round(rgba[0]/255 * 100),
  166. g = Math.round(rgba[1]/255 * 100),
  167. b = Math.round(rgba[2]/255 * 100);
  168. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  169. }
  170. function hslString(hsla, alpha) {
  171. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  172. return hslaString(hsla, alpha);
  173. }
  174. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  175. }
  176. function hslaString(hsla, alpha) {
  177. if (alpha === undefined) {
  178. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  179. }
  180. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  181. + alpha + ")";
  182. }
  183. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  184. // (hwb have alpha optional & 1 is default value)
  185. function hwbString(hwb, alpha) {
  186. if (alpha === undefined) {
  187. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  188. }
  189. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  190. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  191. }
  192. function keyword(rgb) {
  193. return reverseNames[rgb.slice(0, 3)];
  194. }
  195. // helpers
  196. function scale(num, min, max) {
  197. return Math.min(Math.max(min, num), max);
  198. }
  199. function hexDouble(num) {
  200. var str = num.toString(16).toUpperCase();
  201. return (str.length < 2) ? "0" + str : str;
  202. }
  203. //create a list of reverse color names
  204. var reverseNames = {};
  205. for (var name in colorNames) {
  206. reverseNames[colorNames[name]] = name;
  207. }
  208. },{"5":5}],2:[function(require,module,exports){
  209. /* MIT license */
  210. var convert = require(4);
  211. var string = require(1);
  212. var Color = function (obj) {
  213. if (obj instanceof Color) {
  214. return obj;
  215. }
  216. if (!(this instanceof Color)) {
  217. return new Color(obj);
  218. }
  219. this.valid = false;
  220. this.values = {
  221. rgb: [0, 0, 0],
  222. hsl: [0, 0, 0],
  223. hsv: [0, 0, 0],
  224. hwb: [0, 0, 0],
  225. cmyk: [0, 0, 0, 0],
  226. alpha: 1
  227. };
  228. // parse Color() argument
  229. var vals;
  230. if (typeof obj === 'string') {
  231. vals = string.getRgba(obj);
  232. if (vals) {
  233. this.setValues('rgb', vals);
  234. } else if (vals = string.getHsla(obj)) {
  235. this.setValues('hsl', vals);
  236. } else if (vals = string.getHwb(obj)) {
  237. this.setValues('hwb', vals);
  238. }
  239. } else if (typeof obj === 'object') {
  240. vals = obj;
  241. if (vals.r !== undefined || vals.red !== undefined) {
  242. this.setValues('rgb', vals);
  243. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  244. this.setValues('hsl', vals);
  245. } else if (vals.v !== undefined || vals.value !== undefined) {
  246. this.setValues('hsv', vals);
  247. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  248. this.setValues('hwb', vals);
  249. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  250. this.setValues('cmyk', vals);
  251. }
  252. }
  253. };
  254. Color.prototype = {
  255. isValid: function () {
  256. return this.valid;
  257. },
  258. rgb: function () {
  259. return this.setSpace('rgb', arguments);
  260. },
  261. hsl: function () {
  262. return this.setSpace('hsl', arguments);
  263. },
  264. hsv: function () {
  265. return this.setSpace('hsv', arguments);
  266. },
  267. hwb: function () {
  268. return this.setSpace('hwb', arguments);
  269. },
  270. cmyk: function () {
  271. return this.setSpace('cmyk', arguments);
  272. },
  273. rgbArray: function () {
  274. return this.values.rgb;
  275. },
  276. hslArray: function () {
  277. return this.values.hsl;
  278. },
  279. hsvArray: function () {
  280. return this.values.hsv;
  281. },
  282. hwbArray: function () {
  283. var values = this.values;
  284. if (values.alpha !== 1) {
  285. return values.hwb.concat([values.alpha]);
  286. }
  287. return values.hwb;
  288. },
  289. cmykArray: function () {
  290. return this.values.cmyk;
  291. },
  292. rgbaArray: function () {
  293. var values = this.values;
  294. return values.rgb.concat([values.alpha]);
  295. },
  296. hslaArray: function () {
  297. var values = this.values;
  298. return values.hsl.concat([values.alpha]);
  299. },
  300. alpha: function (val) {
  301. if (val === undefined) {
  302. return this.values.alpha;
  303. }
  304. this.setValues('alpha', val);
  305. return this;
  306. },
  307. red: function (val) {
  308. return this.setChannel('rgb', 0, val);
  309. },
  310. green: function (val) {
  311. return this.setChannel('rgb', 1, val);
  312. },
  313. blue: function (val) {
  314. return this.setChannel('rgb', 2, val);
  315. },
  316. hue: function (val) {
  317. if (val) {
  318. val %= 360;
  319. val = val < 0 ? 360 + val : val;
  320. }
  321. return this.setChannel('hsl', 0, val);
  322. },
  323. saturation: function (val) {
  324. return this.setChannel('hsl', 1, val);
  325. },
  326. lightness: function (val) {
  327. return this.setChannel('hsl', 2, val);
  328. },
  329. saturationv: function (val) {
  330. return this.setChannel('hsv', 1, val);
  331. },
  332. whiteness: function (val) {
  333. return this.setChannel('hwb', 1, val);
  334. },
  335. blackness: function (val) {
  336. return this.setChannel('hwb', 2, val);
  337. },
  338. value: function (val) {
  339. return this.setChannel('hsv', 2, val);
  340. },
  341. cyan: function (val) {
  342. return this.setChannel('cmyk', 0, val);
  343. },
  344. magenta: function (val) {
  345. return this.setChannel('cmyk', 1, val);
  346. },
  347. yellow: function (val) {
  348. return this.setChannel('cmyk', 2, val);
  349. },
  350. black: function (val) {
  351. return this.setChannel('cmyk', 3, val);
  352. },
  353. hexString: function () {
  354. return string.hexString(this.values.rgb);
  355. },
  356. rgbString: function () {
  357. return string.rgbString(this.values.rgb, this.values.alpha);
  358. },
  359. rgbaString: function () {
  360. return string.rgbaString(this.values.rgb, this.values.alpha);
  361. },
  362. percentString: function () {
  363. return string.percentString(this.values.rgb, this.values.alpha);
  364. },
  365. hslString: function () {
  366. return string.hslString(this.values.hsl, this.values.alpha);
  367. },
  368. hslaString: function () {
  369. return string.hslaString(this.values.hsl, this.values.alpha);
  370. },
  371. hwbString: function () {
  372. return string.hwbString(this.values.hwb, this.values.alpha);
  373. },
  374. keyword: function () {
  375. return string.keyword(this.values.rgb, this.values.alpha);
  376. },
  377. rgbNumber: function () {
  378. var rgb = this.values.rgb;
  379. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  380. },
  381. luminosity: function () {
  382. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  383. var rgb = this.values.rgb;
  384. var lum = [];
  385. for (var i = 0; i < rgb.length; i++) {
  386. var chan = rgb[i] / 255;
  387. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  388. }
  389. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  390. },
  391. contrast: function (color2) {
  392. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  393. var lum1 = this.luminosity();
  394. var lum2 = color2.luminosity();
  395. if (lum1 > lum2) {
  396. return (lum1 + 0.05) / (lum2 + 0.05);
  397. }
  398. return (lum2 + 0.05) / (lum1 + 0.05);
  399. },
  400. level: function (color2) {
  401. var contrastRatio = this.contrast(color2);
  402. if (contrastRatio >= 7.1) {
  403. return 'AAA';
  404. }
  405. return (contrastRatio >= 4.5) ? 'AA' : '';
  406. },
  407. dark: function () {
  408. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  409. var rgb = this.values.rgb;
  410. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  411. return yiq < 128;
  412. },
  413. light: function () {
  414. return !this.dark();
  415. },
  416. negate: function () {
  417. var rgb = [];
  418. for (var i = 0; i < 3; i++) {
  419. rgb[i] = 255 - this.values.rgb[i];
  420. }
  421. this.setValues('rgb', rgb);
  422. return this;
  423. },
  424. lighten: function (ratio) {
  425. var hsl = this.values.hsl;
  426. hsl[2] += hsl[2] * ratio;
  427. this.setValues('hsl', hsl);
  428. return this;
  429. },
  430. darken: function (ratio) {
  431. var hsl = this.values.hsl;
  432. hsl[2] -= hsl[2] * ratio;
  433. this.setValues('hsl', hsl);
  434. return this;
  435. },
  436. saturate: function (ratio) {
  437. var hsl = this.values.hsl;
  438. hsl[1] += hsl[1] * ratio;
  439. this.setValues('hsl', hsl);
  440. return this;
  441. },
  442. desaturate: function (ratio) {
  443. var hsl = this.values.hsl;
  444. hsl[1] -= hsl[1] * ratio;
  445. this.setValues('hsl', hsl);
  446. return this;
  447. },
  448. whiten: function (ratio) {
  449. var hwb = this.values.hwb;
  450. hwb[1] += hwb[1] * ratio;
  451. this.setValues('hwb', hwb);
  452. return this;
  453. },
  454. blacken: function (ratio) {
  455. var hwb = this.values.hwb;
  456. hwb[2] += hwb[2] * ratio;
  457. this.setValues('hwb', hwb);
  458. return this;
  459. },
  460. greyscale: function () {
  461. var rgb = this.values.rgb;
  462. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  463. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  464. this.setValues('rgb', [val, val, val]);
  465. return this;
  466. },
  467. clearer: function (ratio) {
  468. var alpha = this.values.alpha;
  469. this.setValues('alpha', alpha - (alpha * ratio));
  470. return this;
  471. },
  472. opaquer: function (ratio) {
  473. var alpha = this.values.alpha;
  474. this.setValues('alpha', alpha + (alpha * ratio));
  475. return this;
  476. },
  477. rotate: function (degrees) {
  478. var hsl = this.values.hsl;
  479. var hue = (hsl[0] + degrees) % 360;
  480. hsl[0] = hue < 0 ? 360 + hue : hue;
  481. this.setValues('hsl', hsl);
  482. return this;
  483. },
  484. /**
  485. * Ported from sass implementation in C
  486. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  487. */
  488. mix: function (mixinColor, weight) {
  489. var color1 = this;
  490. var color2 = mixinColor;
  491. var p = weight === undefined ? 0.5 : weight;
  492. var w = 2 * p - 1;
  493. var a = color1.alpha() - color2.alpha();
  494. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  495. var w2 = 1 - w1;
  496. return this
  497. .rgb(
  498. w1 * color1.red() + w2 * color2.red(),
  499. w1 * color1.green() + w2 * color2.green(),
  500. w1 * color1.blue() + w2 * color2.blue()
  501. )
  502. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  503. },
  504. toJSON: function () {
  505. return this.rgb();
  506. },
  507. clone: function () {
  508. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  509. // making the final build way to big to embed in Chart.js. So let's do it manually,
  510. // assuming that values to clone are 1 dimension arrays containing only numbers,
  511. // except 'alpha' which is a number.
  512. var result = new Color();
  513. var source = this.values;
  514. var target = result.values;
  515. var value, type;
  516. for (var prop in source) {
  517. if (source.hasOwnProperty(prop)) {
  518. value = source[prop];
  519. type = ({}).toString.call(value);
  520. if (type === '[object Array]') {
  521. target[prop] = value.slice(0);
  522. } else if (type === '[object Number]') {
  523. target[prop] = value;
  524. } else {
  525. console.error('unexpected color value:', value);
  526. }
  527. }
  528. }
  529. return result;
  530. }
  531. };
  532. Color.prototype.spaces = {
  533. rgb: ['red', 'green', 'blue'],
  534. hsl: ['hue', 'saturation', 'lightness'],
  535. hsv: ['hue', 'saturation', 'value'],
  536. hwb: ['hue', 'whiteness', 'blackness'],
  537. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  538. };
  539. Color.prototype.maxes = {
  540. rgb: [255, 255, 255],
  541. hsl: [360, 100, 100],
  542. hsv: [360, 100, 100],
  543. hwb: [360, 100, 100],
  544. cmyk: [100, 100, 100, 100]
  545. };
  546. Color.prototype.getValues = function (space) {
  547. var values = this.values;
  548. var vals = {};
  549. for (var i = 0; i < space.length; i++) {
  550. vals[space.charAt(i)] = values[space][i];
  551. }
  552. if (values.alpha !== 1) {
  553. vals.a = values.alpha;
  554. }
  555. // {r: 255, g: 255, b: 255, a: 0.4}
  556. return vals;
  557. };
  558. Color.prototype.setValues = function (space, vals) {
  559. var values = this.values;
  560. var spaces = this.spaces;
  561. var maxes = this.maxes;
  562. var alpha = 1;
  563. var i;
  564. this.valid = true;
  565. if (space === 'alpha') {
  566. alpha = vals;
  567. } else if (vals.length) {
  568. // [10, 10, 10]
  569. values[space] = vals.slice(0, space.length);
  570. alpha = vals[space.length];
  571. } else if (vals[space.charAt(0)] !== undefined) {
  572. // {r: 10, g: 10, b: 10}
  573. for (i = 0; i < space.length; i++) {
  574. values[space][i] = vals[space.charAt(i)];
  575. }
  576. alpha = vals.a;
  577. } else if (vals[spaces[space][0]] !== undefined) {
  578. // {red: 10, green: 10, blue: 10}
  579. var chans = spaces[space];
  580. for (i = 0; i < space.length; i++) {
  581. values[space][i] = vals[chans[i]];
  582. }
  583. alpha = vals.alpha;
  584. }
  585. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  586. if (space === 'alpha') {
  587. return false;
  588. }
  589. var capped;
  590. // cap values of the space prior converting all values
  591. for (i = 0; i < space.length; i++) {
  592. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  593. values[space][i] = Math.round(capped);
  594. }
  595. // convert to all the other color spaces
  596. for (var sname in spaces) {
  597. if (sname !== space) {
  598. values[sname] = convert[space][sname](values[space]);
  599. }
  600. }
  601. return true;
  602. };
  603. Color.prototype.setSpace = function (space, args) {
  604. var vals = args[0];
  605. if (vals === undefined) {
  606. // color.rgb()
  607. return this.getValues(space);
  608. }
  609. // color.rgb(10, 10, 10)
  610. if (typeof vals === 'number') {
  611. vals = Array.prototype.slice.call(args);
  612. }
  613. this.setValues(space, vals);
  614. return this;
  615. };
  616. Color.prototype.setChannel = function (space, index, val) {
  617. var svalues = this.values[space];
  618. if (val === undefined) {
  619. // color.red()
  620. return svalues[index];
  621. } else if (val === svalues[index]) {
  622. // color.red(color.red())
  623. return this;
  624. }
  625. // color.red(100)
  626. svalues[index] = val;
  627. this.setValues(space, svalues);
  628. return this;
  629. };
  630. if (typeof window !== 'undefined') {
  631. window.Color = Color;
  632. }
  633. module.exports = Color;
  634. },{"1":1,"4":4}],3:[function(require,module,exports){
  635. /* MIT license */
  636. module.exports = {
  637. rgb2hsl: rgb2hsl,
  638. rgb2hsv: rgb2hsv,
  639. rgb2hwb: rgb2hwb,
  640. rgb2cmyk: rgb2cmyk,
  641. rgb2keyword: rgb2keyword,
  642. rgb2xyz: rgb2xyz,
  643. rgb2lab: rgb2lab,
  644. rgb2lch: rgb2lch,
  645. hsl2rgb: hsl2rgb,
  646. hsl2hsv: hsl2hsv,
  647. hsl2hwb: hsl2hwb,
  648. hsl2cmyk: hsl2cmyk,
  649. hsl2keyword: hsl2keyword,
  650. hsv2rgb: hsv2rgb,
  651. hsv2hsl: hsv2hsl,
  652. hsv2hwb: hsv2hwb,
  653. hsv2cmyk: hsv2cmyk,
  654. hsv2keyword: hsv2keyword,
  655. hwb2rgb: hwb2rgb,
  656. hwb2hsl: hwb2hsl,
  657. hwb2hsv: hwb2hsv,
  658. hwb2cmyk: hwb2cmyk,
  659. hwb2keyword: hwb2keyword,
  660. cmyk2rgb: cmyk2rgb,
  661. cmyk2hsl: cmyk2hsl,
  662. cmyk2hsv: cmyk2hsv,
  663. cmyk2hwb: cmyk2hwb,
  664. cmyk2keyword: cmyk2keyword,
  665. keyword2rgb: keyword2rgb,
  666. keyword2hsl: keyword2hsl,
  667. keyword2hsv: keyword2hsv,
  668. keyword2hwb: keyword2hwb,
  669. keyword2cmyk: keyword2cmyk,
  670. keyword2lab: keyword2lab,
  671. keyword2xyz: keyword2xyz,
  672. xyz2rgb: xyz2rgb,
  673. xyz2lab: xyz2lab,
  674. xyz2lch: xyz2lch,
  675. lab2xyz: lab2xyz,
  676. lab2rgb: lab2rgb,
  677. lab2lch: lab2lch,
  678. lch2lab: lch2lab,
  679. lch2xyz: lch2xyz,
  680. lch2rgb: lch2rgb
  681. }
  682. function rgb2hsl(rgb) {
  683. var r = rgb[0]/255,
  684. g = rgb[1]/255,
  685. b = rgb[2]/255,
  686. min = Math.min(r, g, b),
  687. max = Math.max(r, g, b),
  688. delta = max - min,
  689. h, s, l;
  690. if (max == min)
  691. h = 0;
  692. else if (r == max)
  693. h = (g - b) / delta;
  694. else if (g == max)
  695. h = 2 + (b - r) / delta;
  696. else if (b == max)
  697. h = 4 + (r - g)/ delta;
  698. h = Math.min(h * 60, 360);
  699. if (h < 0)
  700. h += 360;
  701. l = (min + max) / 2;
  702. if (max == min)
  703. s = 0;
  704. else if (l <= 0.5)
  705. s = delta / (max + min);
  706. else
  707. s = delta / (2 - max - min);
  708. return [h, s * 100, l * 100];
  709. }
  710. function rgb2hsv(rgb) {
  711. var r = rgb[0],
  712. g = rgb[1],
  713. b = rgb[2],
  714. min = Math.min(r, g, b),
  715. max = Math.max(r, g, b),
  716. delta = max - min,
  717. h, s, v;
  718. if (max == 0)
  719. s = 0;
  720. else
  721. s = (delta/max * 1000)/10;
  722. if (max == min)
  723. h = 0;
  724. else if (r == max)
  725. h = (g - b) / delta;
  726. else if (g == max)
  727. h = 2 + (b - r) / delta;
  728. else if (b == max)
  729. h = 4 + (r - g) / delta;
  730. h = Math.min(h * 60, 360);
  731. if (h < 0)
  732. h += 360;
  733. v = ((max / 255) * 1000) / 10;
  734. return [h, s, v];
  735. }
  736. function rgb2hwb(rgb) {
  737. var r = rgb[0],
  738. g = rgb[1],
  739. b = rgb[2],
  740. h = rgb2hsl(rgb)[0],
  741. w = 1/255 * Math.min(r, Math.min(g, b)),
  742. b = 1 - 1/255 * Math.max(r, Math.max(g, b));
  743. return [h, w * 100, b * 100];
  744. }
  745. function rgb2cmyk(rgb) {
  746. var r = rgb[0] / 255,
  747. g = rgb[1] / 255,
  748. b = rgb[2] / 255,
  749. c, m, y, k;
  750. k = Math.min(1 - r, 1 - g, 1 - b);
  751. c = (1 - r - k) / (1 - k) || 0;
  752. m = (1 - g - k) / (1 - k) || 0;
  753. y = (1 - b - k) / (1 - k) || 0;
  754. return [c * 100, m * 100, y * 100, k * 100];
  755. }
  756. function rgb2keyword(rgb) {
  757. return reverseKeywords[JSON.stringify(rgb)];
  758. }
  759. function rgb2xyz(rgb) {
  760. var r = rgb[0] / 255,
  761. g = rgb[1] / 255,
  762. b = rgb[2] / 255;
  763. // assume sRGB
  764. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  765. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  766. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  767. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  768. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  769. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  770. return [x * 100, y *100, z * 100];
  771. }
  772. function rgb2lab(rgb) {
  773. var xyz = rgb2xyz(rgb),
  774. x = xyz[0],
  775. y = xyz[1],
  776. z = xyz[2],
  777. l, a, b;
  778. x /= 95.047;
  779. y /= 100;
  780. z /= 108.883;
  781. x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
  782. y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
  783. z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
  784. l = (116 * y) - 16;
  785. a = 500 * (x - y);
  786. b = 200 * (y - z);
  787. return [l, a, b];
  788. }
  789. function rgb2lch(args) {
  790. return lab2lch(rgb2lab(args));
  791. }
  792. function hsl2rgb(hsl) {
  793. var h = hsl[0] / 360,
  794. s = hsl[1] / 100,
  795. l = hsl[2] / 100,
  796. t1, t2, t3, rgb, val;
  797. if (s == 0) {
  798. val = l * 255;
  799. return [val, val, val];
  800. }
  801. if (l < 0.5)
  802. t2 = l * (1 + s);
  803. else
  804. t2 = l + s - l * s;
  805. t1 = 2 * l - t2;
  806. rgb = [0, 0, 0];
  807. for (var i = 0; i < 3; i++) {
  808. t3 = h + 1 / 3 * - (i - 1);
  809. t3 < 0 && t3++;
  810. t3 > 1 && t3--;
  811. if (6 * t3 < 1)
  812. val = t1 + (t2 - t1) * 6 * t3;
  813. else if (2 * t3 < 1)
  814. val = t2;
  815. else if (3 * t3 < 2)
  816. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  817. else
  818. val = t1;
  819. rgb[i] = val * 255;
  820. }
  821. return rgb;
  822. }
  823. function hsl2hsv(hsl) {
  824. var h = hsl[0],
  825. s = hsl[1] / 100,
  826. l = hsl[2] / 100,
  827. sv, v;
  828. if(l === 0) {
  829. // no need to do calc on black
  830. // also avoids divide by 0 error
  831. return [0, 0, 0];
  832. }
  833. l *= 2;
  834. s *= (l <= 1) ? l : 2 - l;
  835. v = (l + s) / 2;
  836. sv = (2 * s) / (l + s);
  837. return [h, sv * 100, v * 100];
  838. }
  839. function hsl2hwb(args) {
  840. return rgb2hwb(hsl2rgb(args));
  841. }
  842. function hsl2cmyk(args) {
  843. return rgb2cmyk(hsl2rgb(args));
  844. }
  845. function hsl2keyword(args) {
  846. return rgb2keyword(hsl2rgb(args));
  847. }
  848. function hsv2rgb(hsv) {
  849. var h = hsv[0] / 60,
  850. s = hsv[1] / 100,
  851. v = hsv[2] / 100,
  852. hi = Math.floor(h) % 6;
  853. var f = h - Math.floor(h),
  854. p = 255 * v * (1 - s),
  855. q = 255 * v * (1 - (s * f)),
  856. t = 255 * v * (1 - (s * (1 - f))),
  857. v = 255 * v;
  858. switch(hi) {
  859. case 0:
  860. return [v, t, p];
  861. case 1:
  862. return [q, v, p];
  863. case 2:
  864. return [p, v, t];
  865. case 3:
  866. return [p, q, v];
  867. case 4:
  868. return [t, p, v];
  869. case 5:
  870. return [v, p, q];
  871. }
  872. }
  873. function hsv2hsl(hsv) {
  874. var h = hsv[0],
  875. s = hsv[1] / 100,
  876. v = hsv[2] / 100,
  877. sl, l;
  878. l = (2 - s) * v;
  879. sl = s * v;
  880. sl /= (l <= 1) ? l : 2 - l;
  881. sl = sl || 0;
  882. l /= 2;
  883. return [h, sl * 100, l * 100];
  884. }
  885. function hsv2hwb(args) {
  886. return rgb2hwb(hsv2rgb(args))
  887. }
  888. function hsv2cmyk(args) {
  889. return rgb2cmyk(hsv2rgb(args));
  890. }
  891. function hsv2keyword(args) {
  892. return rgb2keyword(hsv2rgb(args));
  893. }
  894. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  895. function hwb2rgb(hwb) {
  896. var h = hwb[0] / 360,
  897. wh = hwb[1] / 100,
  898. bl = hwb[2] / 100,
  899. ratio = wh + bl,
  900. i, v, f, n;
  901. // wh + bl cant be > 1
  902. if (ratio > 1) {
  903. wh /= ratio;
  904. bl /= ratio;
  905. }
  906. i = Math.floor(6 * h);
  907. v = 1 - bl;
  908. f = 6 * h - i;
  909. if ((i & 0x01) != 0) {
  910. f = 1 - f;
  911. }
  912. n = wh + f * (v - wh); // linear interpolation
  913. switch (i) {
  914. default:
  915. case 6:
  916. case 0: r = v; g = n; b = wh; break;
  917. case 1: r = n; g = v; b = wh; break;
  918. case 2: r = wh; g = v; b = n; break;
  919. case 3: r = wh; g = n; b = v; break;
  920. case 4: r = n; g = wh; b = v; break;
  921. case 5: r = v; g = wh; b = n; break;
  922. }
  923. return [r * 255, g * 255, b * 255];
  924. }
  925. function hwb2hsl(args) {
  926. return rgb2hsl(hwb2rgb(args));
  927. }
  928. function hwb2hsv(args) {
  929. return rgb2hsv(hwb2rgb(args));
  930. }
  931. function hwb2cmyk(args) {
  932. return rgb2cmyk(hwb2rgb(args));
  933. }
  934. function hwb2keyword(args) {
  935. return rgb2keyword(hwb2rgb(args));
  936. }
  937. function cmyk2rgb(cmyk) {
  938. var c = cmyk[0] / 100,
  939. m = cmyk[1] / 100,
  940. y = cmyk[2] / 100,
  941. k = cmyk[3] / 100,
  942. r, g, b;
  943. r = 1 - Math.min(1, c * (1 - k) + k);
  944. g = 1 - Math.min(1, m * (1 - k) + k);
  945. b = 1 - Math.min(1, y * (1 - k) + k);
  946. return [r * 255, g * 255, b * 255];
  947. }
  948. function cmyk2hsl(args) {
  949. return rgb2hsl(cmyk2rgb(args));
  950. }
  951. function cmyk2hsv(args) {
  952. return rgb2hsv(cmyk2rgb(args));
  953. }
  954. function cmyk2hwb(args) {
  955. return rgb2hwb(cmyk2rgb(args));
  956. }
  957. function cmyk2keyword(args) {
  958. return rgb2keyword(cmyk2rgb(args));
  959. }
  960. function xyz2rgb(xyz) {
  961. var x = xyz[0] / 100,
  962. y = xyz[1] / 100,
  963. z = xyz[2] / 100,
  964. r, g, b;
  965. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  966. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  967. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  968. // assume sRGB
  969. r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  970. : r = (r * 12.92);
  971. g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  972. : g = (g * 12.92);
  973. b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  974. : b = (b * 12.92);
  975. r = Math.min(Math.max(0, r), 1);
  976. g = Math.min(Math.max(0, g), 1);
  977. b = Math.min(Math.max(0, b), 1);
  978. return [r * 255, g * 255, b * 255];
  979. }
  980. function xyz2lab(xyz) {
  981. var x = xyz[0],
  982. y = xyz[1],
  983. z = xyz[2],
  984. l, a, b;
  985. x /= 95.047;
  986. y /= 100;
  987. z /= 108.883;
  988. x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
  989. y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
  990. z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
  991. l = (116 * y) - 16;
  992. a = 500 * (x - y);
  993. b = 200 * (y - z);
  994. return [l, a, b];
  995. }
  996. function xyz2lch(args) {
  997. return lab2lch(xyz2lab(args));
  998. }
  999. function lab2xyz(lab) {
  1000. var l = lab[0],
  1001. a = lab[1],
  1002. b = lab[2],
  1003. x, y, z, y2;
  1004. if (l <= 8) {
  1005. y = (l * 100) / 903.3;
  1006. y2 = (7.787 * (y / 100)) + (16 / 116);
  1007. } else {
  1008. y = 100 * Math.pow((l + 16) / 116, 3);
  1009. y2 = Math.pow(y / 100, 1/3);
  1010. }
  1011. x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
  1012. z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
  1013. return [x, y, z];
  1014. }
  1015. function lab2lch(lab) {
  1016. var l = lab[0],
  1017. a = lab[1],
  1018. b = lab[2],
  1019. hr, h, c;
  1020. hr = Math.atan2(b, a);
  1021. h = hr * 360 / 2 / Math.PI;
  1022. if (h < 0) {
  1023. h += 360;
  1024. }
  1025. c = Math.sqrt(a * a + b * b);
  1026. return [l, c, h];
  1027. }
  1028. function lab2rgb(args) {
  1029. return xyz2rgb(lab2xyz(args));
  1030. }
  1031. function lch2lab(lch) {
  1032. var l = lch[0],
  1033. c = lch[1],
  1034. h = lch[2],
  1035. a, b, hr;
  1036. hr = h / 360 * 2 * Math.PI;
  1037. a = c * Math.cos(hr);
  1038. b = c * Math.sin(hr);
  1039. return [l, a, b];
  1040. }
  1041. function lch2xyz(args) {
  1042. return lab2xyz(lch2lab(args));
  1043. }
  1044. function lch2rgb(args) {
  1045. return lab2rgb(lch2lab(args));
  1046. }
  1047. function keyword2rgb(keyword) {
  1048. return cssKeywords[keyword];
  1049. }
  1050. function keyword2hsl(args) {
  1051. return rgb2hsl(keyword2rgb(args));
  1052. }
  1053. function keyword2hsv(args) {
  1054. return rgb2hsv(keyword2rgb(args));
  1055. }
  1056. function keyword2hwb(args) {
  1057. return rgb2hwb(keyword2rgb(args));
  1058. }
  1059. function keyword2cmyk(args) {
  1060. return rgb2cmyk(keyword2rgb(args));
  1061. }
  1062. function keyword2lab(args) {
  1063. return rgb2lab(keyword2rgb(args));
  1064. }
  1065. function keyword2xyz(args) {
  1066. return rgb2xyz(keyword2rgb(args));
  1067. }
  1068. var cssKeywords = {
  1069. aliceblue: [240,248,255],
  1070. antiquewhite: [250,235,215],
  1071. aqua: [0,255,255],
  1072. aquamarine: [127,255,212],
  1073. azure: [240,255,255],
  1074. beige: [245,245,220],
  1075. bisque: [255,228,196],
  1076. black: [0,0,0],
  1077. blanchedalmond: [255,235,205],
  1078. blue: [0,0,255],
  1079. blueviolet: [138,43,226],
  1080. brown: [165,42,42],
  1081. burlywood: [222,184,135],
  1082. cadetblue: [95,158,160],
  1083. chartreuse: [127,255,0],
  1084. chocolate: [210,105,30],
  1085. coral: [255,127,80],
  1086. cornflowerblue: [100,149,237],
  1087. cornsilk: [255,248,220],
  1088. crimson: [220,20,60],
  1089. cyan: [0,255,255],
  1090. darkblue: [0,0,139],
  1091. darkcyan: [0,139,139],
  1092. darkgoldenrod: [184,134,11],
  1093. darkgray: [169,169,169],
  1094. darkgreen: [0,100,0],
  1095. darkgrey: [169,169,169],
  1096. darkkhaki: [189,183,107],
  1097. darkmagenta: [139,0,139],
  1098. darkolivegreen: [85,107,47],
  1099. darkorange: [255,140,0],
  1100. darkorchid: [153,50,204],
  1101. darkred: [139,0,0],
  1102. darksalmon: [233,150,122],
  1103. darkseagreen: [143,188,143],
  1104. darkslateblue: [72,61,139],
  1105. darkslategray: [47,79,79],
  1106. darkslategrey: [47,79,79],
  1107. darkturquoise: [0,206,209],
  1108. darkviolet: [148,0,211],
  1109. deeppink: [255,20,147],
  1110. deepskyblue: [0,191,255],
  1111. dimgray: [105,105,105],
  1112. dimgrey: [105,105,105],
  1113. dodgerblue: [30,144,255],
  1114. firebrick: [178,34,34],
  1115. floralwhite: [255,250,240],
  1116. forestgreen: [34,139,34],
  1117. fuchsia: [255,0,255],
  1118. gainsboro: [220,220,220],
  1119. ghostwhite: [248,248,255],
  1120. gold: [255,215,0],
  1121. goldenrod: [218,165,32],
  1122. gray: [128,128,128],
  1123. green: [0,128,0],
  1124. greenyellow: [173,255,47],
  1125. grey: [128,128,128],
  1126. honeydew: [240,255,240],
  1127. hotpink: [255,105,180],
  1128. indianred: [205,92,92],
  1129. indigo: [75,0,130],
  1130. ivory: [255,255,240],
  1131. khaki: [240,230,140],
  1132. lavender: [230,230,250],
  1133. lavenderblush: [255,240,245],
  1134. lawngreen: [124,252,0],
  1135. lemonchiffon: [255,250,205],
  1136. lightblue: [173,216,230],
  1137. lightcoral: [240,128,128],
  1138. lightcyan: [224,255,255],
  1139. lightgoldenrodyellow: [250,250,210],
  1140. lightgray: [211,211,211],
  1141. lightgreen: [144,238,144],
  1142. lightgrey: [211,211,211],
  1143. lightpink: [255,182,193],
  1144. lightsalmon: [255,160,122],
  1145. lightseagreen: [32,178,170],
  1146. lightskyblue: [135,206,250],
  1147. lightslategray: [119,136,153],
  1148. lightslategrey: [119,136,153],
  1149. lightsteelblue: [176,196,222],
  1150. lightyellow: [255,255,224],
  1151. lime: [0,255,0],
  1152. limegreen: [50,205,50],
  1153. linen: [250,240,230],
  1154. magenta: [255,0,255],
  1155. maroon: [128,0,0],
  1156. mediumaquamarine: [102,205,170],
  1157. mediumblue: [0,0,205],
  1158. mediumorchid: [186,85,211],
  1159. mediumpurple: [147,112,219],
  1160. mediumseagreen: [60,179,113],
  1161. mediumslateblue: [123,104,238],
  1162. mediumspringgreen: [0,250,154],
  1163. mediumturquoise: [72,209,204],
  1164. mediumvioletred: [199,21,133],
  1165. midnightblue: [25,25,112],
  1166. mintcream: [245,255,250],
  1167. mistyrose: [255,228,225],
  1168. moccasin: [255,228,181],
  1169. navajowhite: [255,222,173],
  1170. navy: [0,0,128],
  1171. oldlace: [253,245,230],
  1172. olive: [128,128,0],
  1173. olivedrab: [107,142,35],
  1174. orange: [255,165,0],
  1175. orangered: [255,69,0],
  1176. orchid: [218,112,214],
  1177. palegoldenrod: [238,232,170],
  1178. palegreen: [152,251,152],
  1179. paleturquoise: [175,238,238],
  1180. palevioletred: [219,112,147],
  1181. papayawhip: [255,239,213],
  1182. peachpuff: [255,218,185],
  1183. peru: [205,133,63],
  1184. pink: [255,192,203],
  1185. plum: [221,160,221],
  1186. powderblue: [176,224,230],
  1187. purple: [128,0,128],
  1188. rebeccapurple: [102, 51, 153],
  1189. red: [255,0,0],
  1190. rosybrown: [188,143,143],
  1191. royalblue: [65,105,225],
  1192. saddlebrown: [139,69,19],
  1193. salmon: [250,128,114],
  1194. sandybrown: [244,164,96],
  1195. seagreen: [46,139,87],
  1196. seashell: [255,245,238],
  1197. sienna: [160,82,45],
  1198. silver: [192,192,192],
  1199. skyblue: [135,206,235],
  1200. slateblue: [106,90,205],
  1201. slategray: [112,128,144],
  1202. slategrey: [112,128,144],
  1203. snow: [255,250,250],
  1204. springgreen: [0,255,127],
  1205. steelblue: [70,130,180],
  1206. tan: [210,180,140],
  1207. teal: [0,128,128],
  1208. thistle: [216,191,216],
  1209. tomato: [255,99,71],
  1210. turquoise: [64,224,208],
  1211. violet: [238,130,238],
  1212. wheat: [245,222,179],
  1213. white: [255,255,255],
  1214. whitesmoke: [245,245,245],
  1215. yellow: [255,255,0],
  1216. yellowgreen: [154,205,50]
  1217. };
  1218. var reverseKeywords = {};
  1219. for (var key in cssKeywords) {
  1220. reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
  1221. }
  1222. },{}],4:[function(require,module,exports){
  1223. var conversions = require(3);
  1224. var convert = function() {
  1225. return new Converter();
  1226. }
  1227. for (var func in conversions) {
  1228. // export Raw versions
  1229. convert[func + "Raw"] = (function(func) {
  1230. // accept array or plain args
  1231. return function(arg) {
  1232. if (typeof arg == "number")
  1233. arg = Array.prototype.slice.call(arguments);
  1234. return conversions[func](arg);
  1235. }
  1236. })(func);
  1237. var pair = /(\w+)2(\w+)/.exec(func),
  1238. from = pair[1],
  1239. to = pair[2];
  1240. // export rgb2hsl and ["rgb"]["hsl"]
  1241. convert[from] = convert[from] || {};
  1242. convert[from][to] = convert[func] = (function(func) {
  1243. return function(arg) {
  1244. if (typeof arg == "number")
  1245. arg = Array.prototype.slice.call(arguments);
  1246. var val = conversions[func](arg);
  1247. if (typeof val == "string" || val === undefined)
  1248. return val; // keyword
  1249. for (var i = 0; i < val.length; i++)
  1250. val[i] = Math.round(val[i]);
  1251. return val;
  1252. }
  1253. })(func);
  1254. }
  1255. /* Converter does lazy conversion and caching */
  1256. var Converter = function() {
  1257. this.convs = {};
  1258. };
  1259. /* Either get the values for a space or
  1260. set the values for a space, depending on args */
  1261. Converter.prototype.routeSpace = function(space, args) {
  1262. var values = args[0];
  1263. if (values === undefined) {
  1264. // color.rgb()
  1265. return this.getValues(space);
  1266. }
  1267. // color.rgb(10, 10, 10)
  1268. if (typeof values == "number") {
  1269. values = Array.prototype.slice.call(args);
  1270. }
  1271. return this.setValues(space, values);
  1272. };
  1273. /* Set the values for a space, invalidating cache */
  1274. Converter.prototype.setValues = function(space, values) {
  1275. this.space = space;
  1276. this.convs = {};
  1277. this.convs[space] = values;
  1278. return this;
  1279. };
  1280. /* Get the values for a space. If there's already
  1281. a conversion for the space, fetch it, otherwise
  1282. compute it */
  1283. Converter.prototype.getValues = function(space) {
  1284. var vals = this.convs[space];
  1285. if (!vals) {
  1286. var fspace = this.space,
  1287. from = this.convs[fspace];
  1288. vals = convert[fspace][space](from);
  1289. this.convs[space] = vals;
  1290. }
  1291. return vals;
  1292. };
  1293. ["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
  1294. Converter.prototype[space] = function(vals) {
  1295. return this.routeSpace(space, arguments);
  1296. }
  1297. });
  1298. module.exports = convert;
  1299. },{"3":3}],5:[function(require,module,exports){
  1300. 'use strict'
  1301. module.exports = {
  1302. "aliceblue": [240, 248, 255],
  1303. "antiquewhite": [250, 235, 215],
  1304. "aqua": [0, 255, 255],
  1305. "aquamarine": [127, 255, 212],
  1306. "azure": [240, 255, 255],
  1307. "beige": [245, 245, 220],
  1308. "bisque": [255, 228, 196],
  1309. "black": [0, 0, 0],
  1310. "blanchedalmond": [255, 235, 205],
  1311. "blue": [0, 0, 255],
  1312. "blueviolet": [138, 43, 226],
  1313. "brown": [165, 42, 42],
  1314. "burlywood": [222, 184, 135],
  1315. "cadetblue": [95, 158, 160],
  1316. "chartreuse": [127, 255, 0],
  1317. "chocolate": [210, 105, 30],
  1318. "coral": [255, 127, 80],
  1319. "cornflowerblue": [100, 149, 237],
  1320. "cornsilk": [255, 248, 220],
  1321. "crimson": [220, 20, 60],
  1322. "cyan": [0, 255, 255],
  1323. "darkblue": [0, 0, 139],
  1324. "darkcyan": [0, 139, 139],
  1325. "darkgoldenrod": [184, 134, 11],
  1326. "darkgray": [169, 169, 169],
  1327. "darkgreen": [0, 100, 0],
  1328. "darkgrey": [169, 169, 169],
  1329. "darkkhaki": [189, 183, 107],
  1330. "darkmagenta": [139, 0, 139],
  1331. "darkolivegreen": [85, 107, 47],
  1332. "darkorange": [255, 140, 0],
  1333. "darkorchid": [153, 50, 204],
  1334. "darkred": [139, 0, 0],
  1335. "darksalmon": [233, 150, 122],
  1336. "darkseagreen": [143, 188, 143],
  1337. "darkslateblue": [72, 61, 139],
  1338. "darkslategray": [47, 79, 79],
  1339. "darkslategrey": [47, 79, 79],
  1340. "darkturquoise": [0, 206, 209],
  1341. "darkviolet": [148, 0, 211],
  1342. "deeppink": [255, 20, 147],
  1343. "deepskyblue": [0, 191, 255],
  1344. "dimgray": [105, 105, 105],
  1345. "dimgrey": [105, 105, 105],
  1346. "dodgerblue": [30, 144, 255],
  1347. "firebrick": [178, 34, 34],
  1348. "floralwhite": [255, 250, 240],
  1349. "forestgreen": [34, 139, 34],
  1350. "fuchsia": [255, 0, 255],
  1351. "gainsboro": [220, 220, 220],
  1352. "ghostwhite": [248, 248, 255],
  1353. "gold": [255, 215, 0],
  1354. "goldenrod": [218, 165, 32],
  1355. "gray": [128, 128, 128],
  1356. "green": [0, 128, 0],
  1357. "greenyellow": [173, 255, 47],
  1358. "grey": [128, 128, 128],
  1359. "honeydew": [240, 255, 240],
  1360. "hotpink": [255, 105, 180],
  1361. "indianred": [205, 92, 92],
  1362. "indigo": [75, 0, 130],
  1363. "ivory": [255, 255, 240],
  1364. "khaki": [240, 230, 140],
  1365. "lavender": [230, 230, 250],
  1366. "lavenderblush": [255, 240, 245],
  1367. "lawngreen": [124, 252, 0],
  1368. "lemonchiffon": [255, 250, 205],
  1369. "lightblue": [173, 216, 230],
  1370. "lightcoral": [240, 128, 128],
  1371. "lightcyan": [224, 255, 255],
  1372. "lightgoldenrodyellow": [250, 250, 210],
  1373. "lightgray": [211, 211, 211],
  1374. "lightgreen": [144, 238, 144],
  1375. "lightgrey": [211, 211, 211],
  1376. "lightpink": [255, 182, 193],
  1377. "lightsalmon": [255, 160, 122],
  1378. "lightseagreen": [32, 178, 170],
  1379. "lightskyblue": [135, 206, 250],
  1380. "lightslategray": [119, 136, 153],
  1381. "lightslategrey": [119, 136, 153],
  1382. "lightsteelblue": [176, 196, 222],
  1383. "lightyellow": [255, 255, 224],
  1384. "lime": [0, 255, 0],
  1385. "limegreen": [50, 205, 50],
  1386. "linen": [250, 240, 230],
  1387. "magenta": [255, 0, 255],
  1388. "maroon": [128, 0, 0],
  1389. "mediumaquamarine": [102, 205, 170],
  1390. "mediumblue": [0, 0, 205],
  1391. "mediumorchid": [186, 85, 211],
  1392. "mediumpurple": [147, 112, 219],
  1393. "mediumseagreen": [60, 179, 113],
  1394. "mediumslateblue": [123, 104, 238],
  1395. "mediumspringgreen": [0, 250, 154],
  1396. "mediumturquoise": [72, 209, 204],
  1397. "mediumvioletred": [199, 21, 133],
  1398. "midnightblue": [25, 25, 112],
  1399. "mintcream": [245, 255, 250],
  1400. "mistyrose": [255, 228, 225],
  1401. "moccasin": [255, 228, 181],
  1402. "navajowhite": [255, 222, 173],
  1403. "navy": [0, 0, 128],
  1404. "oldlace": [253, 245, 230],
  1405. "olive": [128, 128, 0],
  1406. "olivedrab": [107, 142, 35],
  1407. "orange": [255, 165, 0],
  1408. "orangered": [255, 69, 0],
  1409. "orchid": [218, 112, 214],
  1410. "palegoldenrod": [238, 232, 170],
  1411. "palegreen": [152, 251, 152],
  1412. "paleturquoise": [175, 238, 238],
  1413. "palevioletred": [219, 112, 147],
  1414. "papayawhip": [255, 239, 213],
  1415. "peachpuff": [255, 218, 185],
  1416. "peru": [205, 133, 63],
  1417. "pink": [255, 192, 203],
  1418. "plum": [221, 160, 221],
  1419. "powderblue": [176, 224, 230],
  1420. "purple": [128, 0, 128],
  1421. "rebeccapurple": [102, 51, 153],
  1422. "red": [255, 0, 0],
  1423. "rosybrown": [188, 143, 143],
  1424. "royalblue": [65, 105, 225],
  1425. "saddlebrown": [139, 69, 19],
  1426. "salmon": [250, 128, 114],
  1427. "sandybrown": [244, 164, 96],
  1428. "seagreen": [46, 139, 87],
  1429. "seashell": [255, 245, 238],
  1430. "sienna": [160, 82, 45],
  1431. "silver": [192, 192, 192],
  1432. "skyblue": [135, 206, 235],
  1433. "slateblue": [106, 90, 205],
  1434. "slategray": [112, 128, 144],
  1435. "slategrey": [112, 128, 144],
  1436. "snow": [255, 250, 250],
  1437. "springgreen": [0, 255, 127],
  1438. "steelblue": [70, 130, 180],
  1439. "tan": [210, 180, 140],
  1440. "teal": [0, 128, 128],
  1441. "thistle": [216, 191, 216],
  1442. "tomato": [255, 99, 71],
  1443. "turquoise": [64, 224, 208],
  1444. "violet": [238, 130, 238],
  1445. "wheat": [245, 222, 179],
  1446. "white": [255, 255, 255],
  1447. "whitesmoke": [245, 245, 245],
  1448. "yellow": [255, 255, 0],
  1449. "yellowgreen": [154, 205, 50]
  1450. };
  1451. },{}],6:[function(require,module,exports){
  1452. //! moment.js
  1453. ;(function (global, factory) {
  1454. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  1455. typeof define === 'function' && define.amd ? define(factory) :
  1456. global.moment = factory()
  1457. }(this, (function () { 'use strict';
  1458. var hookCallback;
  1459. function hooks () {
  1460. return hookCallback.apply(null, arguments);
  1461. }
  1462. // This is done to register the method called with moment()
  1463. // without creating circular dependencies.
  1464. function setHookCallback (callback) {
  1465. hookCallback = callback;
  1466. }
  1467. function isArray(input) {
  1468. return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
  1469. }
  1470. function isObject(input) {
  1471. // IE8 will treat undefined and null as object if it wasn't for
  1472. // input != null
  1473. return input != null && Object.prototype.toString.call(input) === '[object Object]';
  1474. }
  1475. function isObjectEmpty(obj) {
  1476. if (Object.getOwnPropertyNames) {
  1477. return (Object.getOwnPropertyNames(obj).length === 0);
  1478. } else {
  1479. var k;
  1480. for (k in obj) {
  1481. if (obj.hasOwnProperty(k)) {
  1482. return false;
  1483. }
  1484. }
  1485. return true;
  1486. }
  1487. }
  1488. function isUndefined(input) {
  1489. return input === void 0;
  1490. }
  1491. function isNumber(input) {
  1492. return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
  1493. }
  1494. function isDate(input) {
  1495. return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
  1496. }
  1497. function map(arr, fn) {
  1498. var res = [], i;
  1499. for (i = 0; i < arr.length; ++i) {
  1500. res.push(fn(arr[i], i));
  1501. }
  1502. return res;
  1503. }
  1504. function hasOwnProp(a, b) {
  1505. return Object.prototype.hasOwnProperty.call(a, b);
  1506. }
  1507. function extend(a, b) {
  1508. for (var i in b) {
  1509. if (hasOwnProp(b, i)) {
  1510. a[i] = b[i];
  1511. }
  1512. }
  1513. if (hasOwnProp(b, 'toString')) {
  1514. a.toString = b.toString;
  1515. }
  1516. if (hasOwnProp(b, 'valueOf')) {
  1517. a.valueOf = b.valueOf;
  1518. }
  1519. return a;
  1520. }
  1521. function createUTC (input, format, locale, strict) {
  1522. return createLocalOrUTC(input, format, locale, strict, true).utc();
  1523. }
  1524. function defaultParsingFlags() {
  1525. // We need to deep clone this object.
  1526. return {
  1527. empty : false,
  1528. unusedTokens : [],
  1529. unusedInput : [],
  1530. overflow : -2,
  1531. charsLeftOver : 0,
  1532. nullInput : false,
  1533. invalidMonth : null,
  1534. invalidFormat : false,
  1535. userInvalidated : false,
  1536. iso : false,
  1537. parsedDateParts : [],
  1538. meridiem : null,
  1539. rfc2822 : false,
  1540. weekdayMismatch : false
  1541. };
  1542. }
  1543. function getParsingFlags(m) {
  1544. if (m._pf == null) {
  1545. m._pf = defaultParsingFlags();
  1546. }
  1547. return m._pf;
  1548. }
  1549. var some;
  1550. if (Array.prototype.some) {
  1551. some = Array.prototype.some;
  1552. } else {
  1553. some = function (fun) {
  1554. var t = Object(this);
  1555. var len = t.length >>> 0;
  1556. for (var i = 0; i < len; i++) {
  1557. if (i in t && fun.call(this, t[i], i, t)) {
  1558. return true;
  1559. }
  1560. }
  1561. return false;
  1562. };
  1563. }
  1564. function isValid(m) {
  1565. if (m._isValid == null) {
  1566. var flags = getParsingFlags(m);
  1567. var parsedParts = some.call(flags.parsedDateParts, function (i) {
  1568. return i != null;
  1569. });
  1570. var isNowValid = !isNaN(m._d.getTime()) &&
  1571. flags.overflow < 0 &&
  1572. !flags.empty &&
  1573. !flags.invalidMonth &&
  1574. !flags.invalidWeekday &&
  1575. !flags.weekdayMismatch &&
  1576. !flags.nullInput &&
  1577. !flags.invalidFormat &&
  1578. !flags.userInvalidated &&
  1579. (!flags.meridiem || (flags.meridiem && parsedParts));
  1580. if (m._strict) {
  1581. isNowValid = isNowValid &&
  1582. flags.charsLeftOver === 0 &&
  1583. flags.unusedTokens.length === 0 &&
  1584. flags.bigHour === undefined;
  1585. }
  1586. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  1587. m._isValid = isNowValid;
  1588. }
  1589. else {
  1590. return isNowValid;
  1591. }
  1592. }
  1593. return m._isValid;
  1594. }
  1595. function createInvalid (flags) {
  1596. var m = createUTC(NaN);
  1597. if (flags != null) {
  1598. extend(getParsingFlags(m), flags);
  1599. }
  1600. else {
  1601. getParsingFlags(m).userInvalidated = true;
  1602. }
  1603. return m;
  1604. }
  1605. // Plugins that add properties should also add the key here (null value),
  1606. // so we can properly clone ourselves.
  1607. var momentProperties = hooks.momentProperties = [];
  1608. function copyConfig(to, from) {
  1609. var i, prop, val;
  1610. if (!isUndefined(from._isAMomentObject)) {
  1611. to._isAMomentObject = from._isAMomentObject;
  1612. }
  1613. if (!isUndefined(from._i)) {
  1614. to._i = from._i;
  1615. }
  1616. if (!isUndefined(from._f)) {
  1617. to._f = from._f;
  1618. }
  1619. if (!isUndefined(from._l)) {
  1620. to._l = from._l;
  1621. }
  1622. if (!isUndefined(from._strict)) {
  1623. to._strict = from._strict;
  1624. }
  1625. if (!isUndefined(from._tzm)) {
  1626. to._tzm = from._tzm;
  1627. }
  1628. if (!isUndefined(from._isUTC)) {
  1629. to._isUTC = from._isUTC;
  1630. }
  1631. if (!isUndefined(from._offset)) {
  1632. to._offset = from._offset;
  1633. }
  1634. if (!isUndefined(from._pf)) {
  1635. to._pf = getParsingFlags(from);
  1636. }
  1637. if (!isUndefined(from._locale)) {
  1638. to._locale = from._locale;
  1639. }
  1640. if (momentProperties.length > 0) {
  1641. for (i = 0; i < momentProperties.length; i++) {
  1642. prop = momentProperties[i];
  1643. val = from[prop];
  1644. if (!isUndefined(val)) {
  1645. to[prop] = val;
  1646. }
  1647. }
  1648. }
  1649. return to;
  1650. }
  1651. var updateInProgress = false;
  1652. // Moment prototype object
  1653. function Moment(config) {
  1654. copyConfig(this, config);
  1655. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  1656. if (!this.isValid()) {
  1657. this._d = new Date(NaN);
  1658. }
  1659. // Prevent infinite loop in case updateOffset creates new moment
  1660. // objects.
  1661. if (updateInProgress === false) {
  1662. updateInProgress = true;
  1663. hooks.updateOffset(this);
  1664. updateInProgress = false;
  1665. }
  1666. }
  1667. function isMoment (obj) {
  1668. return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
  1669. }
  1670. function absFloor (number) {
  1671. if (number < 0) {
  1672. // -0 -> 0
  1673. return Math.ceil(number) || 0;
  1674. } else {
  1675. return Math.floor(number);
  1676. }
  1677. }
  1678. function toInt(argumentForCoercion) {
  1679. var coercedNumber = +argumentForCoercion,
  1680. value = 0;
  1681. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  1682. value = absFloor(coercedNumber);
  1683. }
  1684. return value;
  1685. }
  1686. // compare two arrays, return the number of differences
  1687. function compareArrays(array1, array2, dontConvert) {
  1688. var len = Math.min(array1.length, array2.length),
  1689. lengthDiff = Math.abs(array1.length - array2.length),
  1690. diffs = 0,
  1691. i;
  1692. for (i = 0; i < len; i++) {
  1693. if ((dontConvert && array1[i] !== array2[i]) ||
  1694. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  1695. diffs++;
  1696. }
  1697. }
  1698. return diffs + lengthDiff;
  1699. }
  1700. function warn(msg) {
  1701. if (hooks.suppressDeprecationWarnings === false &&
  1702. (typeof console !== 'undefined') && console.warn) {
  1703. console.warn('Deprecation warning: ' + msg);
  1704. }
  1705. }
  1706. function deprecate(msg, fn) {
  1707. var firstTime = true;
  1708. return extend(function () {
  1709. if (hooks.deprecationHandler != null) {
  1710. hooks.deprecationHandler(null, msg);
  1711. }
  1712. if (firstTime) {
  1713. var args = [];
  1714. var arg;
  1715. for (var i = 0; i < arguments.length; i++) {
  1716. arg = '';
  1717. if (typeof arguments[i] === 'object') {
  1718. arg += '\n[' + i + '] ';
  1719. for (var key in arguments[0]) {
  1720. arg += key + ': ' + arguments[0][key] + ', ';
  1721. }
  1722. arg = arg.slice(0, -2); // Remove trailing comma and space
  1723. } else {
  1724. arg = arguments[i];
  1725. }
  1726. args.push(arg);
  1727. }
  1728. warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
  1729. firstTime = false;
  1730. }
  1731. return fn.apply(this, arguments);
  1732. }, fn);
  1733. }
  1734. var deprecations = {};
  1735. function deprecateSimple(name, msg) {
  1736. if (hooks.deprecationHandler != null) {
  1737. hooks.deprecationHandler(name, msg);
  1738. }
  1739. if (!deprecations[name]) {
  1740. warn(msg);
  1741. deprecations[name] = true;
  1742. }
  1743. }
  1744. hooks.suppressDeprecationWarnings = false;
  1745. hooks.deprecationHandler = null;
  1746. function isFunction(input) {
  1747. return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
  1748. }
  1749. function set (config) {
  1750. var prop, i;
  1751. for (i in config) {
  1752. prop = config[i];
  1753. if (isFunction(prop)) {
  1754. this[i] = prop;
  1755. } else {
  1756. this['_' + i] = prop;
  1757. }
  1758. }
  1759. this._config = config;
  1760. // Lenient ordinal parsing accepts just a number in addition to
  1761. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  1762. // TODO: Remove "ordinalParse" fallback in next major release.
  1763. this._dayOfMonthOrdinalParseLenient = new RegExp(
  1764. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  1765. '|' + (/\d{1,2}/).source);
  1766. }
  1767. function mergeConfigs(parentConfig, childConfig) {
  1768. var res = extend({}, parentConfig), prop;
  1769. for (prop in childConfig) {
  1770. if (hasOwnProp(childConfig, prop)) {
  1771. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  1772. res[prop] = {};
  1773. extend(res[prop], parentConfig[prop]);
  1774. extend(res[prop], childConfig[prop]);
  1775. } else if (childConfig[prop] != null) {
  1776. res[prop] = childConfig[prop];
  1777. } else {
  1778. delete res[prop];
  1779. }
  1780. }
  1781. }
  1782. for (prop in parentConfig) {
  1783. if (hasOwnProp(parentConfig, prop) &&
  1784. !hasOwnProp(childConfig, prop) &&
  1785. isObject(parentConfig[prop])) {
  1786. // make sure changes to properties don't modify parent config
  1787. res[prop] = extend({}, res[prop]);
  1788. }
  1789. }
  1790. return res;
  1791. }
  1792. function Locale(config) {
  1793. if (config != null) {
  1794. this.set(config);
  1795. }
  1796. }
  1797. var keys;
  1798. if (Object.keys) {
  1799. keys = Object.keys;
  1800. } else {
  1801. keys = function (obj) {
  1802. var i, res = [];
  1803. for (i in obj) {
  1804. if (hasOwnProp(obj, i)) {
  1805. res.push(i);
  1806. }
  1807. }
  1808. return res;
  1809. };
  1810. }
  1811. var defaultCalendar = {
  1812. sameDay : '[Today at] LT',
  1813. nextDay : '[Tomorrow at] LT',
  1814. nextWeek : 'dddd [at] LT',
  1815. lastDay : '[Yesterday at] LT',
  1816. lastWeek : '[Last] dddd [at] LT',
  1817. sameElse : 'L'
  1818. };
  1819. function calendar (key, mom, now) {
  1820. var output = this._calendar[key] || this._calendar['sameElse'];
  1821. return isFunction(output) ? output.call(mom, now) : output;
  1822. }
  1823. var defaultLongDateFormat = {
  1824. LTS : 'h:mm:ss A',
  1825. LT : 'h:mm A',
  1826. L : 'MM/DD/YYYY',
  1827. LL : 'MMMM D, YYYY',
  1828. LLL : 'MMMM D, YYYY h:mm A',
  1829. LLLL : 'dddd, MMMM D, YYYY h:mm A'
  1830. };
  1831. function longDateFormat (key) {
  1832. var format = this._longDateFormat[key],
  1833. formatUpper = this._longDateFormat[key.toUpperCase()];
  1834. if (format || !formatUpper) {
  1835. return format;
  1836. }
  1837. this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
  1838. return val.slice(1);
  1839. });
  1840. return this._longDateFormat[key];
  1841. }
  1842. var defaultInvalidDate = 'Invalid date';
  1843. function invalidDate () {
  1844. return this._invalidDate;
  1845. }
  1846. var defaultOrdinal = '%d';
  1847. var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  1848. function ordinal (number) {
  1849. return this._ordinal.replace('%d', number);
  1850. }
  1851. var defaultRelativeTime = {
  1852. future : 'in %s',
  1853. past : '%s ago',
  1854. s : 'a few seconds',
  1855. ss : '%d seconds',
  1856. m : 'a minute',
  1857. mm : '%d minutes',
  1858. h : 'an hour',
  1859. hh : '%d hours',
  1860. d : 'a day',
  1861. dd : '%d days',
  1862. M : 'a month',
  1863. MM : '%d months',
  1864. y : 'a year',
  1865. yy : '%d years'
  1866. };
  1867. function relativeTime (number, withoutSuffix, string, isFuture) {
  1868. var output = this._relativeTime[string];
  1869. return (isFunction(output)) ?
  1870. output(number, withoutSuffix, string, isFuture) :
  1871. output.replace(/%d/i, number);
  1872. }
  1873. function pastFuture (diff, output) {
  1874. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  1875. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  1876. }
  1877. var aliases = {};
  1878. function addUnitAlias (unit, shorthand) {
  1879. var lowerCase = unit.toLowerCase();
  1880. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  1881. }
  1882. function normalizeUnits(units) {
  1883. return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
  1884. }
  1885. function normalizeObjectUnits(inputObject) {
  1886. var normalizedInput = {},
  1887. normalizedProp,
  1888. prop;
  1889. for (prop in inputObject) {
  1890. if (hasOwnProp(inputObject, prop)) {
  1891. normalizedProp = normalizeUnits(prop);
  1892. if (normalizedProp) {
  1893. normalizedInput[normalizedProp] = inputObject[prop];
  1894. }
  1895. }
  1896. }
  1897. return normalizedInput;
  1898. }
  1899. var priorities = {};
  1900. function addUnitPriority(unit, priority) {
  1901. priorities[unit] = priority;
  1902. }
  1903. function getPrioritizedUnits(unitsObj) {
  1904. var units = [];
  1905. for (var u in unitsObj) {
  1906. units.push({unit: u, priority: priorities[u]});
  1907. }
  1908. units.sort(function (a, b) {
  1909. return a.priority - b.priority;
  1910. });
  1911. return units;
  1912. }
  1913. function zeroFill(number, targetLength, forceSign) {
  1914. var absNumber = '' + Math.abs(number),
  1915. zerosToFill = targetLength - absNumber.length,
  1916. sign = number >= 0;
  1917. return (sign ? (forceSign ? '+' : '') : '-') +
  1918. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
  1919. }
  1920. 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;
  1921. var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  1922. var formatFunctions = {};
  1923. var formatTokenFunctions = {};
  1924. // token: 'M'
  1925. // padded: ['MM', 2]
  1926. // ordinal: 'Mo'
  1927. // callback: function () { this.month() + 1 }
  1928. function addFormatToken (token, padded, ordinal, callback) {
  1929. var func = callback;
  1930. if (typeof callback === 'string') {
  1931. func = function () {
  1932. return this[callback]();
  1933. };
  1934. }
  1935. if (token) {
  1936. formatTokenFunctions[token] = func;
  1937. }
  1938. if (padded) {
  1939. formatTokenFunctions[padded[0]] = function () {
  1940. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  1941. };
  1942. }
  1943. if (ordinal) {
  1944. formatTokenFunctions[ordinal] = function () {
  1945. return this.localeData().ordinal(func.apply(this, arguments), token);
  1946. };
  1947. }
  1948. }
  1949. function removeFormattingTokens(input) {
  1950. if (input.match(/\[[\s\S]/)) {
  1951. return input.replace(/^\[|\]$/g, '');
  1952. }
  1953. return input.replace(/\\/g, '');
  1954. }
  1955. function makeFormatFunction(format) {
  1956. var array = format.match(formattingTokens), i, length;
  1957. for (i = 0, length = array.length; i < length; i++) {
  1958. if (formatTokenFunctions[array[i]]) {
  1959. array[i] = formatTokenFunctions[array[i]];
  1960. } else {
  1961. array[i] = removeFormattingTokens(array[i]);
  1962. }
  1963. }
  1964. return function (mom) {
  1965. var output = '', i;
  1966. for (i = 0; i < length; i++) {
  1967. output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
  1968. }
  1969. return output;
  1970. };
  1971. }
  1972. // format date using native date object
  1973. function formatMoment(m, format) {
  1974. if (!m.isValid()) {
  1975. return m.localeData().invalidDate();
  1976. }
  1977. format = expandFormat(format, m.localeData());
  1978. formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
  1979. return formatFunctions[format](m);
  1980. }
  1981. function expandFormat(format, locale) {
  1982. var i = 5;
  1983. function replaceLongDateFormatTokens(input) {
  1984. return locale.longDateFormat(input) || input;
  1985. }
  1986. localFormattingTokens.lastIndex = 0;
  1987. while (i >= 0 && localFormattingTokens.test(format)) {
  1988. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  1989. localFormattingTokens.lastIndex = 0;
  1990. i -= 1;
  1991. }
  1992. return format;
  1993. }
  1994. var match1 = /\d/; // 0 - 9
  1995. var match2 = /\d\d/; // 00 - 99
  1996. var match3 = /\d{3}/; // 000 - 999
  1997. var match4 = /\d{4}/; // 0000 - 9999
  1998. var match6 = /[+-]?\d{6}/; // -999999 - 999999
  1999. var match1to2 = /\d\d?/; // 0 - 99
  2000. var match3to4 = /\d\d\d\d?/; // 999 - 9999
  2001. var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
  2002. var match1to3 = /\d{1,3}/; // 0 - 999
  2003. var match1to4 = /\d{1,4}/; // 0 - 9999
  2004. var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
  2005. var matchUnsigned = /\d+/; // 0 - inf
  2006. var matchSigned = /[+-]?\d+/; // -inf - inf
  2007. var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
  2008. var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  2009. var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
  2010. // any word (or two) characters or numbers including two/three word month in arabic.
  2011. // includes scottish gaelic two word and hyphenated months
  2012. 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;
  2013. var regexes = {};
  2014. function addRegexToken (token, regex, strictRegex) {
  2015. regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
  2016. return (isStrict && strictRegex) ? strictRegex : regex;
  2017. };
  2018. }
  2019. function getParseRegexForToken (token, config) {
  2020. if (!hasOwnProp(regexes, token)) {
  2021. return new RegExp(unescapeFormat(token));
  2022. }
  2023. return regexes[token](config._strict, config._locale);
  2024. }
  2025. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  2026. function unescapeFormat(s) {
  2027. return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  2028. return p1 || p2 || p3 || p4;
  2029. }));
  2030. }
  2031. function regexEscape(s) {
  2032. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  2033. }
  2034. var tokens = {};
  2035. function addParseToken (token, callback) {
  2036. var i, func = callback;
  2037. if (typeof token === 'string') {
  2038. token = [token];
  2039. }
  2040. if (isNumber(callback)) {
  2041. func = function (input, array) {
  2042. array[callback] = toInt(input);
  2043. };
  2044. }
  2045. for (i = 0; i < token.length; i++) {
  2046. tokens[token[i]] = func;
  2047. }
  2048. }
  2049. function addWeekParseToken (token, callback) {
  2050. addParseToken(token, function (input, array, config, token) {
  2051. config._w = config._w || {};
  2052. callback(input, config._w, config, token);
  2053. });
  2054. }
  2055. function addTimeToArrayFromToken(token, input, config) {
  2056. if (input != null && hasOwnProp(tokens, token)) {
  2057. tokens[token](input, config._a, config, token);
  2058. }
  2059. }
  2060. var YEAR = 0;
  2061. var MONTH = 1;
  2062. var DATE = 2;
  2063. var HOUR = 3;
  2064. var MINUTE = 4;
  2065. var SECOND = 5;
  2066. var MILLISECOND = 6;
  2067. var WEEK = 7;
  2068. var WEEKDAY = 8;
  2069. // FORMATTING
  2070. addFormatToken('Y', 0, 0, function () {
  2071. var y = this.year();
  2072. return y <= 9999 ? '' + y : '+' + y;
  2073. });
  2074. addFormatToken(0, ['YY', 2], 0, function () {
  2075. return this.year() % 100;
  2076. });
  2077. addFormatToken(0, ['YYYY', 4], 0, 'year');
  2078. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  2079. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  2080. // ALIASES
  2081. addUnitAlias('year', 'y');
  2082. // PRIORITIES
  2083. addUnitPriority('year', 1);
  2084. // PARSING
  2085. addRegexToken('Y', matchSigned);
  2086. addRegexToken('YY', match1to2, match2);
  2087. addRegexToken('YYYY', match1to4, match4);
  2088. addRegexToken('YYYYY', match1to6, match6);
  2089. addRegexToken('YYYYYY', match1to6, match6);
  2090. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  2091. addParseToken('YYYY', function (input, array) {
  2092. array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  2093. });
  2094. addParseToken('YY', function (input, array) {
  2095. array[YEAR] = hooks.parseTwoDigitYear(input);
  2096. });
  2097. addParseToken('Y', function (input, array) {
  2098. array[YEAR] = parseInt(input, 10);
  2099. });
  2100. // HELPERS
  2101. function daysInYear(year) {
  2102. return isLeapYear(year) ? 366 : 365;
  2103. }
  2104. function isLeapYear(year) {
  2105. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  2106. }
  2107. // HOOKS
  2108. hooks.parseTwoDigitYear = function (input) {
  2109. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  2110. };
  2111. // MOMENTS
  2112. var getSetYear = makeGetSet('FullYear', true);
  2113. function getIsLeapYear () {
  2114. return isLeapYear(this.year());
  2115. }
  2116. function makeGetSet (unit, keepTime) {
  2117. return function (value) {
  2118. if (value != null) {
  2119. set$1(this, unit, value);
  2120. hooks.updateOffset(this, keepTime);
  2121. return this;
  2122. } else {
  2123. return get(this, unit);
  2124. }
  2125. };
  2126. }
  2127. function get (mom, unit) {
  2128. return mom.isValid() ?
  2129. mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
  2130. }
  2131. function set$1 (mom, unit, value) {
  2132. if (mom.isValid() && !isNaN(value)) {
  2133. if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
  2134. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
  2135. }
  2136. else {
  2137. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  2138. }
  2139. }
  2140. }
  2141. // MOMENTS
  2142. function stringGet (units) {
  2143. units = normalizeUnits(units);
  2144. if (isFunction(this[units])) {
  2145. return this[units]();
  2146. }
  2147. return this;
  2148. }
  2149. function stringSet (units, value) {
  2150. if (typeof units === 'object') {
  2151. units = normalizeObjectUnits(units);
  2152. var prioritized = getPrioritizedUnits(units);
  2153. for (var i = 0; i < prioritized.length; i++) {
  2154. this[prioritized[i].unit](units[prioritized[i].unit]);
  2155. }
  2156. } else {
  2157. units = normalizeUnits(units);
  2158. if (isFunction(this[units])) {
  2159. return this[units](value);
  2160. }
  2161. }
  2162. return this;
  2163. }
  2164. function mod(n, x) {
  2165. return ((n % x) + x) % x;
  2166. }
  2167. var indexOf;
  2168. if (Array.prototype.indexOf) {
  2169. indexOf = Array.prototype.indexOf;
  2170. } else {
  2171. indexOf = function (o) {
  2172. // I know
  2173. var i;
  2174. for (i = 0; i < this.length; ++i) {
  2175. if (this[i] === o) {
  2176. return i;
  2177. }
  2178. }
  2179. return -1;
  2180. };
  2181. }
  2182. function daysInMonth(year, month) {
  2183. if (isNaN(year) || isNaN(month)) {
  2184. return NaN;
  2185. }
  2186. var modMonth = mod(month, 12);
  2187. year += (month - modMonth) / 12;
  2188. return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
  2189. }
  2190. // FORMATTING
  2191. addFormatToken('M', ['MM', 2], 'Mo', function () {
  2192. return this.month() + 1;
  2193. });
  2194. addFormatToken('MMM', 0, 0, function (format) {
  2195. return this.localeData().monthsShort(this, format);
  2196. });
  2197. addFormatToken('MMMM', 0, 0, function (format) {
  2198. return this.localeData().months(this, format);
  2199. });
  2200. // ALIASES
  2201. addUnitAlias('month', 'M');
  2202. // PRIORITY
  2203. addUnitPriority('month', 8);
  2204. // PARSING
  2205. addRegexToken('M', match1to2);
  2206. addRegexToken('MM', match1to2, match2);
  2207. addRegexToken('MMM', function (isStrict, locale) {
  2208. return locale.monthsShortRegex(isStrict);
  2209. });
  2210. addRegexToken('MMMM', function (isStrict, locale) {
  2211. return locale.monthsRegex(isStrict);
  2212. });
  2213. addParseToken(['M', 'MM'], function (input, array) {
  2214. array[MONTH] = toInt(input) - 1;
  2215. });
  2216. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  2217. var month = config._locale.monthsParse(input, token, config._strict);
  2218. // if we didn't find a month name, mark the date as invalid.
  2219. if (month != null) {
  2220. array[MONTH] = month;
  2221. } else {
  2222. getParsingFlags(config).invalidMonth = input;
  2223. }
  2224. });
  2225. // LOCALES
  2226. var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
  2227. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
  2228. function localeMonths (m, format) {
  2229. if (!m) {
  2230. return isArray(this._months) ? this._months :
  2231. this._months['standalone'];
  2232. }
  2233. return isArray(this._months) ? this._months[m.month()] :
  2234. this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
  2235. }
  2236. var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
  2237. function localeMonthsShort (m, format) {
  2238. if (!m) {
  2239. return isArray(this._monthsShort) ? this._monthsShort :
  2240. this._monthsShort['standalone'];
  2241. }
  2242. return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
  2243. this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
  2244. }
  2245. function handleStrictParse(monthName, format, strict) {
  2246. var i, ii, mom, llc = monthName.toLocaleLowerCase();
  2247. if (!this._monthsParse) {
  2248. // this is not used
  2249. this._monthsParse = [];
  2250. this._longMonthsParse = [];
  2251. this._shortMonthsParse = [];
  2252. for (i = 0; i < 12; ++i) {
  2253. mom = createUTC([2000, i]);
  2254. this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
  2255. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  2256. }
  2257. }
  2258. if (strict) {
  2259. if (format === 'MMM') {
  2260. ii = indexOf.call(this._shortMonthsParse, llc);
  2261. return ii !== -1 ? ii : null;
  2262. } else {
  2263. ii = indexOf.call(this._longMonthsParse, llc);
  2264. return ii !== -1 ? ii : null;
  2265. }
  2266. } else {
  2267. if (format === 'MMM') {
  2268. ii = indexOf.call(this._shortMonthsParse, llc);
  2269. if (ii !== -1) {
  2270. return ii;
  2271. }
  2272. ii = indexOf.call(this._longMonthsParse, llc);
  2273. return ii !== -1 ? ii : null;
  2274. } else {
  2275. ii = indexOf.call(this._longMonthsParse, llc);
  2276. if (ii !== -1) {
  2277. return ii;
  2278. }
  2279. ii = indexOf.call(this._shortMonthsParse, llc);
  2280. return ii !== -1 ? ii : null;
  2281. }
  2282. }
  2283. }
  2284. function localeMonthsParse (monthName, format, strict) {
  2285. var i, mom, regex;
  2286. if (this._monthsParseExact) {
  2287. return handleStrictParse.call(this, monthName, format, strict);
  2288. }
  2289. if (!this._monthsParse) {
  2290. this._monthsParse = [];
  2291. this._longMonthsParse = [];
  2292. this._shortMonthsParse = [];
  2293. }
  2294. // TODO: add sorting
  2295. // Sorting makes sure if one month (or abbr) is a prefix of another
  2296. // see sorting in computeMonthsParse
  2297. for (i = 0; i < 12; i++) {
  2298. // make the regex if we don't have it already
  2299. mom = createUTC([2000, i]);
  2300. if (strict && !this._longMonthsParse[i]) {
  2301. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  2302. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  2303. }
  2304. if (!strict && !this._monthsParse[i]) {
  2305. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  2306. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  2307. }
  2308. // test the regex
  2309. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  2310. return i;
  2311. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  2312. return i;
  2313. } else if (!strict && this._monthsParse[i].test(monthName)) {
  2314. return i;
  2315. }
  2316. }
  2317. }
  2318. // MOMENTS
  2319. function setMonth (mom, value) {
  2320. var dayOfMonth;
  2321. if (!mom.isValid()) {
  2322. // No op
  2323. return mom;
  2324. }
  2325. if (typeof value === 'string') {
  2326. if (/^\d+$/.test(value)) {
  2327. value = toInt(value);
  2328. } else {
  2329. value = mom.localeData().monthsParse(value);
  2330. // TODO: Another silent failure?
  2331. if (!isNumber(value)) {
  2332. return mom;
  2333. }
  2334. }
  2335. }
  2336. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  2337. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  2338. return mom;
  2339. }
  2340. function getSetMonth (value) {
  2341. if (value != null) {
  2342. setMonth(this, value);
  2343. hooks.updateOffset(this, true);
  2344. return this;
  2345. } else {
  2346. return get(this, 'Month');
  2347. }
  2348. }
  2349. function getDaysInMonth () {
  2350. return daysInMonth(this.year(), this.month());
  2351. }
  2352. var defaultMonthsShortRegex = matchWord;
  2353. function monthsShortRegex (isStrict) {
  2354. if (this._monthsParseExact) {
  2355. if (!hasOwnProp(this, '_monthsRegex')) {
  2356. computeMonthsParse.call(this);
  2357. }
  2358. if (isStrict) {
  2359. return this._monthsShortStrictRegex;
  2360. } else {
  2361. return this._monthsShortRegex;
  2362. }
  2363. } else {
  2364. if (!hasOwnProp(this, '_monthsShortRegex')) {
  2365. this._monthsShortRegex = defaultMonthsShortRegex;
  2366. }
  2367. return this._monthsShortStrictRegex && isStrict ?
  2368. this._monthsShortStrictRegex : this._monthsShortRegex;
  2369. }
  2370. }
  2371. var defaultMonthsRegex = matchWord;
  2372. function monthsRegex (isStrict) {
  2373. if (this._monthsParseExact) {
  2374. if (!hasOwnProp(this, '_monthsRegex')) {
  2375. computeMonthsParse.call(this);
  2376. }
  2377. if (isStrict) {
  2378. return this._monthsStrictRegex;
  2379. } else {
  2380. return this._monthsRegex;
  2381. }
  2382. } else {
  2383. if (!hasOwnProp(this, '_monthsRegex')) {
  2384. this._monthsRegex = defaultMonthsRegex;
  2385. }
  2386. return this._monthsStrictRegex && isStrict ?
  2387. this._monthsStrictRegex : this._monthsRegex;
  2388. }
  2389. }
  2390. function computeMonthsParse () {
  2391. function cmpLenRev(a, b) {
  2392. return b.length - a.length;
  2393. }
  2394. var shortPieces = [], longPieces = [], mixedPieces = [],
  2395. i, mom;
  2396. for (i = 0; i < 12; i++) {
  2397. // make the regex if we don't have it already
  2398. mom = createUTC([2000, i]);
  2399. shortPieces.push(this.monthsShort(mom, ''));
  2400. longPieces.push(this.months(mom, ''));
  2401. mixedPieces.push(this.months(mom, ''));
  2402. mixedPieces.push(this.monthsShort(mom, ''));
  2403. }
  2404. // Sorting makes sure if one month (or abbr) is a prefix of another it
  2405. // will match the longer piece.
  2406. shortPieces.sort(cmpLenRev);
  2407. longPieces.sort(cmpLenRev);
  2408. mixedPieces.sort(cmpLenRev);
  2409. for (i = 0; i < 12; i++) {
  2410. shortPieces[i] = regexEscape(shortPieces[i]);
  2411. longPieces[i] = regexEscape(longPieces[i]);
  2412. }
  2413. for (i = 0; i < 24; i++) {
  2414. mixedPieces[i] = regexEscape(mixedPieces[i]);
  2415. }
  2416. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  2417. this._monthsShortRegex = this._monthsRegex;
  2418. this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  2419. this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  2420. }
  2421. function createDate (y, m, d, h, M, s, ms) {
  2422. // can't just apply() to create a date:
  2423. // https://stackoverflow.com/q/181348
  2424. var date = new Date(y, m, d, h, M, s, ms);
  2425. // the date constructor remaps years 0-99 to 1900-1999
  2426. if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
  2427. date.setFullYear(y);
  2428. }
  2429. return date;
  2430. }
  2431. function createUTCDate (y) {
  2432. var date = new Date(Date.UTC.apply(null, arguments));
  2433. // the Date.UTC function remaps years 0-99 to 1900-1999
  2434. if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
  2435. date.setUTCFullYear(y);
  2436. }
  2437. return date;
  2438. }
  2439. // start-of-first-week - start-of-year
  2440. function firstWeekOffset(year, dow, doy) {
  2441. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  2442. fwd = 7 + dow - doy,
  2443. // first-week day local weekday -- which local weekday is fwd
  2444. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  2445. return -fwdlw + fwd - 1;
  2446. }
  2447. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  2448. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  2449. var localWeekday = (7 + weekday - dow) % 7,
  2450. weekOffset = firstWeekOffset(year, dow, doy),
  2451. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  2452. resYear, resDayOfYear;
  2453. if (dayOfYear <= 0) {
  2454. resYear = year - 1;
  2455. resDayOfYear = daysInYear(resYear) + dayOfYear;
  2456. } else if (dayOfYear > daysInYear(year)) {
  2457. resYear = year + 1;
  2458. resDayOfYear = dayOfYear - daysInYear(year);
  2459. } else {
  2460. resYear = year;
  2461. resDayOfYear = dayOfYear;
  2462. }
  2463. return {
  2464. year: resYear,
  2465. dayOfYear: resDayOfYear
  2466. };
  2467. }
  2468. function weekOfYear(mom, dow, doy) {
  2469. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  2470. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  2471. resWeek, resYear;
  2472. if (week < 1) {
  2473. resYear = mom.year() - 1;
  2474. resWeek = week + weeksInYear(resYear, dow, doy);
  2475. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  2476. resWeek = week - weeksInYear(mom.year(), dow, doy);
  2477. resYear = mom.year() + 1;
  2478. } else {
  2479. resYear = mom.year();
  2480. resWeek = week;
  2481. }
  2482. return {
  2483. week: resWeek,
  2484. year: resYear
  2485. };
  2486. }
  2487. function weeksInYear(year, dow, doy) {
  2488. var weekOffset = firstWeekOffset(year, dow, doy),
  2489. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  2490. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  2491. }
  2492. // FORMATTING
  2493. addFormatToken('w', ['ww', 2], 'wo', 'week');
  2494. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  2495. // ALIASES
  2496. addUnitAlias('week', 'w');
  2497. addUnitAlias('isoWeek', 'W');
  2498. // PRIORITIES
  2499. addUnitPriority('week', 5);
  2500. addUnitPriority('isoWeek', 5);
  2501. // PARSING
  2502. addRegexToken('w', match1to2);
  2503. addRegexToken('ww', match1to2, match2);
  2504. addRegexToken('W', match1to2);
  2505. addRegexToken('WW', match1to2, match2);
  2506. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
  2507. week[token.substr(0, 1)] = toInt(input);
  2508. });
  2509. // HELPERS
  2510. // LOCALES
  2511. function localeWeek (mom) {
  2512. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  2513. }
  2514. var defaultLocaleWeek = {
  2515. dow : 0, // Sunday is the first day of the week.
  2516. doy : 6 // The week that contains Jan 1st is the first week of the year.
  2517. };
  2518. function localeFirstDayOfWeek () {
  2519. return this._week.dow;
  2520. }
  2521. function localeFirstDayOfYear () {
  2522. return this._week.doy;
  2523. }
  2524. // MOMENTS
  2525. function getSetWeek (input) {
  2526. var week = this.localeData().week(this);
  2527. return input == null ? week : this.add((input - week) * 7, 'd');
  2528. }
  2529. function getSetISOWeek (input) {
  2530. var week = weekOfYear(this, 1, 4).week;
  2531. return input == null ? week : this.add((input - week) * 7, 'd');
  2532. }
  2533. // FORMATTING
  2534. addFormatToken('d', 0, 'do', 'day');
  2535. addFormatToken('dd', 0, 0, function (format) {
  2536. return this.localeData().weekdaysMin(this, format);
  2537. });
  2538. addFormatToken('ddd', 0, 0, function (format) {
  2539. return this.localeData().weekdaysShort(this, format);
  2540. });
  2541. addFormatToken('dddd', 0, 0, function (format) {
  2542. return this.localeData().weekdays(this, format);
  2543. });
  2544. addFormatToken('e', 0, 0, 'weekday');
  2545. addFormatToken('E', 0, 0, 'isoWeekday');
  2546. // ALIASES
  2547. addUnitAlias('day', 'd');
  2548. addUnitAlias('weekday', 'e');
  2549. addUnitAlias('isoWeekday', 'E');
  2550. // PRIORITY
  2551. addUnitPriority('day', 11);
  2552. addUnitPriority('weekday', 11);
  2553. addUnitPriority('isoWeekday', 11);
  2554. // PARSING
  2555. addRegexToken('d', match1to2);
  2556. addRegexToken('e', match1to2);
  2557. addRegexToken('E', match1to2);
  2558. addRegexToken('dd', function (isStrict, locale) {
  2559. return locale.weekdaysMinRegex(isStrict);
  2560. });
  2561. addRegexToken('ddd', function (isStrict, locale) {
  2562. return locale.weekdaysShortRegex(isStrict);
  2563. });
  2564. addRegexToken('dddd', function (isStrict, locale) {
  2565. return locale.weekdaysRegex(isStrict);
  2566. });
  2567. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  2568. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  2569. // if we didn't get a weekday name, mark the date as invalid
  2570. if (weekday != null) {
  2571. week.d = weekday;
  2572. } else {
  2573. getParsingFlags(config).invalidWeekday = input;
  2574. }
  2575. });
  2576. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  2577. week[token] = toInt(input);
  2578. });
  2579. // HELPERS
  2580. function parseWeekday(input, locale) {
  2581. if (typeof input !== 'string') {
  2582. return input;
  2583. }
  2584. if (!isNaN(input)) {
  2585. return parseInt(input, 10);
  2586. }
  2587. input = locale.weekdaysParse(input);
  2588. if (typeof input === 'number') {
  2589. return input;
  2590. }
  2591. return null;
  2592. }
  2593. function parseIsoWeekday(input, locale) {
  2594. if (typeof input === 'string') {
  2595. return locale.weekdaysParse(input) % 7 || 7;
  2596. }
  2597. return isNaN(input) ? null : input;
  2598. }
  2599. // LOCALES
  2600. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
  2601. function localeWeekdays (m, format) {
  2602. if (!m) {
  2603. return isArray(this._weekdays) ? this._weekdays :
  2604. this._weekdays['standalone'];
  2605. }
  2606. return isArray(this._weekdays) ? this._weekdays[m.day()] :
  2607. this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
  2608. }
  2609. var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
  2610. function localeWeekdaysShort (m) {
  2611. return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
  2612. }
  2613. var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
  2614. function localeWeekdaysMin (m) {
  2615. return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
  2616. }
  2617. function handleStrictParse$1(weekdayName, format, strict) {
  2618. var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
  2619. if (!this._weekdaysParse) {
  2620. this._weekdaysParse = [];
  2621. this._shortWeekdaysParse = [];
  2622. this._minWeekdaysParse = [];
  2623. for (i = 0; i < 7; ++i) {
  2624. mom = createUTC([2000, 1]).day(i);
  2625. this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
  2626. this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
  2627. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  2628. }
  2629. }
  2630. if (strict) {
  2631. if (format === 'dddd') {
  2632. ii = indexOf.call(this._weekdaysParse, llc);
  2633. return ii !== -1 ? ii : null;
  2634. } else if (format === 'ddd') {
  2635. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2636. return ii !== -1 ? ii : null;
  2637. } else {
  2638. ii = indexOf.call(this._minWeekdaysParse, llc);
  2639. return ii !== -1 ? ii : null;
  2640. }
  2641. } else {
  2642. if (format === 'dddd') {
  2643. ii = indexOf.call(this._weekdaysParse, llc);
  2644. if (ii !== -1) {
  2645. return ii;
  2646. }
  2647. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2648. if (ii !== -1) {
  2649. return ii;
  2650. }
  2651. ii = indexOf.call(this._minWeekdaysParse, llc);
  2652. return ii !== -1 ? ii : null;
  2653. } else if (format === 'ddd') {
  2654. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2655. if (ii !== -1) {
  2656. return ii;
  2657. }
  2658. ii = indexOf.call(this._weekdaysParse, llc);
  2659. if (ii !== -1) {
  2660. return ii;
  2661. }
  2662. ii = indexOf.call(this._minWeekdaysParse, llc);
  2663. return ii !== -1 ? ii : null;
  2664. } else {
  2665. ii = indexOf.call(this._minWeekdaysParse, llc);
  2666. if (ii !== -1) {
  2667. return ii;
  2668. }
  2669. ii = indexOf.call(this._weekdaysParse, llc);
  2670. if (ii !== -1) {
  2671. return ii;
  2672. }
  2673. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2674. return ii !== -1 ? ii : null;
  2675. }
  2676. }
  2677. }
  2678. function localeWeekdaysParse (weekdayName, format, strict) {
  2679. var i, mom, regex;
  2680. if (this._weekdaysParseExact) {
  2681. return handleStrictParse$1.call(this, weekdayName, format, strict);
  2682. }
  2683. if (!this._weekdaysParse) {
  2684. this._weekdaysParse = [];
  2685. this._minWeekdaysParse = [];
  2686. this._shortWeekdaysParse = [];
  2687. this._fullWeekdaysParse = [];
  2688. }
  2689. for (i = 0; i < 7; i++) {
  2690. // make the regex if we don't have it already
  2691. mom = createUTC([2000, 1]).day(i);
  2692. if (strict && !this._fullWeekdaysParse[i]) {
  2693. this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
  2694. this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
  2695. this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
  2696. }
  2697. if (!this._weekdaysParse[i]) {
  2698. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  2699. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  2700. }
  2701. // test the regex
  2702. if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
  2703. return i;
  2704. } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
  2705. return i;
  2706. } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
  2707. return i;
  2708. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  2709. return i;
  2710. }
  2711. }
  2712. }
  2713. // MOMENTS
  2714. function getSetDayOfWeek (input) {
  2715. if (!this.isValid()) {
  2716. return input != null ? this : NaN;
  2717. }
  2718. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  2719. if (input != null) {
  2720. input = parseWeekday(input, this.localeData());
  2721. return this.add(input - day, 'd');
  2722. } else {
  2723. return day;
  2724. }
  2725. }
  2726. function getSetLocaleDayOfWeek (input) {
  2727. if (!this.isValid()) {
  2728. return input != null ? this : NaN;
  2729. }
  2730. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  2731. return input == null ? weekday : this.add(input - weekday, 'd');
  2732. }
  2733. function getSetISODayOfWeek (input) {
  2734. if (!this.isValid()) {
  2735. return input != null ? this : NaN;
  2736. }
  2737. // behaves the same as moment#day except
  2738. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  2739. // as a setter, sunday should belong to the previous week.
  2740. if (input != null) {
  2741. var weekday = parseIsoWeekday(input, this.localeData());
  2742. return this.day(this.day() % 7 ? weekday : weekday - 7);
  2743. } else {
  2744. return this.day() || 7;
  2745. }
  2746. }
  2747. var defaultWeekdaysRegex = matchWord;
  2748. function weekdaysRegex (isStrict) {
  2749. if (this._weekdaysParseExact) {
  2750. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2751. computeWeekdaysParse.call(this);
  2752. }
  2753. if (isStrict) {
  2754. return this._weekdaysStrictRegex;
  2755. } else {
  2756. return this._weekdaysRegex;
  2757. }
  2758. } else {
  2759. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2760. this._weekdaysRegex = defaultWeekdaysRegex;
  2761. }
  2762. return this._weekdaysStrictRegex && isStrict ?
  2763. this._weekdaysStrictRegex : this._weekdaysRegex;
  2764. }
  2765. }
  2766. var defaultWeekdaysShortRegex = matchWord;
  2767. function weekdaysShortRegex (isStrict) {
  2768. if (this._weekdaysParseExact) {
  2769. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2770. computeWeekdaysParse.call(this);
  2771. }
  2772. if (isStrict) {
  2773. return this._weekdaysShortStrictRegex;
  2774. } else {
  2775. return this._weekdaysShortRegex;
  2776. }
  2777. } else {
  2778. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  2779. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  2780. }
  2781. return this._weekdaysShortStrictRegex && isStrict ?
  2782. this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
  2783. }
  2784. }
  2785. var defaultWeekdaysMinRegex = matchWord;
  2786. function weekdaysMinRegex (isStrict) {
  2787. if (this._weekdaysParseExact) {
  2788. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2789. computeWeekdaysParse.call(this);
  2790. }
  2791. if (isStrict) {
  2792. return this._weekdaysMinStrictRegex;
  2793. } else {
  2794. return this._weekdaysMinRegex;
  2795. }
  2796. } else {
  2797. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  2798. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  2799. }
  2800. return this._weekdaysMinStrictRegex && isStrict ?
  2801. this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
  2802. }
  2803. }
  2804. function computeWeekdaysParse () {
  2805. function cmpLenRev(a, b) {
  2806. return b.length - a.length;
  2807. }
  2808. var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
  2809. i, mom, minp, shortp, longp;
  2810. for (i = 0; i < 7; i++) {
  2811. // make the regex if we don't have it already
  2812. mom = createUTC([2000, 1]).day(i);
  2813. minp = this.weekdaysMin(mom, '');
  2814. shortp = this.weekdaysShort(mom, '');
  2815. longp = this.weekdays(mom, '');
  2816. minPieces.push(minp);
  2817. shortPieces.push(shortp);
  2818. longPieces.push(longp);
  2819. mixedPieces.push(minp);
  2820. mixedPieces.push(shortp);
  2821. mixedPieces.push(longp);
  2822. }
  2823. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  2824. // will match the longer piece.
  2825. minPieces.sort(cmpLenRev);
  2826. shortPieces.sort(cmpLenRev);
  2827. longPieces.sort(cmpLenRev);
  2828. mixedPieces.sort(cmpLenRev);
  2829. for (i = 0; i < 7; i++) {
  2830. shortPieces[i] = regexEscape(shortPieces[i]);
  2831. longPieces[i] = regexEscape(longPieces[i]);
  2832. mixedPieces[i] = regexEscape(mixedPieces[i]);
  2833. }
  2834. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  2835. this._weekdaysShortRegex = this._weekdaysRegex;
  2836. this._weekdaysMinRegex = this._weekdaysRegex;
  2837. this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  2838. this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  2839. this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
  2840. }
  2841. // FORMATTING
  2842. function hFormat() {
  2843. return this.hours() % 12 || 12;
  2844. }
  2845. function kFormat() {
  2846. return this.hours() || 24;
  2847. }
  2848. addFormatToken('H', ['HH', 2], 0, 'hour');
  2849. addFormatToken('h', ['hh', 2], 0, hFormat);
  2850. addFormatToken('k', ['kk', 2], 0, kFormat);
  2851. addFormatToken('hmm', 0, 0, function () {
  2852. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  2853. });
  2854. addFormatToken('hmmss', 0, 0, function () {
  2855. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
  2856. zeroFill(this.seconds(), 2);
  2857. });
  2858. addFormatToken('Hmm', 0, 0, function () {
  2859. return '' + this.hours() + zeroFill(this.minutes(), 2);
  2860. });
  2861. addFormatToken('Hmmss', 0, 0, function () {
  2862. return '' + this.hours() + zeroFill(this.minutes(), 2) +
  2863. zeroFill(this.seconds(), 2);
  2864. });
  2865. function meridiem (token, lowercase) {
  2866. addFormatToken(token, 0, 0, function () {
  2867. return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
  2868. });
  2869. }
  2870. meridiem('a', true);
  2871. meridiem('A', false);
  2872. // ALIASES
  2873. addUnitAlias('hour', 'h');
  2874. // PRIORITY
  2875. addUnitPriority('hour', 13);
  2876. // PARSING
  2877. function matchMeridiem (isStrict, locale) {
  2878. return locale._meridiemParse;
  2879. }
  2880. addRegexToken('a', matchMeridiem);
  2881. addRegexToken('A', matchMeridiem);
  2882. addRegexToken('H', match1to2);
  2883. addRegexToken('h', match1to2);
  2884. addRegexToken('k', match1to2);
  2885. addRegexToken('HH', match1to2, match2);
  2886. addRegexToken('hh', match1to2, match2);
  2887. addRegexToken('kk', match1to2, match2);
  2888. addRegexToken('hmm', match3to4);
  2889. addRegexToken('hmmss', match5to6);
  2890. addRegexToken('Hmm', match3to4);
  2891. addRegexToken('Hmmss', match5to6);
  2892. addParseToken(['H', 'HH'], HOUR);
  2893. addParseToken(['k', 'kk'], function (input, array, config) {
  2894. var kInput = toInt(input);
  2895. array[HOUR] = kInput === 24 ? 0 : kInput;
  2896. });
  2897. addParseToken(['a', 'A'], function (input, array, config) {
  2898. config._isPm = config._locale.isPM(input);
  2899. config._meridiem = input;
  2900. });
  2901. addParseToken(['h', 'hh'], function (input, array, config) {
  2902. array[HOUR] = toInt(input);
  2903. getParsingFlags(config).bigHour = true;
  2904. });
  2905. addParseToken('hmm', function (input, array, config) {
  2906. var pos = input.length - 2;
  2907. array[HOUR] = toInt(input.substr(0, pos));
  2908. array[MINUTE] = toInt(input.substr(pos));
  2909. getParsingFlags(config).bigHour = true;
  2910. });
  2911. addParseToken('hmmss', function (input, array, config) {
  2912. var pos1 = input.length - 4;
  2913. var pos2 = input.length - 2;
  2914. array[HOUR] = toInt(input.substr(0, pos1));
  2915. array[MINUTE] = toInt(input.substr(pos1, 2));
  2916. array[SECOND] = toInt(input.substr(pos2));
  2917. getParsingFlags(config).bigHour = true;
  2918. });
  2919. addParseToken('Hmm', function (input, array, config) {
  2920. var pos = input.length - 2;
  2921. array[HOUR] = toInt(input.substr(0, pos));
  2922. array[MINUTE] = toInt(input.substr(pos));
  2923. });
  2924. addParseToken('Hmmss', function (input, array, config) {
  2925. var pos1 = input.length - 4;
  2926. var pos2 = input.length - 2;
  2927. array[HOUR] = toInt(input.substr(0, pos1));
  2928. array[MINUTE] = toInt(input.substr(pos1, 2));
  2929. array[SECOND] = toInt(input.substr(pos2));
  2930. });
  2931. // LOCALES
  2932. function localeIsPM (input) {
  2933. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  2934. // Using charAt should be more compatible.
  2935. return ((input + '').toLowerCase().charAt(0) === 'p');
  2936. }
  2937. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  2938. function localeMeridiem (hours, minutes, isLower) {
  2939. if (hours > 11) {
  2940. return isLower ? 'pm' : 'PM';
  2941. } else {
  2942. return isLower ? 'am' : 'AM';
  2943. }
  2944. }
  2945. // MOMENTS
  2946. // Setting the hour should keep the time, because the user explicitly
  2947. // specified which hour they want. So trying to maintain the same hour (in
  2948. // a new timezone) makes sense. Adding/subtracting hours does not follow
  2949. // this rule.
  2950. var getSetHour = makeGetSet('Hours', true);
  2951. var baseConfig = {
  2952. calendar: defaultCalendar,
  2953. longDateFormat: defaultLongDateFormat,
  2954. invalidDate: defaultInvalidDate,
  2955. ordinal: defaultOrdinal,
  2956. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  2957. relativeTime: defaultRelativeTime,
  2958. months: defaultLocaleMonths,
  2959. monthsShort: defaultLocaleMonthsShort,
  2960. week: defaultLocaleWeek,
  2961. weekdays: defaultLocaleWeekdays,
  2962. weekdaysMin: defaultLocaleWeekdaysMin,
  2963. weekdaysShort: defaultLocaleWeekdaysShort,
  2964. meridiemParse: defaultLocaleMeridiemParse
  2965. };
  2966. // internal storage for locale config files
  2967. var locales = {};
  2968. var localeFamilies = {};
  2969. var globalLocale;
  2970. function normalizeLocale(key) {
  2971. return key ? key.toLowerCase().replace('_', '-') : key;
  2972. }
  2973. // pick the locale from the array
  2974. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  2975. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  2976. function chooseLocale(names) {
  2977. var i = 0, j, next, locale, split;
  2978. while (i < names.length) {
  2979. split = normalizeLocale(names[i]).split('-');
  2980. j = split.length;
  2981. next = normalizeLocale(names[i + 1]);
  2982. next = next ? next.split('-') : null;
  2983. while (j > 0) {
  2984. locale = loadLocale(split.slice(0, j).join('-'));
  2985. if (locale) {
  2986. return locale;
  2987. }
  2988. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  2989. //the next array item is better than a shallower substring of this one
  2990. break;
  2991. }
  2992. j--;
  2993. }
  2994. i++;
  2995. }
  2996. return globalLocale;
  2997. }
  2998. function loadLocale(name) {
  2999. var oldLocale = null;
  3000. // TODO: Find a better way to register and load all the locales in Node
  3001. if (!locales[name] && (typeof module !== 'undefined') &&
  3002. module && module.exports) {
  3003. try {
  3004. oldLocale = globalLocale._abbr;
  3005. var aliasedRequire = require;
  3006. aliasedRequire('./locale/' + name);
  3007. getSetGlobalLocale(oldLocale);
  3008. } catch (e) {}
  3009. }
  3010. return locales[name];
  3011. }
  3012. // This function will load locale and then set the global locale. If
  3013. // no arguments are passed in, it will simply return the current global
  3014. // locale key.
  3015. function getSetGlobalLocale (key, values) {
  3016. var data;
  3017. if (key) {
  3018. if (isUndefined(values)) {
  3019. data = getLocale(key);
  3020. }
  3021. else {
  3022. data = defineLocale(key, values);
  3023. }
  3024. if (data) {
  3025. // moment.duration._locale = moment._locale = data;
  3026. globalLocale = data;
  3027. }
  3028. else {
  3029. if ((typeof console !== 'undefined') && console.warn) {
  3030. //warn user if arguments are passed but the locale could not be set
  3031. console.warn('Locale ' + key + ' not found. Did you forget to load it?');
  3032. }
  3033. }
  3034. }
  3035. return globalLocale._abbr;
  3036. }
  3037. function defineLocale (name, config) {
  3038. if (config !== null) {
  3039. var locale, parentConfig = baseConfig;
  3040. config.abbr = name;
  3041. if (locales[name] != null) {
  3042. deprecateSimple('defineLocaleOverride',
  3043. 'use moment.updateLocale(localeName, config) to change ' +
  3044. 'an existing locale. moment.defineLocale(localeName, ' +
  3045. 'config) should only be used for creating a new locale ' +
  3046. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
  3047. parentConfig = locales[name]._config;
  3048. } else if (config.parentLocale != null) {
  3049. if (locales[config.parentLocale] != null) {
  3050. parentConfig = locales[config.parentLocale]._config;
  3051. } else {
  3052. locale = loadLocale(config.parentLocale);
  3053. if (locale != null) {
  3054. parentConfig = locale._config;
  3055. } else {
  3056. if (!localeFamilies[config.parentLocale]) {
  3057. localeFamilies[config.parentLocale] = [];
  3058. }
  3059. localeFamilies[config.parentLocale].push({
  3060. name: name,
  3061. config: config
  3062. });
  3063. return null;
  3064. }
  3065. }
  3066. }
  3067. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  3068. if (localeFamilies[name]) {
  3069. localeFamilies[name].forEach(function (x) {
  3070. defineLocale(x.name, x.config);
  3071. });
  3072. }
  3073. // backwards compat for now: also set the locale
  3074. // make sure we set the locale AFTER all child locales have been
  3075. // created, so we won't end up with the child locale set.
  3076. getSetGlobalLocale(name);
  3077. return locales[name];
  3078. } else {
  3079. // useful for testing
  3080. delete locales[name];
  3081. return null;
  3082. }
  3083. }
  3084. function updateLocale(name, config) {
  3085. if (config != null) {
  3086. var locale, tmpLocale, parentConfig = baseConfig;
  3087. // MERGE
  3088. tmpLocale = loadLocale(name);
  3089. if (tmpLocale != null) {
  3090. parentConfig = tmpLocale._config;
  3091. }
  3092. config = mergeConfigs(parentConfig, config);
  3093. locale = new Locale(config);
  3094. locale.parentLocale = locales[name];
  3095. locales[name] = locale;
  3096. // backwards compat for now: also set the locale
  3097. getSetGlobalLocale(name);
  3098. } else {
  3099. // pass null for config to unupdate, useful for tests
  3100. if (locales[name] != null) {
  3101. if (locales[name].parentLocale != null) {
  3102. locales[name] = locales[name].parentLocale;
  3103. } else if (locales[name] != null) {
  3104. delete locales[name];
  3105. }
  3106. }
  3107. }
  3108. return locales[name];
  3109. }
  3110. // returns locale data
  3111. function getLocale (key) {
  3112. var locale;
  3113. if (key && key._locale && key._locale._abbr) {
  3114. key = key._locale._abbr;
  3115. }
  3116. if (!key) {
  3117. return globalLocale;
  3118. }
  3119. if (!isArray(key)) {
  3120. //short-circuit everything else
  3121. locale = loadLocale(key);
  3122. if (locale) {
  3123. return locale;
  3124. }
  3125. key = [key];
  3126. }
  3127. return chooseLocale(key);
  3128. }
  3129. function listLocales() {
  3130. return keys(locales);
  3131. }
  3132. function checkOverflow (m) {
  3133. var overflow;
  3134. var a = m._a;
  3135. if (a && getParsingFlags(m).overflow === -2) {
  3136. overflow =
  3137. a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
  3138. a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
  3139. a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
  3140. a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
  3141. a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
  3142. a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
  3143. -1;
  3144. if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  3145. overflow = DATE;
  3146. }
  3147. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  3148. overflow = WEEK;
  3149. }
  3150. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  3151. overflow = WEEKDAY;
  3152. }
  3153. getParsingFlags(m).overflow = overflow;
  3154. }
  3155. return m;
  3156. }
  3157. // Pick the first defined of two or three arguments.
  3158. function defaults(a, b, c) {
  3159. if (a != null) {
  3160. return a;
  3161. }
  3162. if (b != null) {
  3163. return b;
  3164. }
  3165. return c;
  3166. }
  3167. function currentDateArray(config) {
  3168. // hooks is actually the exported moment object
  3169. var nowValue = new Date(hooks.now());
  3170. if (config._useUTC) {
  3171. return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
  3172. }
  3173. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  3174. }
  3175. // convert an array to a date.
  3176. // the array should mirror the parameters below
  3177. // note: all values past the year are optional and will default to the lowest possible value.
  3178. // [year, month, day , hour, minute, second, millisecond]
  3179. function configFromArray (config) {
  3180. var i, date, input = [], currentDate, expectedWeekday, yearToUse;
  3181. if (config._d) {
  3182. return;
  3183. }
  3184. currentDate = currentDateArray(config);
  3185. //compute day of the year from weeks and weekdays
  3186. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  3187. dayOfYearFromWeekInfo(config);
  3188. }
  3189. //if the day of the year is set, figure out what it is
  3190. if (config._dayOfYear != null) {
  3191. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  3192. if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
  3193. getParsingFlags(config)._overflowDayOfYear = true;
  3194. }
  3195. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  3196. config._a[MONTH] = date.getUTCMonth();
  3197. config._a[DATE] = date.getUTCDate();
  3198. }
  3199. // Default to current date.
  3200. // * if no year, month, day of month are given, default to today
  3201. // * if day of month is given, default month and year
  3202. // * if month is given, default only year
  3203. // * if year is given, don't default anything
  3204. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  3205. config._a[i] = input[i] = currentDate[i];
  3206. }
  3207. // Zero out whatever was not defaulted, including time
  3208. for (; i < 7; i++) {
  3209. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  3210. }
  3211. // Check for 24:00:00.000
  3212. if (config._a[HOUR] === 24 &&
  3213. config._a[MINUTE] === 0 &&
  3214. config._a[SECOND] === 0 &&
  3215. config._a[MILLISECOND] === 0) {
  3216. config._nextDay = true;
  3217. config._a[HOUR] = 0;
  3218. }
  3219. config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
  3220. expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
  3221. // Apply timezone offset from input. The actual utcOffset can be changed
  3222. // with parseZone.
  3223. if (config._tzm != null) {
  3224. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  3225. }
  3226. if (config._nextDay) {
  3227. config._a[HOUR] = 24;
  3228. }
  3229. // check for mismatching day of week
  3230. if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
  3231. getParsingFlags(config).weekdayMismatch = true;
  3232. }
  3233. }
  3234. function dayOfYearFromWeekInfo(config) {
  3235. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
  3236. w = config._w;
  3237. if (w.GG != null || w.W != null || w.E != null) {
  3238. dow = 1;
  3239. doy = 4;
  3240. // TODO: We need to take the current isoWeekYear, but that depends on
  3241. // how we interpret now (local, utc, fixed offset). So create
  3242. // a now version of current config (take local/utc/offset flags, and
  3243. // create now).
  3244. weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
  3245. week = defaults(w.W, 1);
  3246. weekday = defaults(w.E, 1);
  3247. if (weekday < 1 || weekday > 7) {
  3248. weekdayOverflow = true;
  3249. }
  3250. } else {
  3251. dow = config._locale._week.dow;
  3252. doy = config._locale._week.doy;
  3253. var curWeek = weekOfYear(createLocal(), dow, doy);
  3254. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  3255. // Default to current week.
  3256. week = defaults(w.w, curWeek.week);
  3257. if (w.d != null) {
  3258. // weekday -- low day numbers are considered next week
  3259. weekday = w.d;
  3260. if (weekday < 0 || weekday > 6) {
  3261. weekdayOverflow = true;
  3262. }
  3263. } else if (w.e != null) {
  3264. // local weekday -- counting starts from begining of week
  3265. weekday = w.e + dow;
  3266. if (w.e < 0 || w.e > 6) {
  3267. weekdayOverflow = true;
  3268. }
  3269. } else {
  3270. // default to begining of week
  3271. weekday = dow;
  3272. }
  3273. }
  3274. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  3275. getParsingFlags(config)._overflowWeeks = true;
  3276. } else if (weekdayOverflow != null) {
  3277. getParsingFlags(config)._overflowWeekday = true;
  3278. } else {
  3279. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  3280. config._a[YEAR] = temp.year;
  3281. config._dayOfYear = temp.dayOfYear;
  3282. }
  3283. }
  3284. // iso 8601 regex
  3285. // 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)
  3286. 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)?)?$/;
  3287. 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)?)?$/;
  3288. var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
  3289. var isoDates = [
  3290. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  3291. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  3292. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  3293. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  3294. ['YYYY-DDD', /\d{4}-\d{3}/],
  3295. ['YYYY-MM', /\d{4}-\d\d/, false],
  3296. ['YYYYYYMMDD', /[+-]\d{10}/],
  3297. ['YYYYMMDD', /\d{8}/],
  3298. // YYYYMM is NOT allowed by the standard
  3299. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  3300. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  3301. ['YYYYDDD', /\d{7}/]
  3302. ];
  3303. // iso time formats and regexes
  3304. var isoTimes = [
  3305. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  3306. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  3307. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  3308. ['HH:mm', /\d\d:\d\d/],
  3309. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  3310. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  3311. ['HHmmss', /\d\d\d\d\d\d/],
  3312. ['HHmm', /\d\d\d\d/],
  3313. ['HH', /\d\d/]
  3314. ];
  3315. var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
  3316. // date from iso format
  3317. function configFromISO(config) {
  3318. var i, l,
  3319. string = config._i,
  3320. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  3321. allowTime, dateFormat, timeFormat, tzFormat;
  3322. if (match) {
  3323. getParsingFlags(config).iso = true;
  3324. for (i = 0, l = isoDates.length; i < l; i++) {
  3325. if (isoDates[i][1].exec(match[1])) {
  3326. dateFormat = isoDates[i][0];
  3327. allowTime = isoDates[i][2] !== false;
  3328. break;
  3329. }
  3330. }
  3331. if (dateFormat == null) {
  3332. config._isValid = false;
  3333. return;
  3334. }
  3335. if (match[3]) {
  3336. for (i = 0, l = isoTimes.length; i < l; i++) {
  3337. if (isoTimes[i][1].exec(match[3])) {
  3338. // match[2] should be 'T' or space
  3339. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  3340. break;
  3341. }
  3342. }
  3343. if (timeFormat == null) {
  3344. config._isValid = false;
  3345. return;
  3346. }
  3347. }
  3348. if (!allowTime && timeFormat != null) {
  3349. config._isValid = false;
  3350. return;
  3351. }
  3352. if (match[4]) {
  3353. if (tzRegex.exec(match[4])) {
  3354. tzFormat = 'Z';
  3355. } else {
  3356. config._isValid = false;
  3357. return;
  3358. }
  3359. }
  3360. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  3361. configFromStringAndFormat(config);
  3362. } else {
  3363. config._isValid = false;
  3364. }
  3365. }
  3366. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  3367. 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}))$/;
  3368. function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  3369. var result = [
  3370. untruncateYear(yearStr),
  3371. defaultLocaleMonthsShort.indexOf(monthStr),
  3372. parseInt(dayStr, 10),
  3373. parseInt(hourStr, 10),
  3374. parseInt(minuteStr, 10)
  3375. ];
  3376. if (secondStr) {
  3377. result.push(parseInt(secondStr, 10));
  3378. }
  3379. return result;
  3380. }
  3381. function untruncateYear(yearStr) {
  3382. var year = parseInt(yearStr, 10);
  3383. if (year <= 49) {
  3384. return 2000 + year;
  3385. } else if (year <= 999) {
  3386. return 1900 + year;
  3387. }
  3388. return year;
  3389. }
  3390. function preprocessRFC2822(s) {
  3391. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  3392. return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  3393. }
  3394. function checkWeekday(weekdayStr, parsedInput, config) {
  3395. if (weekdayStr) {
  3396. // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
  3397. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  3398. weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
  3399. if (weekdayProvided !== weekdayActual) {
  3400. getParsingFlags(config).weekdayMismatch = true;
  3401. config._isValid = false;
  3402. return false;
  3403. }
  3404. }
  3405. return true;
  3406. }
  3407. var obsOffsets = {
  3408. UT: 0,
  3409. GMT: 0,
  3410. EDT: -4 * 60,
  3411. EST: -5 * 60,
  3412. CDT: -5 * 60,
  3413. CST: -6 * 60,
  3414. MDT: -6 * 60,
  3415. MST: -7 * 60,
  3416. PDT: -7 * 60,
  3417. PST: -8 * 60
  3418. };
  3419. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  3420. if (obsOffset) {
  3421. return obsOffsets[obsOffset];
  3422. } else if (militaryOffset) {
  3423. // the only allowed military tz is Z
  3424. return 0;
  3425. } else {
  3426. var hm = parseInt(numOffset, 10);
  3427. var m = hm % 100, h = (hm - m) / 100;
  3428. return h * 60 + m;
  3429. }
  3430. }
  3431. // date and time from ref 2822 format
  3432. function configFromRFC2822(config) {
  3433. var match = rfc2822.exec(preprocessRFC2822(config._i));
  3434. if (match) {
  3435. var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
  3436. if (!checkWeekday(match[1], parsedArray, config)) {
  3437. return;
  3438. }
  3439. config._a = parsedArray;
  3440. config._tzm = calculateOffset(match[8], match[9], match[10]);
  3441. config._d = createUTCDate.apply(null, config._a);
  3442. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  3443. getParsingFlags(config).rfc2822 = true;
  3444. } else {
  3445. config._isValid = false;
  3446. }
  3447. }
  3448. // date from iso format or fallback
  3449. function configFromString(config) {
  3450. var matched = aspNetJsonRegex.exec(config._i);
  3451. if (matched !== null) {
  3452. config._d = new Date(+matched[1]);
  3453. return;
  3454. }
  3455. configFromISO(config);
  3456. if (config._isValid === false) {
  3457. delete config._isValid;
  3458. } else {
  3459. return;
  3460. }
  3461. configFromRFC2822(config);
  3462. if (config._isValid === false) {
  3463. delete config._isValid;
  3464. } else {
  3465. return;
  3466. }
  3467. // Final attempt, use Input Fallback
  3468. hooks.createFromInputFallback(config);
  3469. }
  3470. hooks.createFromInputFallback = deprecate(
  3471. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  3472. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  3473. 'discouraged and will be removed in an upcoming major release. Please refer to ' +
  3474. 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  3475. function (config) {
  3476. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  3477. }
  3478. );
  3479. // constant that refers to the ISO standard
  3480. hooks.ISO_8601 = function () {};
  3481. // constant that refers to the RFC 2822 form
  3482. hooks.RFC_2822 = function () {};
  3483. // date from string and format string
  3484. function configFromStringAndFormat(config) {
  3485. // TODO: Move this to another part of the creation flow to prevent circular deps
  3486. if (config._f === hooks.ISO_8601) {
  3487. configFromISO(config);
  3488. return;
  3489. }
  3490. if (config._f === hooks.RFC_2822) {
  3491. configFromRFC2822(config);
  3492. return;
  3493. }
  3494. config._a = [];
  3495. getParsingFlags(config).empty = true;
  3496. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  3497. var string = '' + config._i,
  3498. i, parsedInput, tokens, token, skipped,
  3499. stringLength = string.length,
  3500. totalParsedInputLength = 0;
  3501. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  3502. for (i = 0; i < tokens.length; i++) {
  3503. token = tokens[i];
  3504. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  3505. // console.log('token', token, 'parsedInput', parsedInput,
  3506. // 'regex', getParseRegexForToken(token, config));
  3507. if (parsedInput) {
  3508. skipped = string.substr(0, string.indexOf(parsedInput));
  3509. if (skipped.length > 0) {
  3510. getParsingFlags(config).unusedInput.push(skipped);
  3511. }
  3512. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  3513. totalParsedInputLength += parsedInput.length;
  3514. }
  3515. // don't parse if it's not a known token
  3516. if (formatTokenFunctions[token]) {
  3517. if (parsedInput) {
  3518. getParsingFlags(config).empty = false;
  3519. }
  3520. else {
  3521. getParsingFlags(config).unusedTokens.push(token);
  3522. }
  3523. addTimeToArrayFromToken(token, parsedInput, config);
  3524. }
  3525. else if (config._strict && !parsedInput) {
  3526. getParsingFlags(config).unusedTokens.push(token);
  3527. }
  3528. }
  3529. // add remaining unparsed input length to the string
  3530. getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
  3531. if (string.length > 0) {
  3532. getParsingFlags(config).unusedInput.push(string);
  3533. }
  3534. // clear _12h flag if hour is <= 12
  3535. if (config._a[HOUR] <= 12 &&
  3536. getParsingFlags(config).bigHour === true &&
  3537. config._a[HOUR] > 0) {
  3538. getParsingFlags(config).bigHour = undefined;
  3539. }
  3540. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  3541. getParsingFlags(config).meridiem = config._meridiem;
  3542. // handle meridiem
  3543. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
  3544. configFromArray(config);
  3545. checkOverflow(config);
  3546. }
  3547. function meridiemFixWrap (locale, hour, meridiem) {
  3548. var isPm;
  3549. if (meridiem == null) {
  3550. // nothing to do
  3551. return hour;
  3552. }
  3553. if (locale.meridiemHour != null) {
  3554. return locale.meridiemHour(hour, meridiem);
  3555. } else if (locale.isPM != null) {
  3556. // Fallback
  3557. isPm = locale.isPM(meridiem);
  3558. if (isPm && hour < 12) {
  3559. hour += 12;
  3560. }
  3561. if (!isPm && hour === 12) {
  3562. hour = 0;
  3563. }
  3564. return hour;
  3565. } else {
  3566. // this is not supposed to happen
  3567. return hour;
  3568. }
  3569. }
  3570. // date from string and array of format strings
  3571. function configFromStringAndArray(config) {
  3572. var tempConfig,
  3573. bestMoment,
  3574. scoreToBeat,
  3575. i,
  3576. currentScore;
  3577. if (config._f.length === 0) {
  3578. getParsingFlags(config).invalidFormat = true;
  3579. config._d = new Date(NaN);
  3580. return;
  3581. }
  3582. for (i = 0; i < config._f.length; i++) {
  3583. currentScore = 0;
  3584. tempConfig = copyConfig({}, config);
  3585. if (config._useUTC != null) {
  3586. tempConfig._useUTC = config._useUTC;
  3587. }
  3588. tempConfig._f = config._f[i];
  3589. configFromStringAndFormat(tempConfig);
  3590. if (!isValid(tempConfig)) {
  3591. continue;
  3592. }
  3593. // if there is any input that was not parsed add a penalty for that format
  3594. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  3595. //or tokens
  3596. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  3597. getParsingFlags(tempConfig).score = currentScore;
  3598. if (scoreToBeat == null || currentScore < scoreToBeat) {
  3599. scoreToBeat = currentScore;
  3600. bestMoment = tempConfig;
  3601. }
  3602. }
  3603. extend(config, bestMoment || tempConfig);
  3604. }
  3605. function configFromObject(config) {
  3606. if (config._d) {
  3607. return;
  3608. }
  3609. var i = normalizeObjectUnits(config._i);
  3610. config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
  3611. return obj && parseInt(obj, 10);
  3612. });
  3613. configFromArray(config);
  3614. }
  3615. function createFromConfig (config) {
  3616. var res = new Moment(checkOverflow(prepareConfig(config)));
  3617. if (res._nextDay) {
  3618. // Adding is smart enough around DST
  3619. res.add(1, 'd');
  3620. res._nextDay = undefined;
  3621. }
  3622. return res;
  3623. }
  3624. function prepareConfig (config) {
  3625. var input = config._i,
  3626. format = config._f;
  3627. config._locale = config._locale || getLocale(config._l);
  3628. if (input === null || (format === undefined && input === '')) {
  3629. return createInvalid({nullInput: true});
  3630. }
  3631. if (typeof input === 'string') {
  3632. config._i = input = config._locale.preparse(input);
  3633. }
  3634. if (isMoment(input)) {
  3635. return new Moment(checkOverflow(input));
  3636. } else if (isDate(input)) {
  3637. config._d = input;
  3638. } else if (isArray(format)) {
  3639. configFromStringAndArray(config);
  3640. } else if (format) {
  3641. configFromStringAndFormat(config);
  3642. } else {
  3643. configFromInput(config);
  3644. }
  3645. if (!isValid(config)) {
  3646. config._d = null;
  3647. }
  3648. return config;
  3649. }
  3650. function configFromInput(config) {
  3651. var input = config._i;
  3652. if (isUndefined(input)) {
  3653. config._d = new Date(hooks.now());
  3654. } else if (isDate(input)) {
  3655. config._d = new Date(input.valueOf());
  3656. } else if (typeof input === 'string') {
  3657. configFromString(config);
  3658. } else if (isArray(input)) {
  3659. config._a = map(input.slice(0), function (obj) {
  3660. return parseInt(obj, 10);
  3661. });
  3662. configFromArray(config);
  3663. } else if (isObject(input)) {
  3664. configFromObject(config);
  3665. } else if (isNumber(input)) {
  3666. // from milliseconds
  3667. config._d = new Date(input);
  3668. } else {
  3669. hooks.createFromInputFallback(config);
  3670. }
  3671. }
  3672. function createLocalOrUTC (input, format, locale, strict, isUTC) {
  3673. var c = {};
  3674. if (locale === true || locale === false) {
  3675. strict = locale;
  3676. locale = undefined;
  3677. }
  3678. if ((isObject(input) && isObjectEmpty(input)) ||
  3679. (isArray(input) && input.length === 0)) {
  3680. input = undefined;
  3681. }
  3682. // object construction must be done this way.
  3683. // https://github.com/moment/moment/issues/1423
  3684. c._isAMomentObject = true;
  3685. c._useUTC = c._isUTC = isUTC;
  3686. c._l = locale;
  3687. c._i = input;
  3688. c._f = format;
  3689. c._strict = strict;
  3690. return createFromConfig(c);
  3691. }
  3692. function createLocal (input, format, locale, strict) {
  3693. return createLocalOrUTC(input, format, locale, strict, false);
  3694. }
  3695. var prototypeMin = deprecate(
  3696. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  3697. function () {
  3698. var other = createLocal.apply(null, arguments);
  3699. if (this.isValid() && other.isValid()) {
  3700. return other < this ? this : other;
  3701. } else {
  3702. return createInvalid();
  3703. }
  3704. }
  3705. );
  3706. var prototypeMax = deprecate(
  3707. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  3708. function () {
  3709. var other = createLocal.apply(null, arguments);
  3710. if (this.isValid() && other.isValid()) {
  3711. return other > this ? this : other;
  3712. } else {
  3713. return createInvalid();
  3714. }
  3715. }
  3716. );
  3717. // Pick a moment m from moments so that m[fn](other) is true for all
  3718. // other. This relies on the function fn to be transitive.
  3719. //
  3720. // moments should either be an array of moment objects or an array, whose
  3721. // first element is an array of moment objects.
  3722. function pickBy(fn, moments) {
  3723. var res, i;
  3724. if (moments.length === 1 && isArray(moments[0])) {
  3725. moments = moments[0];
  3726. }
  3727. if (!moments.length) {
  3728. return createLocal();
  3729. }
  3730. res = moments[0];
  3731. for (i = 1; i < moments.length; ++i) {
  3732. if (!moments[i].isValid() || moments[i][fn](res)) {
  3733. res = moments[i];
  3734. }
  3735. }
  3736. return res;
  3737. }
  3738. // TODO: Use [].sort instead?
  3739. function min () {
  3740. var args = [].slice.call(arguments, 0);
  3741. return pickBy('isBefore', args);
  3742. }
  3743. function max () {
  3744. var args = [].slice.call(arguments, 0);
  3745. return pickBy('isAfter', args);
  3746. }
  3747. var now = function () {
  3748. return Date.now ? Date.now() : +(new Date());
  3749. };
  3750. var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
  3751. function isDurationValid(m) {
  3752. for (var key in m) {
  3753. if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
  3754. return false;
  3755. }
  3756. }
  3757. var unitHasDecimal = false;
  3758. for (var i = 0; i < ordering.length; ++i) {
  3759. if (m[ordering[i]]) {
  3760. if (unitHasDecimal) {
  3761. return false; // only allow non-integers for smallest unit
  3762. }
  3763. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  3764. unitHasDecimal = true;
  3765. }
  3766. }
  3767. }
  3768. return true;
  3769. }
  3770. function isValid$1() {
  3771. return this._isValid;
  3772. }
  3773. function createInvalid$1() {
  3774. return createDuration(NaN);
  3775. }
  3776. function Duration (duration) {
  3777. var normalizedInput = normalizeObjectUnits(duration),
  3778. years = normalizedInput.year || 0,
  3779. quarters = normalizedInput.quarter || 0,
  3780. months = normalizedInput.month || 0,
  3781. weeks = normalizedInput.week || 0,
  3782. days = normalizedInput.day || 0,
  3783. hours = normalizedInput.hour || 0,
  3784. minutes = normalizedInput.minute || 0,
  3785. seconds = normalizedInput.second || 0,
  3786. milliseconds = normalizedInput.millisecond || 0;
  3787. this._isValid = isDurationValid(normalizedInput);
  3788. // representation for dateAddRemove
  3789. this._milliseconds = +milliseconds +
  3790. seconds * 1e3 + // 1000
  3791. minutes * 6e4 + // 1000 * 60
  3792. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  3793. // Because of dateAddRemove treats 24 hours as different from a
  3794. // day when working around DST, we need to store them separately
  3795. this._days = +days +
  3796. weeks * 7;
  3797. // It is impossible to translate months into days without knowing
  3798. // which months you are are talking about, so we have to store
  3799. // it separately.
  3800. this._months = +months +
  3801. quarters * 3 +
  3802. years * 12;
  3803. this._data = {};
  3804. this._locale = getLocale();
  3805. this._bubble();
  3806. }
  3807. function isDuration (obj) {
  3808. return obj instanceof Duration;
  3809. }
  3810. function absRound (number) {
  3811. if (number < 0) {
  3812. return Math.round(-1 * number) * -1;
  3813. } else {
  3814. return Math.round(number);
  3815. }
  3816. }
  3817. // FORMATTING
  3818. function offset (token, separator) {
  3819. addFormatToken(token, 0, 0, function () {
  3820. var offset = this.utcOffset();
  3821. var sign = '+';
  3822. if (offset < 0) {
  3823. offset = -offset;
  3824. sign = '-';
  3825. }
  3826. return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
  3827. });
  3828. }
  3829. offset('Z', ':');
  3830. offset('ZZ', '');
  3831. // PARSING
  3832. addRegexToken('Z', matchShortOffset);
  3833. addRegexToken('ZZ', matchShortOffset);
  3834. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  3835. config._useUTC = true;
  3836. config._tzm = offsetFromString(matchShortOffset, input);
  3837. });
  3838. // HELPERS
  3839. // timezone chunker
  3840. // '+10:00' > ['10', '00']
  3841. // '-1530' > ['-15', '30']
  3842. var chunkOffset = /([\+\-]|\d\d)/gi;
  3843. function offsetFromString(matcher, string) {
  3844. var matches = (string || '').match(matcher);
  3845. if (matches === null) {
  3846. return null;
  3847. }
  3848. var chunk = matches[matches.length - 1] || [];
  3849. var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  3850. var minutes = +(parts[1] * 60) + toInt(parts[2]);
  3851. return minutes === 0 ?
  3852. 0 :
  3853. parts[0] === '+' ? minutes : -minutes;
  3854. }
  3855. // Return a moment from input, that is local/utc/zone equivalent to model.
  3856. function cloneWithOffset(input, model) {
  3857. var res, diff;
  3858. if (model._isUTC) {
  3859. res = model.clone();
  3860. diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
  3861. // Use low-level api, because this fn is low-level api.
  3862. res._d.setTime(res._d.valueOf() + diff);
  3863. hooks.updateOffset(res, false);
  3864. return res;
  3865. } else {
  3866. return createLocal(input).local();
  3867. }
  3868. }
  3869. function getDateOffset (m) {
  3870. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  3871. // https://github.com/moment/moment/pull/1871
  3872. return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
  3873. }
  3874. // HOOKS
  3875. // This function will be called whenever a moment is mutated.
  3876. // It is intended to keep the offset in sync with the timezone.
  3877. hooks.updateOffset = function () {};
  3878. // MOMENTS
  3879. // keepLocalTime = true means only change the timezone, without
  3880. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  3881. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  3882. // +0200, so we adjust the time as needed, to be valid.
  3883. //
  3884. // Keeping the time actually adds/subtracts (one hour)
  3885. // from the actual represented time. That is why we call updateOffset
  3886. // a second time. In case it wants us to change the offset again
  3887. // _changeInProgress == true case, then we have to adjust, because
  3888. // there is no such time in the given timezone.
  3889. function getSetOffset (input, keepLocalTime, keepMinutes) {
  3890. var offset = this._offset || 0,
  3891. localAdjust;
  3892. if (!this.isValid()) {
  3893. return input != null ? this : NaN;
  3894. }
  3895. if (input != null) {
  3896. if (typeof input === 'string') {
  3897. input = offsetFromString(matchShortOffset, input);
  3898. if (input === null) {
  3899. return this;
  3900. }
  3901. } else if (Math.abs(input) < 16 && !keepMinutes) {
  3902. input = input * 60;
  3903. }
  3904. if (!this._isUTC && keepLocalTime) {
  3905. localAdjust = getDateOffset(this);
  3906. }
  3907. this._offset = input;
  3908. this._isUTC = true;
  3909. if (localAdjust != null) {
  3910. this.add(localAdjust, 'm');
  3911. }
  3912. if (offset !== input) {
  3913. if (!keepLocalTime || this._changeInProgress) {
  3914. addSubtract(this, createDuration(input - offset, 'm'), 1, false);
  3915. } else if (!this._changeInProgress) {
  3916. this._changeInProgress = true;
  3917. hooks.updateOffset(this, true);
  3918. this._changeInProgress = null;
  3919. }
  3920. }
  3921. return this;
  3922. } else {
  3923. return this._isUTC ? offset : getDateOffset(this);
  3924. }
  3925. }
  3926. function getSetZone (input, keepLocalTime) {
  3927. if (input != null) {
  3928. if (typeof input !== 'string') {
  3929. input = -input;
  3930. }
  3931. this.utcOffset(input, keepLocalTime);
  3932. return this;
  3933. } else {
  3934. return -this.utcOffset();
  3935. }
  3936. }
  3937. function setOffsetToUTC (keepLocalTime) {
  3938. return this.utcOffset(0, keepLocalTime);
  3939. }
  3940. function setOffsetToLocal (keepLocalTime) {
  3941. if (this._isUTC) {
  3942. this.utcOffset(0, keepLocalTime);
  3943. this._isUTC = false;
  3944. if (keepLocalTime) {
  3945. this.subtract(getDateOffset(this), 'm');
  3946. }
  3947. }
  3948. return this;
  3949. }
  3950. function setOffsetToParsedOffset () {
  3951. if (this._tzm != null) {
  3952. this.utcOffset(this._tzm, false, true);
  3953. } else if (typeof this._i === 'string') {
  3954. var tZone = offsetFromString(matchOffset, this._i);
  3955. if (tZone != null) {
  3956. this.utcOffset(tZone);
  3957. }
  3958. else {
  3959. this.utcOffset(0, true);
  3960. }
  3961. }
  3962. return this;
  3963. }
  3964. function hasAlignedHourOffset (input) {
  3965. if (!this.isValid()) {
  3966. return false;
  3967. }
  3968. input = input ? createLocal(input).utcOffset() : 0;
  3969. return (this.utcOffset() - input) % 60 === 0;
  3970. }
  3971. function isDaylightSavingTime () {
  3972. return (
  3973. this.utcOffset() > this.clone().month(0).utcOffset() ||
  3974. this.utcOffset() > this.clone().month(5).utcOffset()
  3975. );
  3976. }
  3977. function isDaylightSavingTimeShifted () {
  3978. if (!isUndefined(this._isDSTShifted)) {
  3979. return this._isDSTShifted;
  3980. }
  3981. var c = {};
  3982. copyConfig(c, this);
  3983. c = prepareConfig(c);
  3984. if (c._a) {
  3985. var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  3986. this._isDSTShifted = this.isValid() &&
  3987. compareArrays(c._a, other.toArray()) > 0;
  3988. } else {
  3989. this._isDSTShifted = false;
  3990. }
  3991. return this._isDSTShifted;
  3992. }
  3993. function isLocal () {
  3994. return this.isValid() ? !this._isUTC : false;
  3995. }
  3996. function isUtcOffset () {
  3997. return this.isValid() ? this._isUTC : false;
  3998. }
  3999. function isUtc () {
  4000. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  4001. }
  4002. // ASP.NET json date format regex
  4003. var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
  4004. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  4005. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  4006. // and further modified to allow for strings containing both week and day
  4007. 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)?)?$/;
  4008. function createDuration (input, key) {
  4009. var duration = input,
  4010. // matching against regexp is expensive, do it on demand
  4011. match = null,
  4012. sign,
  4013. ret,
  4014. diffRes;
  4015. if (isDuration(input)) {
  4016. duration = {
  4017. ms : input._milliseconds,
  4018. d : input._days,
  4019. M : input._months
  4020. };
  4021. } else if (isNumber(input)) {
  4022. duration = {};
  4023. if (key) {
  4024. duration[key] = input;
  4025. } else {
  4026. duration.milliseconds = input;
  4027. }
  4028. } else if (!!(match = aspNetRegex.exec(input))) {
  4029. sign = (match[1] === '-') ? -1 : 1;
  4030. duration = {
  4031. y : 0,
  4032. d : toInt(match[DATE]) * sign,
  4033. h : toInt(match[HOUR]) * sign,
  4034. m : toInt(match[MINUTE]) * sign,
  4035. s : toInt(match[SECOND]) * sign,
  4036. ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
  4037. };
  4038. } else if (!!(match = isoRegex.exec(input))) {
  4039. sign = (match[1] === '-') ? -1 : (match[1] === '+') ? 1 : 1;
  4040. duration = {
  4041. y : parseIso(match[2], sign),
  4042. M : parseIso(match[3], sign),
  4043. w : parseIso(match[4], sign),
  4044. d : parseIso(match[5], sign),
  4045. h : parseIso(match[6], sign),
  4046. m : parseIso(match[7], sign),
  4047. s : parseIso(match[8], sign)
  4048. };
  4049. } else if (duration == null) {// checks for null or undefined
  4050. duration = {};
  4051. } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
  4052. diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
  4053. duration = {};
  4054. duration.ms = diffRes.milliseconds;
  4055. duration.M = diffRes.months;
  4056. }
  4057. ret = new Duration(duration);
  4058. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  4059. ret._locale = input._locale;
  4060. }
  4061. return ret;
  4062. }
  4063. createDuration.fn = Duration.prototype;
  4064. createDuration.invalid = createInvalid$1;
  4065. function parseIso (inp, sign) {
  4066. // We'd normally use ~~inp for this, but unfortunately it also
  4067. // converts floats to ints.
  4068. // inp may be undefined, so careful calling replace on it.
  4069. var res = inp && parseFloat(inp.replace(',', '.'));
  4070. // apply sign while we're at it
  4071. return (isNaN(res) ? 0 : res) * sign;
  4072. }
  4073. function positiveMomentsDifference(base, other) {
  4074. var res = {milliseconds: 0, months: 0};
  4075. res.months = other.month() - base.month() +
  4076. (other.year() - base.year()) * 12;
  4077. if (base.clone().add(res.months, 'M').isAfter(other)) {
  4078. --res.months;
  4079. }
  4080. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  4081. return res;
  4082. }
  4083. function momentsDifference(base, other) {
  4084. var res;
  4085. if (!(base.isValid() && other.isValid())) {
  4086. return {milliseconds: 0, months: 0};
  4087. }
  4088. other = cloneWithOffset(other, base);
  4089. if (base.isBefore(other)) {
  4090. res = positiveMomentsDifference(base, other);
  4091. } else {
  4092. res = positiveMomentsDifference(other, base);
  4093. res.milliseconds = -res.milliseconds;
  4094. res.months = -res.months;
  4095. }
  4096. return res;
  4097. }
  4098. // TODO: remove 'name' arg after deprecation is removed
  4099. function createAdder(direction, name) {
  4100. return function (val, period) {
  4101. var dur, tmp;
  4102. //invert the arguments, but complain about it
  4103. if (period !== null && !isNaN(+period)) {
  4104. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
  4105. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
  4106. tmp = val; val = period; period = tmp;
  4107. }
  4108. val = typeof val === 'string' ? +val : val;
  4109. dur = createDuration(val, period);
  4110. addSubtract(this, dur, direction);
  4111. return this;
  4112. };
  4113. }
  4114. function addSubtract (mom, duration, isAdding, updateOffset) {
  4115. var milliseconds = duration._milliseconds,
  4116. days = absRound(duration._days),
  4117. months = absRound(duration._months);
  4118. if (!mom.isValid()) {
  4119. // No op
  4120. return;
  4121. }
  4122. updateOffset = updateOffset == null ? true : updateOffset;
  4123. if (months) {
  4124. setMonth(mom, get(mom, 'Month') + months * isAdding);
  4125. }
  4126. if (days) {
  4127. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  4128. }
  4129. if (milliseconds) {
  4130. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  4131. }
  4132. if (updateOffset) {
  4133. hooks.updateOffset(mom, days || months);
  4134. }
  4135. }
  4136. var add = createAdder(1, 'add');
  4137. var subtract = createAdder(-1, 'subtract');
  4138. function getCalendarFormat(myMoment, now) {
  4139. var diff = myMoment.diff(now, 'days', true);
  4140. return diff < -6 ? 'sameElse' :
  4141. diff < -1 ? 'lastWeek' :
  4142. diff < 0 ? 'lastDay' :
  4143. diff < 1 ? 'sameDay' :
  4144. diff < 2 ? 'nextDay' :
  4145. diff < 7 ? 'nextWeek' : 'sameElse';
  4146. }
  4147. function calendar$1 (time, formats) {
  4148. // We want to compare the start of today, vs this.
  4149. // Getting start-of-today depends on whether we're local/utc/offset or not.
  4150. var now = time || createLocal(),
  4151. sod = cloneWithOffset(now, this).startOf('day'),
  4152. format = hooks.calendarFormat(this, sod) || 'sameElse';
  4153. var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
  4154. return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
  4155. }
  4156. function clone () {
  4157. return new Moment(this);
  4158. }
  4159. function isAfter (input, units) {
  4160. var localInput = isMoment(input) ? input : createLocal(input);
  4161. if (!(this.isValid() && localInput.isValid())) {
  4162. return false;
  4163. }
  4164. units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
  4165. if (units === 'millisecond') {
  4166. return this.valueOf() > localInput.valueOf();
  4167. } else {
  4168. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  4169. }
  4170. }
  4171. function isBefore (input, units) {
  4172. var localInput = isMoment(input) ? input : createLocal(input);
  4173. if (!(this.isValid() && localInput.isValid())) {
  4174. return false;
  4175. }
  4176. units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
  4177. if (units === 'millisecond') {
  4178. return this.valueOf() < localInput.valueOf();
  4179. } else {
  4180. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  4181. }
  4182. }
  4183. function isBetween (from, to, units, inclusivity) {
  4184. inclusivity = inclusivity || '()';
  4185. return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
  4186. (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
  4187. }
  4188. function isSame (input, units) {
  4189. var localInput = isMoment(input) ? input : createLocal(input),
  4190. inputMs;
  4191. if (!(this.isValid() && localInput.isValid())) {
  4192. return false;
  4193. }
  4194. units = normalizeUnits(units || 'millisecond');
  4195. if (units === 'millisecond') {
  4196. return this.valueOf() === localInput.valueOf();
  4197. } else {
  4198. inputMs = localInput.valueOf();
  4199. return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
  4200. }
  4201. }
  4202. function isSameOrAfter (input, units) {
  4203. return this.isSame(input, units) || this.isAfter(input,units);
  4204. }
  4205. function isSameOrBefore (input, units) {
  4206. return this.isSame(input, units) || this.isBefore(input,units);
  4207. }
  4208. function diff (input, units, asFloat) {
  4209. var that,
  4210. zoneDelta,
  4211. output;
  4212. if (!this.isValid()) {
  4213. return NaN;
  4214. }
  4215. that = cloneWithOffset(input, this);
  4216. if (!that.isValid()) {
  4217. return NaN;
  4218. }
  4219. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  4220. units = normalizeUnits(units);
  4221. switch (units) {
  4222. case 'year': output = monthDiff(this, that) / 12; break;
  4223. case 'month': output = monthDiff(this, that); break;
  4224. case 'quarter': output = monthDiff(this, that) / 3; break;
  4225. case 'second': output = (this - that) / 1e3; break; // 1000
  4226. case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
  4227. case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
  4228. case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
  4229. case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
  4230. default: output = this - that;
  4231. }
  4232. return asFloat ? output : absFloor(output);
  4233. }
  4234. function monthDiff (a, b) {
  4235. // difference in months
  4236. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  4237. // b is in (anchor - 1 month, anchor + 1 month)
  4238. anchor = a.clone().add(wholeMonthDiff, 'months'),
  4239. anchor2, adjust;
  4240. if (b - anchor < 0) {
  4241. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  4242. // linear across the month
  4243. adjust = (b - anchor) / (anchor - anchor2);
  4244. } else {
  4245. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  4246. // linear across the month
  4247. adjust = (b - anchor) / (anchor2 - anchor);
  4248. }
  4249. //check for negative zero, return zero if negative zero
  4250. return -(wholeMonthDiff + adjust) || 0;
  4251. }
  4252. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  4253. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  4254. function toString () {
  4255. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  4256. }
  4257. function toISOString(keepOffset) {
  4258. if (!this.isValid()) {
  4259. return null;
  4260. }
  4261. var utc = keepOffset !== true;
  4262. var m = utc ? this.clone().utc() : this;
  4263. if (m.year() < 0 || m.year() > 9999) {
  4264. return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
  4265. }
  4266. if (isFunction(Date.prototype.toISOString)) {
  4267. // native implementation is ~50x faster, use it when we can
  4268. if (utc) {
  4269. return this.toDate().toISOString();
  4270. } else {
  4271. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
  4272. }
  4273. }
  4274. return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
  4275. }
  4276. /**
  4277. * Return a human readable representation of a moment that can
  4278. * also be evaluated to get a new moment which is the same
  4279. *
  4280. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  4281. */
  4282. function inspect () {
  4283. if (!this.isValid()) {
  4284. return 'moment.invalid(/* ' + this._i + ' */)';
  4285. }
  4286. var func = 'moment';
  4287. var zone = '';
  4288. if (!this.isLocal()) {
  4289. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  4290. zone = 'Z';
  4291. }
  4292. var prefix = '[' + func + '("]';
  4293. var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
  4294. var datetime = '-MM-DD[T]HH:mm:ss.SSS';
  4295. var suffix = zone + '[")]';
  4296. return this.format(prefix + year + datetime + suffix);
  4297. }
  4298. function format (inputString) {
  4299. if (!inputString) {
  4300. inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
  4301. }
  4302. var output = formatMoment(this, inputString);
  4303. return this.localeData().postformat(output);
  4304. }
  4305. function from (time, withoutSuffix) {
  4306. if (this.isValid() &&
  4307. ((isMoment(time) && time.isValid()) ||
  4308. createLocal(time).isValid())) {
  4309. return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  4310. } else {
  4311. return this.localeData().invalidDate();
  4312. }
  4313. }
  4314. function fromNow (withoutSuffix) {
  4315. return this.from(createLocal(), withoutSuffix);
  4316. }
  4317. function to (time, withoutSuffix) {
  4318. if (this.isValid() &&
  4319. ((isMoment(time) && time.isValid()) ||
  4320. createLocal(time).isValid())) {
  4321. return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
  4322. } else {
  4323. return this.localeData().invalidDate();
  4324. }
  4325. }
  4326. function toNow (withoutSuffix) {
  4327. return this.to(createLocal(), withoutSuffix);
  4328. }
  4329. // If passed a locale key, it will set the locale for this
  4330. // instance. Otherwise, it will return the locale configuration
  4331. // variables for this instance.
  4332. function locale (key) {
  4333. var newLocaleData;
  4334. if (key === undefined) {
  4335. return this._locale._abbr;
  4336. } else {
  4337. newLocaleData = getLocale(key);
  4338. if (newLocaleData != null) {
  4339. this._locale = newLocaleData;
  4340. }
  4341. return this;
  4342. }
  4343. }
  4344. var lang = deprecate(
  4345. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  4346. function (key) {
  4347. if (key === undefined) {
  4348. return this.localeData();
  4349. } else {
  4350. return this.locale(key);
  4351. }
  4352. }
  4353. );
  4354. function localeData () {
  4355. return this._locale;
  4356. }
  4357. function startOf (units) {
  4358. units = normalizeUnits(units);
  4359. // the following switch intentionally omits break keywords
  4360. // to utilize falling through the cases.
  4361. switch (units) {
  4362. case 'year':
  4363. this.month(0);
  4364. /* falls through */
  4365. case 'quarter':
  4366. case 'month':
  4367. this.date(1);
  4368. /* falls through */
  4369. case 'week':
  4370. case 'isoWeek':
  4371. case 'day':
  4372. case 'date':
  4373. this.hours(0);
  4374. /* falls through */
  4375. case 'hour':
  4376. this.minutes(0);
  4377. /* falls through */
  4378. case 'minute':
  4379. this.seconds(0);
  4380. /* falls through */
  4381. case 'second':
  4382. this.milliseconds(0);
  4383. }
  4384. // weeks are a special case
  4385. if (units === 'week') {
  4386. this.weekday(0);
  4387. }
  4388. if (units === 'isoWeek') {
  4389. this.isoWeekday(1);
  4390. }
  4391. // quarters are also special
  4392. if (units === 'quarter') {
  4393. this.month(Math.floor(this.month() / 3) * 3);
  4394. }
  4395. return this;
  4396. }
  4397. function endOf (units) {
  4398. units = normalizeUnits(units);
  4399. if (units === undefined || units === 'millisecond') {
  4400. return this;
  4401. }
  4402. // 'date' is an alias for 'day', so it should be considered as such.
  4403. if (units === 'date') {
  4404. units = 'day';
  4405. }
  4406. return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
  4407. }
  4408. function valueOf () {
  4409. return this._d.valueOf() - ((this._offset || 0) * 60000);
  4410. }
  4411. function unix () {
  4412. return Math.floor(this.valueOf() / 1000);
  4413. }
  4414. function toDate () {
  4415. return new Date(this.valueOf());
  4416. }
  4417. function toArray () {
  4418. var m = this;
  4419. return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
  4420. }
  4421. function toObject () {
  4422. var m = this;
  4423. return {
  4424. years: m.year(),
  4425. months: m.month(),
  4426. date: m.date(),
  4427. hours: m.hours(),
  4428. minutes: m.minutes(),
  4429. seconds: m.seconds(),
  4430. milliseconds: m.milliseconds()
  4431. };
  4432. }
  4433. function toJSON () {
  4434. // new Date(NaN).toJSON() === null
  4435. return this.isValid() ? this.toISOString() : null;
  4436. }
  4437. function isValid$2 () {
  4438. return isValid(this);
  4439. }
  4440. function parsingFlags () {
  4441. return extend({}, getParsingFlags(this));
  4442. }
  4443. function invalidAt () {
  4444. return getParsingFlags(this).overflow;
  4445. }
  4446. function creationData() {
  4447. return {
  4448. input: this._i,
  4449. format: this._f,
  4450. locale: this._locale,
  4451. isUTC: this._isUTC,
  4452. strict: this._strict
  4453. };
  4454. }
  4455. // FORMATTING
  4456. addFormatToken(0, ['gg', 2], 0, function () {
  4457. return this.weekYear() % 100;
  4458. });
  4459. addFormatToken(0, ['GG', 2], 0, function () {
  4460. return this.isoWeekYear() % 100;
  4461. });
  4462. function addWeekYearFormatToken (token, getter) {
  4463. addFormatToken(0, [token, token.length], 0, getter);
  4464. }
  4465. addWeekYearFormatToken('gggg', 'weekYear');
  4466. addWeekYearFormatToken('ggggg', 'weekYear');
  4467. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  4468. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  4469. // ALIASES
  4470. addUnitAlias('weekYear', 'gg');
  4471. addUnitAlias('isoWeekYear', 'GG');
  4472. // PRIORITY
  4473. addUnitPriority('weekYear', 1);
  4474. addUnitPriority('isoWeekYear', 1);
  4475. // PARSING
  4476. addRegexToken('G', matchSigned);
  4477. addRegexToken('g', matchSigned);
  4478. addRegexToken('GG', match1to2, match2);
  4479. addRegexToken('gg', match1to2, match2);
  4480. addRegexToken('GGGG', match1to4, match4);
  4481. addRegexToken('gggg', match1to4, match4);
  4482. addRegexToken('GGGGG', match1to6, match6);
  4483. addRegexToken('ggggg', match1to6, match6);
  4484. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
  4485. week[token.substr(0, 2)] = toInt(input);
  4486. });
  4487. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  4488. week[token] = hooks.parseTwoDigitYear(input);
  4489. });
  4490. // MOMENTS
  4491. function getSetWeekYear (input) {
  4492. return getSetWeekYearHelper.call(this,
  4493. input,
  4494. this.week(),
  4495. this.weekday(),
  4496. this.localeData()._week.dow,
  4497. this.localeData()._week.doy);
  4498. }
  4499. function getSetISOWeekYear (input) {
  4500. return getSetWeekYearHelper.call(this,
  4501. input, this.isoWeek(), this.isoWeekday(), 1, 4);
  4502. }
  4503. function getISOWeeksInYear () {
  4504. return weeksInYear(this.year(), 1, 4);
  4505. }
  4506. function getWeeksInYear () {
  4507. var weekInfo = this.localeData()._week;
  4508. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  4509. }
  4510. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  4511. var weeksTarget;
  4512. if (input == null) {
  4513. return weekOfYear(this, dow, doy).year;
  4514. } else {
  4515. weeksTarget = weeksInYear(input, dow, doy);
  4516. if (week > weeksTarget) {
  4517. week = weeksTarget;
  4518. }
  4519. return setWeekAll.call(this, input, week, weekday, dow, doy);
  4520. }
  4521. }
  4522. function setWeekAll(weekYear, week, weekday, dow, doy) {
  4523. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  4524. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  4525. this.year(date.getUTCFullYear());
  4526. this.month(date.getUTCMonth());
  4527. this.date(date.getUTCDate());
  4528. return this;
  4529. }
  4530. // FORMATTING
  4531. addFormatToken('Q', 0, 'Qo', 'quarter');
  4532. // ALIASES
  4533. addUnitAlias('quarter', 'Q');
  4534. // PRIORITY
  4535. addUnitPriority('quarter', 7);
  4536. // PARSING
  4537. addRegexToken('Q', match1);
  4538. addParseToken('Q', function (input, array) {
  4539. array[MONTH] = (toInt(input) - 1) * 3;
  4540. });
  4541. // MOMENTS
  4542. function getSetQuarter (input) {
  4543. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  4544. }
  4545. // FORMATTING
  4546. addFormatToken('D', ['DD', 2], 'Do', 'date');
  4547. // ALIASES
  4548. addUnitAlias('date', 'D');
  4549. // PRIORITY
  4550. addUnitPriority('date', 9);
  4551. // PARSING
  4552. addRegexToken('D', match1to2);
  4553. addRegexToken('DD', match1to2, match2);
  4554. addRegexToken('Do', function (isStrict, locale) {
  4555. // TODO: Remove "ordinalParse" fallback in next major release.
  4556. return isStrict ?
  4557. (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
  4558. locale._dayOfMonthOrdinalParseLenient;
  4559. });
  4560. addParseToken(['D', 'DD'], DATE);
  4561. addParseToken('Do', function (input, array) {
  4562. array[DATE] = toInt(input.match(match1to2)[0]);
  4563. });
  4564. // MOMENTS
  4565. var getSetDayOfMonth = makeGetSet('Date', true);
  4566. // FORMATTING
  4567. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  4568. // ALIASES
  4569. addUnitAlias('dayOfYear', 'DDD');
  4570. // PRIORITY
  4571. addUnitPriority('dayOfYear', 4);
  4572. // PARSING
  4573. addRegexToken('DDD', match1to3);
  4574. addRegexToken('DDDD', match3);
  4575. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  4576. config._dayOfYear = toInt(input);
  4577. });
  4578. // HELPERS
  4579. // MOMENTS
  4580. function getSetDayOfYear (input) {
  4581. var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
  4582. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  4583. }
  4584. // FORMATTING
  4585. addFormatToken('m', ['mm', 2], 0, 'minute');
  4586. // ALIASES
  4587. addUnitAlias('minute', 'm');
  4588. // PRIORITY
  4589. addUnitPriority('minute', 14);
  4590. // PARSING
  4591. addRegexToken('m', match1to2);
  4592. addRegexToken('mm', match1to2, match2);
  4593. addParseToken(['m', 'mm'], MINUTE);
  4594. // MOMENTS
  4595. var getSetMinute = makeGetSet('Minutes', false);
  4596. // FORMATTING
  4597. addFormatToken('s', ['ss', 2], 0, 'second');
  4598. // ALIASES
  4599. addUnitAlias('second', 's');
  4600. // PRIORITY
  4601. addUnitPriority('second', 15);
  4602. // PARSING
  4603. addRegexToken('s', match1to2);
  4604. addRegexToken('ss', match1to2, match2);
  4605. addParseToken(['s', 'ss'], SECOND);
  4606. // MOMENTS
  4607. var getSetSecond = makeGetSet('Seconds', false);
  4608. // FORMATTING
  4609. addFormatToken('S', 0, 0, function () {
  4610. return ~~(this.millisecond() / 100);
  4611. });
  4612. addFormatToken(0, ['SS', 2], 0, function () {
  4613. return ~~(this.millisecond() / 10);
  4614. });
  4615. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  4616. addFormatToken(0, ['SSSS', 4], 0, function () {
  4617. return this.millisecond() * 10;
  4618. });
  4619. addFormatToken(0, ['SSSSS', 5], 0, function () {
  4620. return this.millisecond() * 100;
  4621. });
  4622. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  4623. return this.millisecond() * 1000;
  4624. });
  4625. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  4626. return this.millisecond() * 10000;
  4627. });
  4628. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  4629. return this.millisecond() * 100000;
  4630. });
  4631. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  4632. return this.millisecond() * 1000000;
  4633. });
  4634. // ALIASES
  4635. addUnitAlias('millisecond', 'ms');
  4636. // PRIORITY
  4637. addUnitPriority('millisecond', 16);
  4638. // PARSING
  4639. addRegexToken('S', match1to3, match1);
  4640. addRegexToken('SS', match1to3, match2);
  4641. addRegexToken('SSS', match1to3, match3);
  4642. var token;
  4643. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  4644. addRegexToken(token, matchUnsigned);
  4645. }
  4646. function parseMs(input, array) {
  4647. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  4648. }
  4649. for (token = 'S'; token.length <= 9; token += 'S') {
  4650. addParseToken(token, parseMs);
  4651. }
  4652. // MOMENTS
  4653. var getSetMillisecond = makeGetSet('Milliseconds', false);
  4654. // FORMATTING
  4655. addFormatToken('z', 0, 0, 'zoneAbbr');
  4656. addFormatToken('zz', 0, 0, 'zoneName');
  4657. // MOMENTS
  4658. function getZoneAbbr () {
  4659. return this._isUTC ? 'UTC' : '';
  4660. }
  4661. function getZoneName () {
  4662. return this._isUTC ? 'Coordinated Universal Time' : '';
  4663. }
  4664. var proto = Moment.prototype;
  4665. proto.add = add;
  4666. proto.calendar = calendar$1;
  4667. proto.clone = clone;
  4668. proto.diff = diff;
  4669. proto.endOf = endOf;
  4670. proto.format = format;
  4671. proto.from = from;
  4672. proto.fromNow = fromNow;
  4673. proto.to = to;
  4674. proto.toNow = toNow;
  4675. proto.get = stringGet;
  4676. proto.invalidAt = invalidAt;
  4677. proto.isAfter = isAfter;
  4678. proto.isBefore = isBefore;
  4679. proto.isBetween = isBetween;
  4680. proto.isSame = isSame;
  4681. proto.isSameOrAfter = isSameOrAfter;
  4682. proto.isSameOrBefore = isSameOrBefore;
  4683. proto.isValid = isValid$2;
  4684. proto.lang = lang;
  4685. proto.locale = locale;
  4686. proto.localeData = localeData;
  4687. proto.max = prototypeMax;
  4688. proto.min = prototypeMin;
  4689. proto.parsingFlags = parsingFlags;
  4690. proto.set = stringSet;
  4691. proto.startOf = startOf;
  4692. proto.subtract = subtract;
  4693. proto.toArray = toArray;
  4694. proto.toObject = toObject;
  4695. proto.toDate = toDate;
  4696. proto.toISOString = toISOString;
  4697. proto.inspect = inspect;
  4698. proto.toJSON = toJSON;
  4699. proto.toString = toString;
  4700. proto.unix = unix;
  4701. proto.valueOf = valueOf;
  4702. proto.creationData = creationData;
  4703. proto.year = getSetYear;
  4704. proto.isLeapYear = getIsLeapYear;
  4705. proto.weekYear = getSetWeekYear;
  4706. proto.isoWeekYear = getSetISOWeekYear;
  4707. proto.quarter = proto.quarters = getSetQuarter;
  4708. proto.month = getSetMonth;
  4709. proto.daysInMonth = getDaysInMonth;
  4710. proto.week = proto.weeks = getSetWeek;
  4711. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  4712. proto.weeksInYear = getWeeksInYear;
  4713. proto.isoWeeksInYear = getISOWeeksInYear;
  4714. proto.date = getSetDayOfMonth;
  4715. proto.day = proto.days = getSetDayOfWeek;
  4716. proto.weekday = getSetLocaleDayOfWeek;
  4717. proto.isoWeekday = getSetISODayOfWeek;
  4718. proto.dayOfYear = getSetDayOfYear;
  4719. proto.hour = proto.hours = getSetHour;
  4720. proto.minute = proto.minutes = getSetMinute;
  4721. proto.second = proto.seconds = getSetSecond;
  4722. proto.millisecond = proto.milliseconds = getSetMillisecond;
  4723. proto.utcOffset = getSetOffset;
  4724. proto.utc = setOffsetToUTC;
  4725. proto.local = setOffsetToLocal;
  4726. proto.parseZone = setOffsetToParsedOffset;
  4727. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  4728. proto.isDST = isDaylightSavingTime;
  4729. proto.isLocal = isLocal;
  4730. proto.isUtcOffset = isUtcOffset;
  4731. proto.isUtc = isUtc;
  4732. proto.isUTC = isUtc;
  4733. proto.zoneAbbr = getZoneAbbr;
  4734. proto.zoneName = getZoneName;
  4735. proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
  4736. proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
  4737. proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
  4738. proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
  4739. proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
  4740. function createUnix (input) {
  4741. return createLocal(input * 1000);
  4742. }
  4743. function createInZone () {
  4744. return createLocal.apply(null, arguments).parseZone();
  4745. }
  4746. function preParsePostFormat (string) {
  4747. return string;
  4748. }
  4749. var proto$1 = Locale.prototype;
  4750. proto$1.calendar = calendar;
  4751. proto$1.longDateFormat = longDateFormat;
  4752. proto$1.invalidDate = invalidDate;
  4753. proto$1.ordinal = ordinal;
  4754. proto$1.preparse = preParsePostFormat;
  4755. proto$1.postformat = preParsePostFormat;
  4756. proto$1.relativeTime = relativeTime;
  4757. proto$1.pastFuture = pastFuture;
  4758. proto$1.set = set;
  4759. proto$1.months = localeMonths;
  4760. proto$1.monthsShort = localeMonthsShort;
  4761. proto$1.monthsParse = localeMonthsParse;
  4762. proto$1.monthsRegex = monthsRegex;
  4763. proto$1.monthsShortRegex = monthsShortRegex;
  4764. proto$1.week = localeWeek;
  4765. proto$1.firstDayOfYear = localeFirstDayOfYear;
  4766. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  4767. proto$1.weekdays = localeWeekdays;
  4768. proto$1.weekdaysMin = localeWeekdaysMin;
  4769. proto$1.weekdaysShort = localeWeekdaysShort;
  4770. proto$1.weekdaysParse = localeWeekdaysParse;
  4771. proto$1.weekdaysRegex = weekdaysRegex;
  4772. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  4773. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  4774. proto$1.isPM = localeIsPM;
  4775. proto$1.meridiem = localeMeridiem;
  4776. function get$1 (format, index, field, setter) {
  4777. var locale = getLocale();
  4778. var utc = createUTC().set(setter, index);
  4779. return locale[field](utc, format);
  4780. }
  4781. function listMonthsImpl (format, index, field) {
  4782. if (isNumber(format)) {
  4783. index = format;
  4784. format = undefined;
  4785. }
  4786. format = format || '';
  4787. if (index != null) {
  4788. return get$1(format, index, field, 'month');
  4789. }
  4790. var i;
  4791. var out = [];
  4792. for (i = 0; i < 12; i++) {
  4793. out[i] = get$1(format, i, field, 'month');
  4794. }
  4795. return out;
  4796. }
  4797. // ()
  4798. // (5)
  4799. // (fmt, 5)
  4800. // (fmt)
  4801. // (true)
  4802. // (true, 5)
  4803. // (true, fmt, 5)
  4804. // (true, fmt)
  4805. function listWeekdaysImpl (localeSorted, format, index, field) {
  4806. if (typeof localeSorted === 'boolean') {
  4807. if (isNumber(format)) {
  4808. index = format;
  4809. format = undefined;
  4810. }
  4811. format = format || '';
  4812. } else {
  4813. format = localeSorted;
  4814. index = format;
  4815. localeSorted = false;
  4816. if (isNumber(format)) {
  4817. index = format;
  4818. format = undefined;
  4819. }
  4820. format = format || '';
  4821. }
  4822. var locale = getLocale(),
  4823. shift = localeSorted ? locale._week.dow : 0;
  4824. if (index != null) {
  4825. return get$1(format, (index + shift) % 7, field, 'day');
  4826. }
  4827. var i;
  4828. var out = [];
  4829. for (i = 0; i < 7; i++) {
  4830. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  4831. }
  4832. return out;
  4833. }
  4834. function listMonths (format, index) {
  4835. return listMonthsImpl(format, index, 'months');
  4836. }
  4837. function listMonthsShort (format, index) {
  4838. return listMonthsImpl(format, index, 'monthsShort');
  4839. }
  4840. function listWeekdays (localeSorted, format, index) {
  4841. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  4842. }
  4843. function listWeekdaysShort (localeSorted, format, index) {
  4844. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  4845. }
  4846. function listWeekdaysMin (localeSorted, format, index) {
  4847. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  4848. }
  4849. getSetGlobalLocale('en', {
  4850. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  4851. ordinal : function (number) {
  4852. var b = number % 10,
  4853. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  4854. (b === 1) ? 'st' :
  4855. (b === 2) ? 'nd' :
  4856. (b === 3) ? 'rd' : 'th';
  4857. return number + output;
  4858. }
  4859. });
  4860. // Side effect imports
  4861. hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
  4862. hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
  4863. var mathAbs = Math.abs;
  4864. function abs () {
  4865. var data = this._data;
  4866. this._milliseconds = mathAbs(this._milliseconds);
  4867. this._days = mathAbs(this._days);
  4868. this._months = mathAbs(this._months);
  4869. data.milliseconds = mathAbs(data.milliseconds);
  4870. data.seconds = mathAbs(data.seconds);
  4871. data.minutes = mathAbs(data.minutes);
  4872. data.hours = mathAbs(data.hours);
  4873. data.months = mathAbs(data.months);
  4874. data.years = mathAbs(data.years);
  4875. return this;
  4876. }
  4877. function addSubtract$1 (duration, input, value, direction) {
  4878. var other = createDuration(input, value);
  4879. duration._milliseconds += direction * other._milliseconds;
  4880. duration._days += direction * other._days;
  4881. duration._months += direction * other._months;
  4882. return duration._bubble();
  4883. }
  4884. // supports only 2.0-style add(1, 's') or add(duration)
  4885. function add$1 (input, value) {
  4886. return addSubtract$1(this, input, value, 1);
  4887. }
  4888. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  4889. function subtract$1 (input, value) {
  4890. return addSubtract$1(this, input, value, -1);
  4891. }
  4892. function absCeil (number) {
  4893. if (number < 0) {
  4894. return Math.floor(number);
  4895. } else {
  4896. return Math.ceil(number);
  4897. }
  4898. }
  4899. function bubble () {
  4900. var milliseconds = this._milliseconds;
  4901. var days = this._days;
  4902. var months = this._months;
  4903. var data = this._data;
  4904. var seconds, minutes, hours, years, monthsFromDays;
  4905. // if we have a mix of positive and negative values, bubble down first
  4906. // check: https://github.com/moment/moment/issues/2166
  4907. if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
  4908. (milliseconds <= 0 && days <= 0 && months <= 0))) {
  4909. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  4910. days = 0;
  4911. months = 0;
  4912. }
  4913. // The following code bubbles up values, see the tests for
  4914. // examples of what that means.
  4915. data.milliseconds = milliseconds % 1000;
  4916. seconds = absFloor(milliseconds / 1000);
  4917. data.seconds = seconds % 60;
  4918. minutes = absFloor(seconds / 60);
  4919. data.minutes = minutes % 60;
  4920. hours = absFloor(minutes / 60);
  4921. data.hours = hours % 24;
  4922. days += absFloor(hours / 24);
  4923. // convert days to months
  4924. monthsFromDays = absFloor(daysToMonths(days));
  4925. months += monthsFromDays;
  4926. days -= absCeil(monthsToDays(monthsFromDays));
  4927. // 12 months -> 1 year
  4928. years = absFloor(months / 12);
  4929. months %= 12;
  4930. data.days = days;
  4931. data.months = months;
  4932. data.years = years;
  4933. return this;
  4934. }
  4935. function daysToMonths (days) {
  4936. // 400 years have 146097 days (taking into account leap year rules)
  4937. // 400 years have 12 months === 4800
  4938. return days * 4800 / 146097;
  4939. }
  4940. function monthsToDays (months) {
  4941. // the reverse of daysToMonths
  4942. return months * 146097 / 4800;
  4943. }
  4944. function as (units) {
  4945. if (!this.isValid()) {
  4946. return NaN;
  4947. }
  4948. var days;
  4949. var months;
  4950. var milliseconds = this._milliseconds;
  4951. units = normalizeUnits(units);
  4952. if (units === 'month' || units === 'year') {
  4953. days = this._days + milliseconds / 864e5;
  4954. months = this._months + daysToMonths(days);
  4955. return units === 'month' ? months : months / 12;
  4956. } else {
  4957. // handle milliseconds separately because of floating point math errors (issue #1867)
  4958. days = this._days + Math.round(monthsToDays(this._months));
  4959. switch (units) {
  4960. case 'week' : return days / 7 + milliseconds / 6048e5;
  4961. case 'day' : return days + milliseconds / 864e5;
  4962. case 'hour' : return days * 24 + milliseconds / 36e5;
  4963. case 'minute' : return days * 1440 + milliseconds / 6e4;
  4964. case 'second' : return days * 86400 + milliseconds / 1000;
  4965. // Math.floor prevents floating point math errors here
  4966. case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
  4967. default: throw new Error('Unknown unit ' + units);
  4968. }
  4969. }
  4970. }
  4971. // TODO: Use this.as('ms')?
  4972. function valueOf$1 () {
  4973. if (!this.isValid()) {
  4974. return NaN;
  4975. }
  4976. return (
  4977. this._milliseconds +
  4978. this._days * 864e5 +
  4979. (this._months % 12) * 2592e6 +
  4980. toInt(this._months / 12) * 31536e6
  4981. );
  4982. }
  4983. function makeAs (alias) {
  4984. return function () {
  4985. return this.as(alias);
  4986. };
  4987. }
  4988. var asMilliseconds = makeAs('ms');
  4989. var asSeconds = makeAs('s');
  4990. var asMinutes = makeAs('m');
  4991. var asHours = makeAs('h');
  4992. var asDays = makeAs('d');
  4993. var asWeeks = makeAs('w');
  4994. var asMonths = makeAs('M');
  4995. var asYears = makeAs('y');
  4996. function clone$1 () {
  4997. return createDuration(this);
  4998. }
  4999. function get$2 (units) {
  5000. units = normalizeUnits(units);
  5001. return this.isValid() ? this[units + 's']() : NaN;
  5002. }
  5003. function makeGetter(name) {
  5004. return function () {
  5005. return this.isValid() ? this._data[name] : NaN;
  5006. };
  5007. }
  5008. var milliseconds = makeGetter('milliseconds');
  5009. var seconds = makeGetter('seconds');
  5010. var minutes = makeGetter('minutes');
  5011. var hours = makeGetter('hours');
  5012. var days = makeGetter('days');
  5013. var months = makeGetter('months');
  5014. var years = makeGetter('years');
  5015. function weeks () {
  5016. return absFloor(this.days() / 7);
  5017. }
  5018. var round = Math.round;
  5019. var thresholds = {
  5020. ss: 44, // a few seconds to seconds
  5021. s : 45, // seconds to minute
  5022. m : 45, // minutes to hour
  5023. h : 22, // hours to day
  5024. d : 26, // days to month
  5025. M : 11 // months to year
  5026. };
  5027. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  5028. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  5029. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  5030. }
  5031. function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
  5032. var duration = createDuration(posNegDuration).abs();
  5033. var seconds = round(duration.as('s'));
  5034. var minutes = round(duration.as('m'));
  5035. var hours = round(duration.as('h'));
  5036. var days = round(duration.as('d'));
  5037. var months = round(duration.as('M'));
  5038. var years = round(duration.as('y'));
  5039. var a = seconds <= thresholds.ss && ['s', seconds] ||
  5040. seconds < thresholds.s && ['ss', seconds] ||
  5041. minutes <= 1 && ['m'] ||
  5042. minutes < thresholds.m && ['mm', minutes] ||
  5043. hours <= 1 && ['h'] ||
  5044. hours < thresholds.h && ['hh', hours] ||
  5045. days <= 1 && ['d'] ||
  5046. days < thresholds.d && ['dd', days] ||
  5047. months <= 1 && ['M'] ||
  5048. months < thresholds.M && ['MM', months] ||
  5049. years <= 1 && ['y'] || ['yy', years];
  5050. a[2] = withoutSuffix;
  5051. a[3] = +posNegDuration > 0;
  5052. a[4] = locale;
  5053. return substituteTimeAgo.apply(null, a);
  5054. }
  5055. // This function allows you to set the rounding function for relative time strings
  5056. function getSetRelativeTimeRounding (roundingFunction) {
  5057. if (roundingFunction === undefined) {
  5058. return round;
  5059. }
  5060. if (typeof(roundingFunction) === 'function') {
  5061. round = roundingFunction;
  5062. return true;
  5063. }
  5064. return false;
  5065. }
  5066. // This function allows you to set a threshold for relative time strings
  5067. function getSetRelativeTimeThreshold (threshold, limit) {
  5068. if (thresholds[threshold] === undefined) {
  5069. return false;
  5070. }
  5071. if (limit === undefined) {
  5072. return thresholds[threshold];
  5073. }
  5074. thresholds[threshold] = limit;
  5075. if (threshold === 's') {
  5076. thresholds.ss = limit - 1;
  5077. }
  5078. return true;
  5079. }
  5080. function humanize (withSuffix) {
  5081. if (!this.isValid()) {
  5082. return this.localeData().invalidDate();
  5083. }
  5084. var locale = this.localeData();
  5085. var output = relativeTime$1(this, !withSuffix, locale);
  5086. if (withSuffix) {
  5087. output = locale.pastFuture(+this, output);
  5088. }
  5089. return locale.postformat(output);
  5090. }
  5091. var abs$1 = Math.abs;
  5092. function sign(x) {
  5093. return ((x > 0) - (x < 0)) || +x;
  5094. }
  5095. function toISOString$1() {
  5096. // for ISO strings we do not use the normal bubbling rules:
  5097. // * milliseconds bubble up until they become hours
  5098. // * days do not bubble at all
  5099. // * months bubble up until they become years
  5100. // This is because there is no context-free conversion between hours and days
  5101. // (think of clock changes)
  5102. // and also not between days and months (28-31 days per month)
  5103. if (!this.isValid()) {
  5104. return this.localeData().invalidDate();
  5105. }
  5106. var seconds = abs$1(this._milliseconds) / 1000;
  5107. var days = abs$1(this._days);
  5108. var months = abs$1(this._months);
  5109. var minutes, hours, years;
  5110. // 3600 seconds -> 60 minutes -> 1 hour
  5111. minutes = absFloor(seconds / 60);
  5112. hours = absFloor(minutes / 60);
  5113. seconds %= 60;
  5114. minutes %= 60;
  5115. // 12 months -> 1 year
  5116. years = absFloor(months / 12);
  5117. months %= 12;
  5118. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  5119. var Y = years;
  5120. var M = months;
  5121. var D = days;
  5122. var h = hours;
  5123. var m = minutes;
  5124. var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  5125. var total = this.asSeconds();
  5126. if (!total) {
  5127. // this is the same as C#'s (Noda) and python (isodate)...
  5128. // but not other JS (goog.date)
  5129. return 'P0D';
  5130. }
  5131. var totalSign = total < 0 ? '-' : '';
  5132. var ymSign = sign(this._months) !== sign(total) ? '-' : '';
  5133. var daysSign = sign(this._days) !== sign(total) ? '-' : '';
  5134. var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  5135. return totalSign + 'P' +
  5136. (Y ? ymSign + Y + 'Y' : '') +
  5137. (M ? ymSign + M + 'M' : '') +
  5138. (D ? daysSign + D + 'D' : '') +
  5139. ((h || m || s) ? 'T' : '') +
  5140. (h ? hmsSign + h + 'H' : '') +
  5141. (m ? hmsSign + m + 'M' : '') +
  5142. (s ? hmsSign + s + 'S' : '');
  5143. }
  5144. var proto$2 = Duration.prototype;
  5145. proto$2.isValid = isValid$1;
  5146. proto$2.abs = abs;
  5147. proto$2.add = add$1;
  5148. proto$2.subtract = subtract$1;
  5149. proto$2.as = as;
  5150. proto$2.asMilliseconds = asMilliseconds;
  5151. proto$2.asSeconds = asSeconds;
  5152. proto$2.asMinutes = asMinutes;
  5153. proto$2.asHours = asHours;
  5154. proto$2.asDays = asDays;
  5155. proto$2.asWeeks = asWeeks;
  5156. proto$2.asMonths = asMonths;
  5157. proto$2.asYears = asYears;
  5158. proto$2.valueOf = valueOf$1;
  5159. proto$2._bubble = bubble;
  5160. proto$2.clone = clone$1;
  5161. proto$2.get = get$2;
  5162. proto$2.milliseconds = milliseconds;
  5163. proto$2.seconds = seconds;
  5164. proto$2.minutes = minutes;
  5165. proto$2.hours = hours;
  5166. proto$2.days = days;
  5167. proto$2.weeks = weeks;
  5168. proto$2.months = months;
  5169. proto$2.years = years;
  5170. proto$2.humanize = humanize;
  5171. proto$2.toISOString = toISOString$1;
  5172. proto$2.toString = toISOString$1;
  5173. proto$2.toJSON = toISOString$1;
  5174. proto$2.locale = locale;
  5175. proto$2.localeData = localeData;
  5176. proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
  5177. proto$2.lang = lang;
  5178. // Side effect imports
  5179. // FORMATTING
  5180. addFormatToken('X', 0, 0, 'unix');
  5181. addFormatToken('x', 0, 0, 'valueOf');
  5182. // PARSING
  5183. addRegexToken('x', matchSigned);
  5184. addRegexToken('X', matchTimestamp);
  5185. addParseToken('X', function (input, array, config) {
  5186. config._d = new Date(parseFloat(input, 10) * 1000);
  5187. });
  5188. addParseToken('x', function (input, array, config) {
  5189. config._d = new Date(toInt(input));
  5190. });
  5191. // Side effect imports
  5192. hooks.version = '2.22.2';
  5193. setHookCallback(createLocal);
  5194. hooks.fn = proto;
  5195. hooks.min = min;
  5196. hooks.max = max;
  5197. hooks.now = now;
  5198. hooks.utc = createUTC;
  5199. hooks.unix = createUnix;
  5200. hooks.months = listMonths;
  5201. hooks.isDate = isDate;
  5202. hooks.locale = getSetGlobalLocale;
  5203. hooks.invalid = createInvalid;
  5204. hooks.duration = createDuration;
  5205. hooks.isMoment = isMoment;
  5206. hooks.weekdays = listWeekdays;
  5207. hooks.parseZone = createInZone;
  5208. hooks.localeData = getLocale;
  5209. hooks.isDuration = isDuration;
  5210. hooks.monthsShort = listMonthsShort;
  5211. hooks.weekdaysMin = listWeekdaysMin;
  5212. hooks.defineLocale = defineLocale;
  5213. hooks.updateLocale = updateLocale;
  5214. hooks.locales = listLocales;
  5215. hooks.weekdaysShort = listWeekdaysShort;
  5216. hooks.normalizeUnits = normalizeUnits;
  5217. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  5218. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  5219. hooks.calendarFormat = getCalendarFormat;
  5220. hooks.prototype = proto;
  5221. // currently HTML5 input type only supports 24-hour formats
  5222. hooks.HTML5_FMT = {
  5223. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  5224. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  5225. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  5226. DATE: 'YYYY-MM-DD', // <input type="date" />
  5227. TIME: 'HH:mm', // <input type="time" />
  5228. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  5229. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  5230. WEEK: 'YYYY-[W]WW', // <input type="week" />
  5231. MONTH: 'YYYY-MM' // <input type="month" />
  5232. };
  5233. return hooks;
  5234. })));
  5235. },{}],7:[function(require,module,exports){
  5236. /**
  5237. * @namespace Chart
  5238. */
  5239. var Chart = require(30)();
  5240. Chart.helpers = require(46);
  5241. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  5242. require(28)(Chart);
  5243. Chart.Animation = require(22);
  5244. Chart.animationService = require(23);
  5245. Chart.defaults = require(26);
  5246. Chart.Element = require(27);
  5247. Chart.elements = require(41);
  5248. Chart.Interaction = require(29);
  5249. Chart.layouts = require(31);
  5250. Chart.platform = require(49);
  5251. Chart.plugins = require(32);
  5252. Chart.Scale = require(33);
  5253. Chart.scaleService = require(34);
  5254. Chart.Ticks = require(35);
  5255. Chart.Tooltip = require(36);
  5256. require(24)(Chart);
  5257. require(25)(Chart);
  5258. require(56)(Chart);
  5259. require(54)(Chart);
  5260. require(55)(Chart);
  5261. require(57)(Chart);
  5262. require(58)(Chart);
  5263. require(59)(Chart);
  5264. // Controllers must be loaded after elements
  5265. // See Chart.core.datasetController.dataElementType
  5266. require(15)(Chart);
  5267. require(16)(Chart);
  5268. require(17)(Chart);
  5269. require(18)(Chart);
  5270. require(19)(Chart);
  5271. require(20)(Chart);
  5272. require(21)(Chart);
  5273. require(8)(Chart);
  5274. require(9)(Chart);
  5275. require(10)(Chart);
  5276. require(11)(Chart);
  5277. require(12)(Chart);
  5278. require(13)(Chart);
  5279. require(14)(Chart);
  5280. // Loading built-in plugins
  5281. var plugins = require(50);
  5282. for (var k in plugins) {
  5283. if (plugins.hasOwnProperty(k)) {
  5284. Chart.plugins.register(plugins[k]);
  5285. }
  5286. }
  5287. Chart.platform.initialize();
  5288. module.exports = Chart;
  5289. if (typeof window !== 'undefined') {
  5290. window.Chart = Chart;
  5291. }
  5292. // DEPRECATIONS
  5293. /**
  5294. * Provided for backward compatibility, not available anymore
  5295. * @namespace Chart.Legend
  5296. * @deprecated since version 2.1.5
  5297. * @todo remove at version 3
  5298. * @private
  5299. */
  5300. Chart.Legend = plugins.legend._element;
  5301. /**
  5302. * Provided for backward compatibility, not available anymore
  5303. * @namespace Chart.Title
  5304. * @deprecated since version 2.1.5
  5305. * @todo remove at version 3
  5306. * @private
  5307. */
  5308. Chart.Title = plugins.title._element;
  5309. /**
  5310. * Provided for backward compatibility, use Chart.plugins instead
  5311. * @namespace Chart.pluginService
  5312. * @deprecated since version 2.1.5
  5313. * @todo remove at version 3
  5314. * @private
  5315. */
  5316. Chart.pluginService = Chart.plugins;
  5317. /**
  5318. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  5319. * effect, instead simply create/register plugins via plain JavaScript objects.
  5320. * @interface Chart.PluginBase
  5321. * @deprecated since version 2.5.0
  5322. * @todo remove at version 3
  5323. * @private
  5324. */
  5325. Chart.PluginBase = Chart.Element.extend({});
  5326. /**
  5327. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  5328. * @namespace Chart.canvasHelpers
  5329. * @deprecated since version 2.6.0
  5330. * @todo remove at version 3
  5331. * @private
  5332. */
  5333. Chart.canvasHelpers = Chart.helpers.canvas;
  5334. /**
  5335. * Provided for backward compatibility, use Chart.layouts instead.
  5336. * @namespace Chart.layoutService
  5337. * @deprecated since version 2.8.0
  5338. * @todo remove at version 3
  5339. * @private
  5340. */
  5341. Chart.layoutService = Chart.layouts;
  5342. },{"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"26":26,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"34":34,"35":35,"36":36,"41":41,"46":46,"49":49,"50":50,"54":54,"55":55,"56":56,"57":57,"58":58,"59":59,"8":8,"9":9}],8:[function(require,module,exports){
  5343. 'use strict';
  5344. module.exports = function(Chart) {
  5345. Chart.Bar = function(context, config) {
  5346. config.type = 'bar';
  5347. return new Chart(context, config);
  5348. };
  5349. };
  5350. },{}],9:[function(require,module,exports){
  5351. 'use strict';
  5352. module.exports = function(Chart) {
  5353. Chart.Bubble = function(context, config) {
  5354. config.type = 'bubble';
  5355. return new Chart(context, config);
  5356. };
  5357. };
  5358. },{}],10:[function(require,module,exports){
  5359. 'use strict';
  5360. module.exports = function(Chart) {
  5361. Chart.Doughnut = function(context, config) {
  5362. config.type = 'doughnut';
  5363. return new Chart(context, config);
  5364. };
  5365. };
  5366. },{}],11:[function(require,module,exports){
  5367. 'use strict';
  5368. module.exports = function(Chart) {
  5369. Chart.Line = function(context, config) {
  5370. config.type = 'line';
  5371. return new Chart(context, config);
  5372. };
  5373. };
  5374. },{}],12:[function(require,module,exports){
  5375. 'use strict';
  5376. module.exports = function(Chart) {
  5377. Chart.PolarArea = function(context, config) {
  5378. config.type = 'polarArea';
  5379. return new Chart(context, config);
  5380. };
  5381. };
  5382. },{}],13:[function(require,module,exports){
  5383. 'use strict';
  5384. module.exports = function(Chart) {
  5385. Chart.Radar = function(context, config) {
  5386. config.type = 'radar';
  5387. return new Chart(context, config);
  5388. };
  5389. };
  5390. },{}],14:[function(require,module,exports){
  5391. 'use strict';
  5392. module.exports = function(Chart) {
  5393. Chart.Scatter = function(context, config) {
  5394. config.type = 'scatter';
  5395. return new Chart(context, config);
  5396. };
  5397. };
  5398. },{}],15:[function(require,module,exports){
  5399. 'use strict';
  5400. var defaults = require(26);
  5401. var elements = require(41);
  5402. var helpers = require(46);
  5403. defaults._set('bar', {
  5404. hover: {
  5405. mode: 'label'
  5406. },
  5407. scales: {
  5408. xAxes: [{
  5409. type: 'category',
  5410. // Specific to Bar Controller
  5411. categoryPercentage: 0.8,
  5412. barPercentage: 0.9,
  5413. // offset settings
  5414. offset: true,
  5415. // grid line settings
  5416. gridLines: {
  5417. offsetGridLines: true
  5418. }
  5419. }],
  5420. yAxes: [{
  5421. type: 'linear'
  5422. }]
  5423. }
  5424. });
  5425. defaults._set('horizontalBar', {
  5426. hover: {
  5427. mode: 'index',
  5428. axis: 'y'
  5429. },
  5430. scales: {
  5431. xAxes: [{
  5432. type: 'linear',
  5433. position: 'bottom'
  5434. }],
  5435. yAxes: [{
  5436. position: 'left',
  5437. type: 'category',
  5438. // Specific to Horizontal Bar Controller
  5439. categoryPercentage: 0.8,
  5440. barPercentage: 0.9,
  5441. // offset settings
  5442. offset: true,
  5443. // grid line settings
  5444. gridLines: {
  5445. offsetGridLines: true
  5446. }
  5447. }]
  5448. },
  5449. elements: {
  5450. rectangle: {
  5451. borderSkipped: 'left'
  5452. }
  5453. },
  5454. tooltips: {
  5455. callbacks: {
  5456. title: function(item, data) {
  5457. // Pick first xLabel for now
  5458. var title = '';
  5459. if (item.length > 0) {
  5460. if (item[0].yLabel) {
  5461. title = item[0].yLabel;
  5462. } else if (data.labels.length > 0 && item[0].index < data.labels.length) {
  5463. title = data.labels[item[0].index];
  5464. }
  5465. }
  5466. return title;
  5467. },
  5468. label: function(item, data) {
  5469. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  5470. return datasetLabel + ': ' + item.xLabel;
  5471. }
  5472. },
  5473. mode: 'index',
  5474. axis: 'y'
  5475. }
  5476. });
  5477. /**
  5478. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  5479. * @private
  5480. */
  5481. function computeMinSampleSize(scale, pixels) {
  5482. var min = scale.isHorizontal() ? scale.width : scale.height;
  5483. var ticks = scale.getTicks();
  5484. var prev, curr, i, ilen;
  5485. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  5486. min = Math.min(min, pixels[i] - pixels[i - 1]);
  5487. }
  5488. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  5489. curr = scale.getPixelForTick(i);
  5490. min = i > 0 ? Math.min(min, curr - prev) : min;
  5491. prev = curr;
  5492. }
  5493. return min;
  5494. }
  5495. /**
  5496. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  5497. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  5498. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  5499. * @private
  5500. */
  5501. function computeFitCategoryTraits(index, ruler, options) {
  5502. var thickness = options.barThickness;
  5503. var count = ruler.stackCount;
  5504. var curr = ruler.pixels[index];
  5505. var size, ratio;
  5506. if (helpers.isNullOrUndef(thickness)) {
  5507. size = ruler.min * options.categoryPercentage;
  5508. ratio = options.barPercentage;
  5509. } else {
  5510. // When bar thickness is enforced, category and bar percentages are ignored.
  5511. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  5512. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  5513. size = thickness * count;
  5514. ratio = 1;
  5515. }
  5516. return {
  5517. chunk: size / count,
  5518. ratio: ratio,
  5519. start: curr - (size / 2)
  5520. };
  5521. }
  5522. /**
  5523. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  5524. * percentage options are 1), based on the previous and following categories. This mode
  5525. * generates bars with different widths when data are not evenly spaced.
  5526. * @private
  5527. */
  5528. function computeFlexCategoryTraits(index, ruler, options) {
  5529. var pixels = ruler.pixels;
  5530. var curr = pixels[index];
  5531. var prev = index > 0 ? pixels[index - 1] : null;
  5532. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  5533. var percent = options.categoryPercentage;
  5534. var start, size;
  5535. if (prev === null) {
  5536. // first data: its size is double based on the next point or,
  5537. // if it's also the last data, we use the scale end extremity.
  5538. prev = curr - (next === null ? ruler.end - curr : next - curr);
  5539. }
  5540. if (next === null) {
  5541. // last data: its size is also double based on the previous point.
  5542. next = curr + curr - prev;
  5543. }
  5544. start = curr - ((curr - prev) / 2) * percent;
  5545. size = ((next - prev) / 2) * percent;
  5546. return {
  5547. chunk: size / ruler.stackCount,
  5548. ratio: options.barPercentage,
  5549. start: start
  5550. };
  5551. }
  5552. module.exports = function(Chart) {
  5553. Chart.controllers.bar = Chart.DatasetController.extend({
  5554. dataElementType: elements.Rectangle,
  5555. initialize: function() {
  5556. var me = this;
  5557. var meta;
  5558. Chart.DatasetController.prototype.initialize.apply(me, arguments);
  5559. meta = me.getMeta();
  5560. meta.stack = me.getDataset().stack;
  5561. meta.bar = true;
  5562. },
  5563. update: function(reset) {
  5564. var me = this;
  5565. var rects = me.getMeta().data;
  5566. var i, ilen;
  5567. me._ruler = me.getRuler();
  5568. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  5569. me.updateElement(rects[i], i, reset);
  5570. }
  5571. },
  5572. updateElement: function(rectangle, index, reset) {
  5573. var me = this;
  5574. var chart = me.chart;
  5575. var meta = me.getMeta();
  5576. var dataset = me.getDataset();
  5577. var custom = rectangle.custom || {};
  5578. var rectangleOptions = chart.options.elements.rectangle;
  5579. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  5580. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  5581. rectangle._datasetIndex = me.index;
  5582. rectangle._index = index;
  5583. rectangle._model = {
  5584. datasetLabel: dataset.label,
  5585. label: chart.data.labels[index],
  5586. borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleOptions.borderSkipped,
  5587. backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleOptions.backgroundColor),
  5588. borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleOptions.borderColor),
  5589. borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleOptions.borderWidth)
  5590. };
  5591. me.updateElementGeometry(rectangle, index, reset);
  5592. rectangle.pivot();
  5593. },
  5594. /**
  5595. * @private
  5596. */
  5597. updateElementGeometry: function(rectangle, index, reset) {
  5598. var me = this;
  5599. var model = rectangle._model;
  5600. var vscale = me.getValueScale();
  5601. var base = vscale.getBasePixel();
  5602. var horizontal = vscale.isHorizontal();
  5603. var ruler = me._ruler || me.getRuler();
  5604. var vpixels = me.calculateBarValuePixels(me.index, index);
  5605. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
  5606. model.horizontal = horizontal;
  5607. model.base = reset ? base : vpixels.base;
  5608. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  5609. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  5610. model.height = horizontal ? ipixels.size : undefined;
  5611. model.width = horizontal ? undefined : ipixels.size;
  5612. },
  5613. /**
  5614. * @private
  5615. */
  5616. getValueScaleId: function() {
  5617. return this.getMeta().yAxisID;
  5618. },
  5619. /**
  5620. * @private
  5621. */
  5622. getIndexScaleId: function() {
  5623. return this.getMeta().xAxisID;
  5624. },
  5625. /**
  5626. * @private
  5627. */
  5628. getValueScale: function() {
  5629. return this.getScaleForId(this.getValueScaleId());
  5630. },
  5631. /**
  5632. * @private
  5633. */
  5634. getIndexScale: function() {
  5635. return this.getScaleForId(this.getIndexScaleId());
  5636. },
  5637. /**
  5638. * Returns the stacks based on groups and bar visibility.
  5639. * @param {Number} [last] - The dataset index
  5640. * @returns {Array} The stack list
  5641. * @private
  5642. */
  5643. _getStacks: function(last) {
  5644. var me = this;
  5645. var chart = me.chart;
  5646. var scale = me.getIndexScale();
  5647. var stacked = scale.options.stacked;
  5648. var ilen = last === undefined ? chart.data.datasets.length : last + 1;
  5649. var stacks = [];
  5650. var i, meta;
  5651. for (i = 0; i < ilen; ++i) {
  5652. meta = chart.getDatasetMeta(i);
  5653. if (meta.bar && chart.isDatasetVisible(i) &&
  5654. (stacked === false ||
  5655. (stacked === true && stacks.indexOf(meta.stack) === -1) ||
  5656. (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
  5657. stacks.push(meta.stack);
  5658. }
  5659. }
  5660. return stacks;
  5661. },
  5662. /**
  5663. * Returns the effective number of stacks based on groups and bar visibility.
  5664. * @private
  5665. */
  5666. getStackCount: function() {
  5667. return this._getStacks().length;
  5668. },
  5669. /**
  5670. * Returns the stack index for the given dataset based on groups and bar visibility.
  5671. * @param {Number} [datasetIndex] - The dataset index
  5672. * @param {String} [name] - The stack name to find
  5673. * @returns {Number} The stack index
  5674. * @private
  5675. */
  5676. getStackIndex: function(datasetIndex, name) {
  5677. var stacks = this._getStacks(datasetIndex);
  5678. var index = (name !== undefined)
  5679. ? stacks.indexOf(name)
  5680. : -1; // indexOf returns -1 if element is not present
  5681. return (index === -1)
  5682. ? stacks.length - 1
  5683. : index;
  5684. },
  5685. /**
  5686. * @private
  5687. */
  5688. getRuler: function() {
  5689. var me = this;
  5690. var scale = me.getIndexScale();
  5691. var stackCount = me.getStackCount();
  5692. var datasetIndex = me.index;
  5693. var isHorizontal = scale.isHorizontal();
  5694. var start = isHorizontal ? scale.left : scale.top;
  5695. var end = start + (isHorizontal ? scale.width : scale.height);
  5696. var pixels = [];
  5697. var i, ilen, min;
  5698. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  5699. pixels.push(scale.getPixelForValue(null, i, datasetIndex));
  5700. }
  5701. min = helpers.isNullOrUndef(scale.options.barThickness)
  5702. ? computeMinSampleSize(scale, pixels)
  5703. : -1;
  5704. return {
  5705. min: min,
  5706. pixels: pixels,
  5707. start: start,
  5708. end: end,
  5709. stackCount: stackCount,
  5710. scale: scale
  5711. };
  5712. },
  5713. /**
  5714. * Note: pixel values are not clamped to the scale area.
  5715. * @private
  5716. */
  5717. calculateBarValuePixels: function(datasetIndex, index) {
  5718. var me = this;
  5719. var chart = me.chart;
  5720. var meta = me.getMeta();
  5721. var scale = me.getValueScale();
  5722. var datasets = chart.data.datasets;
  5723. var value = scale.getRightValue(datasets[datasetIndex].data[index]);
  5724. var stacked = scale.options.stacked;
  5725. var stack = meta.stack;
  5726. var start = 0;
  5727. var i, imeta, ivalue, base, head, size;
  5728. if (stacked || (stacked === undefined && stack !== undefined)) {
  5729. for (i = 0; i < datasetIndex; ++i) {
  5730. imeta = chart.getDatasetMeta(i);
  5731. if (imeta.bar &&
  5732. imeta.stack === stack &&
  5733. imeta.controller.getValueScaleId() === scale.id &&
  5734. chart.isDatasetVisible(i)) {
  5735. ivalue = scale.getRightValue(datasets[i].data[index]);
  5736. if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
  5737. start += ivalue;
  5738. }
  5739. }
  5740. }
  5741. }
  5742. base = scale.getPixelForValue(start);
  5743. head = scale.getPixelForValue(start + value);
  5744. size = (head - base) / 2;
  5745. return {
  5746. size: size,
  5747. base: base,
  5748. head: head,
  5749. center: head + size / 2
  5750. };
  5751. },
  5752. /**
  5753. * @private
  5754. */
  5755. calculateBarIndexPixels: function(datasetIndex, index, ruler) {
  5756. var me = this;
  5757. var options = ruler.scale.options;
  5758. var range = options.barThickness === 'flex'
  5759. ? computeFlexCategoryTraits(index, ruler, options)
  5760. : computeFitCategoryTraits(index, ruler, options);
  5761. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  5762. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  5763. var size = Math.min(
  5764. helpers.valueOrDefault(options.maxBarThickness, Infinity),
  5765. range.chunk * range.ratio);
  5766. return {
  5767. base: center - size / 2,
  5768. head: center + size / 2,
  5769. center: center,
  5770. size: size
  5771. };
  5772. },
  5773. draw: function() {
  5774. var me = this;
  5775. var chart = me.chart;
  5776. var scale = me.getValueScale();
  5777. var rects = me.getMeta().data;
  5778. var dataset = me.getDataset();
  5779. var ilen = rects.length;
  5780. var i = 0;
  5781. helpers.canvas.clipArea(chart.ctx, chart.chartArea);
  5782. for (; i < ilen; ++i) {
  5783. if (!isNaN(scale.getRightValue(dataset.data[i]))) {
  5784. rects[i].draw();
  5785. }
  5786. }
  5787. helpers.canvas.unclipArea(chart.ctx);
  5788. },
  5789. });
  5790. Chart.controllers.horizontalBar = Chart.controllers.bar.extend({
  5791. /**
  5792. * @private
  5793. */
  5794. getValueScaleId: function() {
  5795. return this.getMeta().xAxisID;
  5796. },
  5797. /**
  5798. * @private
  5799. */
  5800. getIndexScaleId: function() {
  5801. return this.getMeta().yAxisID;
  5802. }
  5803. });
  5804. };
  5805. },{"26":26,"41":41,"46":46}],16:[function(require,module,exports){
  5806. 'use strict';
  5807. var defaults = require(26);
  5808. var elements = require(41);
  5809. var helpers = require(46);
  5810. defaults._set('bubble', {
  5811. hover: {
  5812. mode: 'single'
  5813. },
  5814. scales: {
  5815. xAxes: [{
  5816. type: 'linear', // bubble should probably use a linear scale by default
  5817. position: 'bottom',
  5818. id: 'x-axis-0' // need an ID so datasets can reference the scale
  5819. }],
  5820. yAxes: [{
  5821. type: 'linear',
  5822. position: 'left',
  5823. id: 'y-axis-0'
  5824. }]
  5825. },
  5826. tooltips: {
  5827. callbacks: {
  5828. title: function() {
  5829. // Title doesn't make sense for scatter since we format the data as a point
  5830. return '';
  5831. },
  5832. label: function(item, data) {
  5833. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  5834. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  5835. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  5836. }
  5837. }
  5838. }
  5839. });
  5840. module.exports = function(Chart) {
  5841. Chart.controllers.bubble = Chart.DatasetController.extend({
  5842. /**
  5843. * @protected
  5844. */
  5845. dataElementType: elements.Point,
  5846. /**
  5847. * @protected
  5848. */
  5849. update: function(reset) {
  5850. var me = this;
  5851. var meta = me.getMeta();
  5852. var points = meta.data;
  5853. // Update Points
  5854. helpers.each(points, function(point, index) {
  5855. me.updateElement(point, index, reset);
  5856. });
  5857. },
  5858. /**
  5859. * @protected
  5860. */
  5861. updateElement: function(point, index, reset) {
  5862. var me = this;
  5863. var meta = me.getMeta();
  5864. var custom = point.custom || {};
  5865. var xScale = me.getScaleForId(meta.xAxisID);
  5866. var yScale = me.getScaleForId(meta.yAxisID);
  5867. var options = me._resolveElementOptions(point, index);
  5868. var data = me.getDataset().data[index];
  5869. var dsIndex = me.index;
  5870. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  5871. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  5872. point._xScale = xScale;
  5873. point._yScale = yScale;
  5874. point._options = options;
  5875. point._datasetIndex = dsIndex;
  5876. point._index = index;
  5877. point._model = {
  5878. backgroundColor: options.backgroundColor,
  5879. borderColor: options.borderColor,
  5880. borderWidth: options.borderWidth,
  5881. hitRadius: options.hitRadius,
  5882. pointStyle: options.pointStyle,
  5883. rotation: options.rotation,
  5884. radius: reset ? 0 : options.radius,
  5885. skip: custom.skip || isNaN(x) || isNaN(y),
  5886. x: x,
  5887. y: y,
  5888. };
  5889. point.pivot();
  5890. },
  5891. /**
  5892. * @protected
  5893. */
  5894. setHoverStyle: function(point) {
  5895. var model = point._model;
  5896. var options = point._options;
  5897. point.$previousStyle = {
  5898. backgroundColor: model.backgroundColor,
  5899. borderColor: model.borderColor,
  5900. borderWidth: model.borderWidth,
  5901. radius: model.radius
  5902. };
  5903. model.backgroundColor = helpers.valueOrDefault(options.hoverBackgroundColor, helpers.getHoverColor(options.backgroundColor));
  5904. model.borderColor = helpers.valueOrDefault(options.hoverBorderColor, helpers.getHoverColor(options.borderColor));
  5905. model.borderWidth = helpers.valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  5906. model.radius = options.radius + options.hoverRadius;
  5907. },
  5908. /**
  5909. * @private
  5910. */
  5911. _resolveElementOptions: function(point, index) {
  5912. var me = this;
  5913. var chart = me.chart;
  5914. var datasets = chart.data.datasets;
  5915. var dataset = datasets[me.index];
  5916. var custom = point.custom || {};
  5917. var options = chart.options.elements.point;
  5918. var resolve = helpers.options.resolve;
  5919. var data = dataset.data[index];
  5920. var values = {};
  5921. var i, ilen, key;
  5922. // Scriptable options
  5923. var context = {
  5924. chart: chart,
  5925. dataIndex: index,
  5926. dataset: dataset,
  5927. datasetIndex: me.index
  5928. };
  5929. var keys = [
  5930. 'backgroundColor',
  5931. 'borderColor',
  5932. 'borderWidth',
  5933. 'hoverBackgroundColor',
  5934. 'hoverBorderColor',
  5935. 'hoverBorderWidth',
  5936. 'hoverRadius',
  5937. 'hitRadius',
  5938. 'pointStyle',
  5939. 'rotation'
  5940. ];
  5941. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  5942. key = keys[i];
  5943. values[key] = resolve([
  5944. custom[key],
  5945. dataset[key],
  5946. options[key]
  5947. ], context, index);
  5948. }
  5949. // Custom radius resolution
  5950. values.radius = resolve([
  5951. custom.radius,
  5952. data ? data.r : undefined,
  5953. dataset.radius,
  5954. options.radius
  5955. ], context, index);
  5956. return values;
  5957. }
  5958. });
  5959. };
  5960. },{"26":26,"41":41,"46":46}],17:[function(require,module,exports){
  5961. 'use strict';
  5962. var defaults = require(26);
  5963. var elements = require(41);
  5964. var helpers = require(46);
  5965. defaults._set('doughnut', {
  5966. animation: {
  5967. // Boolean - Whether we animate the rotation of the Doughnut
  5968. animateRotate: true,
  5969. // Boolean - Whether we animate scaling the Doughnut from the centre
  5970. animateScale: false
  5971. },
  5972. hover: {
  5973. mode: 'single'
  5974. },
  5975. legendCallback: function(chart) {
  5976. var text = [];
  5977. text.push('<ul class="' + chart.id + '-legend">');
  5978. var data = chart.data;
  5979. var datasets = data.datasets;
  5980. var labels = data.labels;
  5981. if (datasets.length) {
  5982. for (var i = 0; i < datasets[0].data.length; ++i) {
  5983. text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
  5984. if (labels[i]) {
  5985. text.push(labels[i]);
  5986. }
  5987. text.push('</li>');
  5988. }
  5989. }
  5990. text.push('</ul>');
  5991. return text.join('');
  5992. },
  5993. legend: {
  5994. labels: {
  5995. generateLabels: function(chart) {
  5996. var data = chart.data;
  5997. if (data.labels.length && data.datasets.length) {
  5998. return data.labels.map(function(label, i) {
  5999. var meta = chart.getDatasetMeta(0);
  6000. var ds = data.datasets[0];
  6001. var arc = meta.data[i];
  6002. var custom = arc && arc.custom || {};
  6003. var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  6004. var arcOpts = chart.options.elements.arc;
  6005. var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
  6006. var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
  6007. var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
  6008. return {
  6009. text: label,
  6010. fillStyle: fill,
  6011. strokeStyle: stroke,
  6012. lineWidth: bw,
  6013. hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
  6014. // Extra data used for toggling the correct item
  6015. index: i
  6016. };
  6017. });
  6018. }
  6019. return [];
  6020. }
  6021. },
  6022. onClick: function(e, legendItem) {
  6023. var index = legendItem.index;
  6024. var chart = this.chart;
  6025. var i, ilen, meta;
  6026. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  6027. meta = chart.getDatasetMeta(i);
  6028. // toggle visibility of index if exists
  6029. if (meta.data[index]) {
  6030. meta.data[index].hidden = !meta.data[index].hidden;
  6031. }
  6032. }
  6033. chart.update();
  6034. }
  6035. },
  6036. // The percentage of the chart that we cut out of the middle.
  6037. cutoutPercentage: 50,
  6038. // The rotation of the chart, where the first data arc begins.
  6039. rotation: Math.PI * -0.5,
  6040. // The total circumference of the chart.
  6041. circumference: Math.PI * 2.0,
  6042. // Need to override these to give a nice default
  6043. tooltips: {
  6044. callbacks: {
  6045. title: function() {
  6046. return '';
  6047. },
  6048. label: function(tooltipItem, data) {
  6049. var dataLabel = data.labels[tooltipItem.index];
  6050. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  6051. if (helpers.isArray(dataLabel)) {
  6052. // show value on first line of multiline label
  6053. // need to clone because we are changing the value
  6054. dataLabel = dataLabel.slice();
  6055. dataLabel[0] += value;
  6056. } else {
  6057. dataLabel += value;
  6058. }
  6059. return dataLabel;
  6060. }
  6061. }
  6062. }
  6063. });
  6064. defaults._set('pie', helpers.clone(defaults.doughnut));
  6065. defaults._set('pie', {
  6066. cutoutPercentage: 0
  6067. });
  6068. module.exports = function(Chart) {
  6069. Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({
  6070. dataElementType: elements.Arc,
  6071. linkScales: helpers.noop,
  6072. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  6073. getRingIndex: function(datasetIndex) {
  6074. var ringIndex = 0;
  6075. for (var j = 0; j < datasetIndex; ++j) {
  6076. if (this.chart.isDatasetVisible(j)) {
  6077. ++ringIndex;
  6078. }
  6079. }
  6080. return ringIndex;
  6081. },
  6082. update: function(reset) {
  6083. var me = this;
  6084. var chart = me.chart;
  6085. var chartArea = chart.chartArea;
  6086. var opts = chart.options;
  6087. var arcOpts = opts.elements.arc;
  6088. var availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth;
  6089. var availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth;
  6090. var minSize = Math.min(availableWidth, availableHeight);
  6091. var offset = {x: 0, y: 0};
  6092. var meta = me.getMeta();
  6093. var cutoutPercentage = opts.cutoutPercentage;
  6094. var circumference = opts.circumference;
  6095. // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
  6096. if (circumference < Math.PI * 2.0) {
  6097. var startAngle = opts.rotation % (Math.PI * 2.0);
  6098. startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
  6099. var endAngle = startAngle + circumference;
  6100. var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
  6101. var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
  6102. var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
  6103. var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
  6104. var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
  6105. var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
  6106. var cutout = cutoutPercentage / 100.0;
  6107. var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))};
  6108. var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))};
  6109. var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
  6110. minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
  6111. offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
  6112. }
  6113. chart.borderWidth = me.getMaxBorderWidth(meta.data);
  6114. chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
  6115. chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
  6116. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  6117. chart.offsetX = offset.x * chart.outerRadius;
  6118. chart.offsetY = offset.y * chart.outerRadius;
  6119. meta.total = me.calculateTotal();
  6120. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index));
  6121. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0);
  6122. helpers.each(meta.data, function(arc, index) {
  6123. me.updateElement(arc, index, reset);
  6124. });
  6125. },
  6126. updateElement: function(arc, index, reset) {
  6127. var me = this;
  6128. var chart = me.chart;
  6129. var chartArea = chart.chartArea;
  6130. var opts = chart.options;
  6131. var animationOpts = opts.animation;
  6132. var centerX = (chartArea.left + chartArea.right) / 2;
  6133. var centerY = (chartArea.top + chartArea.bottom) / 2;
  6134. var startAngle = opts.rotation; // non reset case handled later
  6135. var endAngle = opts.rotation; // non reset case handled later
  6136. var dataset = me.getDataset();
  6137. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI));
  6138. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  6139. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  6140. var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  6141. helpers.extend(arc, {
  6142. // Utility
  6143. _datasetIndex: me.index,
  6144. _index: index,
  6145. // Desired view properties
  6146. _model: {
  6147. x: centerX + chart.offsetX,
  6148. y: centerY + chart.offsetY,
  6149. startAngle: startAngle,
  6150. endAngle: endAngle,
  6151. circumference: circumference,
  6152. outerRadius: outerRadius,
  6153. innerRadius: innerRadius,
  6154. label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  6155. }
  6156. });
  6157. var model = arc._model;
  6158. // Resets the visual styles
  6159. var custom = arc.custom || {};
  6160. var valueOrDefault = helpers.valueAtIndexOrDefault;
  6161. var elementOpts = this.chart.options.elements.arc;
  6162. model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor);
  6163. model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor);
  6164. model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth);
  6165. // Set correct angles if not resetting
  6166. if (!reset || !animationOpts.animateRotate) {
  6167. if (index === 0) {
  6168. model.startAngle = opts.rotation;
  6169. } else {
  6170. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  6171. }
  6172. model.endAngle = model.startAngle + model.circumference;
  6173. }
  6174. arc.pivot();
  6175. },
  6176. calculateTotal: function() {
  6177. var dataset = this.getDataset();
  6178. var meta = this.getMeta();
  6179. var total = 0;
  6180. var value;
  6181. helpers.each(meta.data, function(element, index) {
  6182. value = dataset.data[index];
  6183. if (!isNaN(value) && !element.hidden) {
  6184. total += Math.abs(value);
  6185. }
  6186. });
  6187. /* if (total === 0) {
  6188. total = NaN;
  6189. }*/
  6190. return total;
  6191. },
  6192. calculateCircumference: function(value) {
  6193. var total = this.getMeta().total;
  6194. if (total > 0 && !isNaN(value)) {
  6195. return (Math.PI * 2.0) * (Math.abs(value) / total);
  6196. }
  6197. return 0;
  6198. },
  6199. // gets the max border or hover width to properly scale pie charts
  6200. getMaxBorderWidth: function(arcs) {
  6201. var max = 0;
  6202. var index = this.index;
  6203. var length = arcs.length;
  6204. var borderWidth;
  6205. var hoverWidth;
  6206. for (var i = 0; i < length; i++) {
  6207. borderWidth = arcs[i]._model ? arcs[i]._model.borderWidth : 0;
  6208. hoverWidth = arcs[i]._chart ? arcs[i]._chart.config.data.datasets[index].hoverBorderWidth : 0;
  6209. max = borderWidth > max ? borderWidth : max;
  6210. max = hoverWidth > max ? hoverWidth : max;
  6211. }
  6212. return max;
  6213. }
  6214. });
  6215. };
  6216. },{"26":26,"41":41,"46":46}],18:[function(require,module,exports){
  6217. 'use strict';
  6218. var defaults = require(26);
  6219. var elements = require(41);
  6220. var helpers = require(46);
  6221. defaults._set('line', {
  6222. showLines: true,
  6223. spanGaps: false,
  6224. hover: {
  6225. mode: 'label'
  6226. },
  6227. scales: {
  6228. xAxes: [{
  6229. type: 'category',
  6230. id: 'x-axis-0'
  6231. }],
  6232. yAxes: [{
  6233. type: 'linear',
  6234. id: 'y-axis-0'
  6235. }]
  6236. }
  6237. });
  6238. module.exports = function(Chart) {
  6239. function lineEnabled(dataset, options) {
  6240. return helpers.valueOrDefault(dataset.showLine, options.showLines);
  6241. }
  6242. Chart.controllers.line = Chart.DatasetController.extend({
  6243. datasetElementType: elements.Line,
  6244. dataElementType: elements.Point,
  6245. update: function(reset) {
  6246. var me = this;
  6247. var meta = me.getMeta();
  6248. var line = meta.dataset;
  6249. var points = meta.data || [];
  6250. var options = me.chart.options;
  6251. var lineElementOptions = options.elements.line;
  6252. var scale = me.getScaleForId(meta.yAxisID);
  6253. var i, ilen, custom;
  6254. var dataset = me.getDataset();
  6255. var showLine = lineEnabled(dataset, options);
  6256. // Update Line
  6257. if (showLine) {
  6258. custom = line.custom || {};
  6259. // Compatibility: If the properties are defined with only the old name, use those values
  6260. if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
  6261. dataset.lineTension = dataset.tension;
  6262. }
  6263. // Utility
  6264. line._scale = scale;
  6265. line._datasetIndex = me.index;
  6266. // Data
  6267. line._children = points;
  6268. // Model
  6269. line._model = {
  6270. // Appearance
  6271. // The default behavior of lines is to break at null values, according
  6272. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  6273. // This option gives lines the ability to span gaps
  6274. spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps,
  6275. tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),
  6276. backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
  6277. borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
  6278. borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
  6279. borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
  6280. borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
  6281. borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
  6282. borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
  6283. fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
  6284. steppedLine: custom.steppedLine ? custom.steppedLine : helpers.valueOrDefault(dataset.steppedLine, lineElementOptions.stepped),
  6285. cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.valueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode),
  6286. };
  6287. line.pivot();
  6288. }
  6289. // Update Points
  6290. for (i = 0, ilen = points.length; i < ilen; ++i) {
  6291. me.updateElement(points[i], i, reset);
  6292. }
  6293. if (showLine && line._model.tension !== 0) {
  6294. me.updateBezierControlPoints();
  6295. }
  6296. // Now pivot the point for animation
  6297. for (i = 0, ilen = points.length; i < ilen; ++i) {
  6298. points[i].pivot();
  6299. }
  6300. },
  6301. getPointBackgroundColor: function(point, index) {
  6302. var backgroundColor = this.chart.options.elements.point.backgroundColor;
  6303. var dataset = this.getDataset();
  6304. var custom = point.custom || {};
  6305. if (custom.backgroundColor) {
  6306. backgroundColor = custom.backgroundColor;
  6307. } else if (dataset.pointBackgroundColor) {
  6308. backgroundColor = helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor);
  6309. } else if (dataset.backgroundColor) {
  6310. backgroundColor = dataset.backgroundColor;
  6311. }
  6312. return backgroundColor;
  6313. },
  6314. getPointBorderColor: function(point, index) {
  6315. var borderColor = this.chart.options.elements.point.borderColor;
  6316. var dataset = this.getDataset();
  6317. var custom = point.custom || {};
  6318. if (custom.borderColor) {
  6319. borderColor = custom.borderColor;
  6320. } else if (dataset.pointBorderColor) {
  6321. borderColor = helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor);
  6322. } else if (dataset.borderColor) {
  6323. borderColor = dataset.borderColor;
  6324. }
  6325. return borderColor;
  6326. },
  6327. getPointBorderWidth: function(point, index) {
  6328. var borderWidth = this.chart.options.elements.point.borderWidth;
  6329. var dataset = this.getDataset();
  6330. var custom = point.custom || {};
  6331. if (!isNaN(custom.borderWidth)) {
  6332. borderWidth = custom.borderWidth;
  6333. } else if (!isNaN(dataset.pointBorderWidth) || helpers.isArray(dataset.pointBorderWidth)) {
  6334. borderWidth = helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);
  6335. } else if (!isNaN(dataset.borderWidth)) {
  6336. borderWidth = dataset.borderWidth;
  6337. }
  6338. return borderWidth;
  6339. },
  6340. getPointRotation: function(point, index) {
  6341. var pointRotation = this.chart.options.elements.point.rotation;
  6342. var dataset = this.getDataset();
  6343. var custom = point.custom || {};
  6344. if (!isNaN(custom.rotation)) {
  6345. pointRotation = custom.rotation;
  6346. } else if (!isNaN(dataset.pointRotation) || helpers.isArray(dataset.pointRotation)) {
  6347. pointRotation = helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointRotation);
  6348. }
  6349. return pointRotation;
  6350. },
  6351. updateElement: function(point, index, reset) {
  6352. var me = this;
  6353. var meta = me.getMeta();
  6354. var custom = point.custom || {};
  6355. var dataset = me.getDataset();
  6356. var datasetIndex = me.index;
  6357. var value = dataset.data[index];
  6358. var yScale = me.getScaleForId(meta.yAxisID);
  6359. var xScale = me.getScaleForId(meta.xAxisID);
  6360. var pointOptions = me.chart.options.elements.point;
  6361. var x, y;
  6362. // Compatibility: If the properties are defined with only the old name, use those values
  6363. if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
  6364. dataset.pointRadius = dataset.radius;
  6365. }
  6366. if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
  6367. dataset.pointHitRadius = dataset.hitRadius;
  6368. }
  6369. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  6370. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  6371. // Utility
  6372. point._xScale = xScale;
  6373. point._yScale = yScale;
  6374. point._datasetIndex = datasetIndex;
  6375. point._index = index;
  6376. // Desired view properties
  6377. point._model = {
  6378. x: x,
  6379. y: y,
  6380. skip: custom.skip || isNaN(x) || isNaN(y),
  6381. // Appearance
  6382. radius: custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),
  6383. pointStyle: custom.pointStyle || helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),
  6384. rotation: me.getPointRotation(point, index),
  6385. backgroundColor: me.getPointBackgroundColor(point, index),
  6386. borderColor: me.getPointBorderColor(point, index),
  6387. borderWidth: me.getPointBorderWidth(point, index),
  6388. tension: meta.dataset._model ? meta.dataset._model.tension : 0,
  6389. steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false,
  6390. // Tooltip
  6391. hitRadius: custom.hitRadius || helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius)
  6392. };
  6393. },
  6394. calculatePointY: function(value, index, datasetIndex) {
  6395. var me = this;
  6396. var chart = me.chart;
  6397. var meta = me.getMeta();
  6398. var yScale = me.getScaleForId(meta.yAxisID);
  6399. var sumPos = 0;
  6400. var sumNeg = 0;
  6401. var i, ds, dsMeta;
  6402. if (yScale.options.stacked) {
  6403. for (i = 0; i < datasetIndex; i++) {
  6404. ds = chart.data.datasets[i];
  6405. dsMeta = chart.getDatasetMeta(i);
  6406. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
  6407. var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
  6408. if (stackedRightValue < 0) {
  6409. sumNeg += stackedRightValue || 0;
  6410. } else {
  6411. sumPos += stackedRightValue || 0;
  6412. }
  6413. }
  6414. }
  6415. var rightValue = Number(yScale.getRightValue(value));
  6416. if (rightValue < 0) {
  6417. return yScale.getPixelForValue(sumNeg + rightValue);
  6418. }
  6419. return yScale.getPixelForValue(sumPos + rightValue);
  6420. }
  6421. return yScale.getPixelForValue(value);
  6422. },
  6423. updateBezierControlPoints: function() {
  6424. var me = this;
  6425. var meta = me.getMeta();
  6426. var area = me.chart.chartArea;
  6427. var points = (meta.data || []);
  6428. var i, ilen, point, model, controlPoints;
  6429. // Only consider points that are drawn in case the spanGaps option is used
  6430. if (meta.dataset._model.spanGaps) {
  6431. points = points.filter(function(pt) {
  6432. return !pt._model.skip;
  6433. });
  6434. }
  6435. function capControlPoint(pt, min, max) {
  6436. return Math.max(Math.min(pt, max), min);
  6437. }
  6438. if (meta.dataset._model.cubicInterpolationMode === 'monotone') {
  6439. helpers.splineCurveMonotone(points);
  6440. } else {
  6441. for (i = 0, ilen = points.length; i < ilen; ++i) {
  6442. point = points[i];
  6443. model = point._model;
  6444. controlPoints = helpers.splineCurve(
  6445. helpers.previousItem(points, i)._model,
  6446. model,
  6447. helpers.nextItem(points, i)._model,
  6448. meta.dataset._model.tension
  6449. );
  6450. model.controlPointPreviousX = controlPoints.previous.x;
  6451. model.controlPointPreviousY = controlPoints.previous.y;
  6452. model.controlPointNextX = controlPoints.next.x;
  6453. model.controlPointNextY = controlPoints.next.y;
  6454. }
  6455. }
  6456. if (me.chart.options.elements.line.capBezierPoints) {
  6457. for (i = 0, ilen = points.length; i < ilen; ++i) {
  6458. model = points[i]._model;
  6459. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  6460. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  6461. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  6462. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  6463. }
  6464. }
  6465. },
  6466. draw: function() {
  6467. var me = this;
  6468. var chart = me.chart;
  6469. var meta = me.getMeta();
  6470. var points = meta.data || [];
  6471. var area = chart.chartArea;
  6472. var ilen = points.length;
  6473. var halfBorderWidth;
  6474. var i = 0;
  6475. if (lineEnabled(me.getDataset(), chart.options)) {
  6476. halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2;
  6477. helpers.canvas.clipArea(chart.ctx, {
  6478. left: area.left,
  6479. right: area.right,
  6480. top: area.top - halfBorderWidth,
  6481. bottom: area.bottom + halfBorderWidth
  6482. });
  6483. meta.dataset.draw();
  6484. helpers.canvas.unclipArea(chart.ctx);
  6485. }
  6486. // Draw the points
  6487. for (; i < ilen; ++i) {
  6488. points[i].draw(area);
  6489. }
  6490. },
  6491. setHoverStyle: function(element) {
  6492. // Point
  6493. var dataset = this.chart.data.datasets[element._datasetIndex];
  6494. var index = element._index;
  6495. var custom = element.custom || {};
  6496. var model = element._model;
  6497. element.$previousStyle = {
  6498. backgroundColor: model.backgroundColor,
  6499. borderColor: model.borderColor,
  6500. borderWidth: model.borderWidth,
  6501. radius: model.radius
  6502. };
  6503. model.backgroundColor = custom.hoverBackgroundColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
  6504. model.borderColor = custom.hoverBorderColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
  6505. model.borderWidth = custom.hoverBorderWidth || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
  6506. model.radius = custom.hoverRadius || helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
  6507. },
  6508. });
  6509. };
  6510. },{"26":26,"41":41,"46":46}],19:[function(require,module,exports){
  6511. 'use strict';
  6512. var defaults = require(26);
  6513. var elements = require(41);
  6514. var helpers = require(46);
  6515. defaults._set('polarArea', {
  6516. scale: {
  6517. type: 'radialLinear',
  6518. angleLines: {
  6519. display: false
  6520. },
  6521. gridLines: {
  6522. circular: true
  6523. },
  6524. pointLabels: {
  6525. display: false
  6526. },
  6527. ticks: {
  6528. beginAtZero: true
  6529. }
  6530. },
  6531. // Boolean - Whether to animate the rotation of the chart
  6532. animation: {
  6533. animateRotate: true,
  6534. animateScale: true
  6535. },
  6536. startAngle: -0.5 * Math.PI,
  6537. legendCallback: function(chart) {
  6538. var text = [];
  6539. text.push('<ul class="' + chart.id + '-legend">');
  6540. var data = chart.data;
  6541. var datasets = data.datasets;
  6542. var labels = data.labels;
  6543. if (datasets.length) {
  6544. for (var i = 0; i < datasets[0].data.length; ++i) {
  6545. text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
  6546. if (labels[i]) {
  6547. text.push(labels[i]);
  6548. }
  6549. text.push('</li>');
  6550. }
  6551. }
  6552. text.push('</ul>');
  6553. return text.join('');
  6554. },
  6555. legend: {
  6556. labels: {
  6557. generateLabels: function(chart) {
  6558. var data = chart.data;
  6559. if (data.labels.length && data.datasets.length) {
  6560. return data.labels.map(function(label, i) {
  6561. var meta = chart.getDatasetMeta(0);
  6562. var ds = data.datasets[0];
  6563. var arc = meta.data[i];
  6564. var custom = arc.custom || {};
  6565. var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  6566. var arcOpts = chart.options.elements.arc;
  6567. var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
  6568. var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
  6569. var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
  6570. return {
  6571. text: label,
  6572. fillStyle: fill,
  6573. strokeStyle: stroke,
  6574. lineWidth: bw,
  6575. hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
  6576. // Extra data used for toggling the correct item
  6577. index: i
  6578. };
  6579. });
  6580. }
  6581. return [];
  6582. }
  6583. },
  6584. onClick: function(e, legendItem) {
  6585. var index = legendItem.index;
  6586. var chart = this.chart;
  6587. var i, ilen, meta;
  6588. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  6589. meta = chart.getDatasetMeta(i);
  6590. meta.data[index].hidden = !meta.data[index].hidden;
  6591. }
  6592. chart.update();
  6593. }
  6594. },
  6595. // Need to override these to give a nice default
  6596. tooltips: {
  6597. callbacks: {
  6598. title: function() {
  6599. return '';
  6600. },
  6601. label: function(item, data) {
  6602. return data.labels[item.index] + ': ' + item.yLabel;
  6603. }
  6604. }
  6605. }
  6606. });
  6607. module.exports = function(Chart) {
  6608. Chart.controllers.polarArea = Chart.DatasetController.extend({
  6609. dataElementType: elements.Arc,
  6610. linkScales: helpers.noop,
  6611. update: function(reset) {
  6612. var me = this;
  6613. var dataset = me.getDataset();
  6614. var meta = me.getMeta();
  6615. var start = me.chart.options.startAngle || 0;
  6616. var starts = me._starts = [];
  6617. var angles = me._angles = [];
  6618. var i, ilen, angle;
  6619. me._updateRadius();
  6620. meta.count = me.countVisibleElements();
  6621. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  6622. starts[i] = start;
  6623. angle = me._computeAngle(i);
  6624. angles[i] = angle;
  6625. start += angle;
  6626. }
  6627. helpers.each(meta.data, function(arc, index) {
  6628. me.updateElement(arc, index, reset);
  6629. });
  6630. },
  6631. /**
  6632. * @private
  6633. */
  6634. _updateRadius: function() {
  6635. var me = this;
  6636. var chart = me.chart;
  6637. var chartArea = chart.chartArea;
  6638. var opts = chart.options;
  6639. var arcOpts = opts.elements.arc;
  6640. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  6641. chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0);
  6642. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  6643. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  6644. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  6645. me.innerRadius = me.outerRadius - chart.radiusLength;
  6646. },
  6647. updateElement: function(arc, index, reset) {
  6648. var me = this;
  6649. var chart = me.chart;
  6650. var dataset = me.getDataset();
  6651. var opts = chart.options;
  6652. var animationOpts = opts.animation;
  6653. var scale = chart.scale;
  6654. var labels = chart.data.labels;
  6655. var centerX = scale.xCenter;
  6656. var centerY = scale.yCenter;
  6657. // var negHalfPI = -0.5 * Math.PI;
  6658. var datasetStartAngle = opts.startAngle;
  6659. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  6660. var startAngle = me._starts[index];
  6661. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  6662. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  6663. helpers.extend(arc, {
  6664. // Utility
  6665. _datasetIndex: me.index,
  6666. _index: index,
  6667. _scale: scale,
  6668. // Desired view properties
  6669. _model: {
  6670. x: centerX,
  6671. y: centerY,
  6672. innerRadius: 0,
  6673. outerRadius: reset ? resetRadius : distance,
  6674. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  6675. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  6676. label: helpers.valueAtIndexOrDefault(labels, index, labels[index])
  6677. }
  6678. });
  6679. // Apply border and fill style
  6680. var elementOpts = this.chart.options.elements.arc;
  6681. var custom = arc.custom || {};
  6682. var valueOrDefault = helpers.valueAtIndexOrDefault;
  6683. var model = arc._model;
  6684. model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor);
  6685. model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor);
  6686. model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth);
  6687. arc.pivot();
  6688. },
  6689. countVisibleElements: function() {
  6690. var dataset = this.getDataset();
  6691. var meta = this.getMeta();
  6692. var count = 0;
  6693. helpers.each(meta.data, function(element, index) {
  6694. if (!isNaN(dataset.data[index]) && !element.hidden) {
  6695. count++;
  6696. }
  6697. });
  6698. return count;
  6699. },
  6700. /**
  6701. * @private
  6702. */
  6703. _computeAngle: function(index) {
  6704. var me = this;
  6705. var count = this.getMeta().count;
  6706. var dataset = me.getDataset();
  6707. var meta = me.getMeta();
  6708. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  6709. return 0;
  6710. }
  6711. // Scriptable options
  6712. var context = {
  6713. chart: me.chart,
  6714. dataIndex: index,
  6715. dataset: dataset,
  6716. datasetIndex: me.index
  6717. };
  6718. return helpers.options.resolve([
  6719. me.chart.options.elements.arc.angle,
  6720. (2 * Math.PI) / count
  6721. ], context, index);
  6722. }
  6723. });
  6724. };
  6725. },{"26":26,"41":41,"46":46}],20:[function(require,module,exports){
  6726. 'use strict';
  6727. var defaults = require(26);
  6728. var elements = require(41);
  6729. var helpers = require(46);
  6730. defaults._set('radar', {
  6731. scale: {
  6732. type: 'radialLinear'
  6733. },
  6734. elements: {
  6735. line: {
  6736. tension: 0 // no bezier in radar
  6737. }
  6738. }
  6739. });
  6740. module.exports = function(Chart) {
  6741. Chart.controllers.radar = Chart.DatasetController.extend({
  6742. datasetElementType: elements.Line,
  6743. dataElementType: elements.Point,
  6744. linkScales: helpers.noop,
  6745. update: function(reset) {
  6746. var me = this;
  6747. var meta = me.getMeta();
  6748. var line = meta.dataset;
  6749. var points = meta.data;
  6750. var custom = line.custom || {};
  6751. var dataset = me.getDataset();
  6752. var lineElementOptions = me.chart.options.elements.line;
  6753. var scale = me.chart.scale;
  6754. // Compatibility: If the properties are defined with only the old name, use those values
  6755. if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
  6756. dataset.lineTension = dataset.tension;
  6757. }
  6758. helpers.extend(meta.dataset, {
  6759. // Utility
  6760. _datasetIndex: me.index,
  6761. _scale: scale,
  6762. // Data
  6763. _children: points,
  6764. _loop: true,
  6765. // Model
  6766. _model: {
  6767. // Appearance
  6768. tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension),
  6769. backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
  6770. borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
  6771. borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
  6772. fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
  6773. borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
  6774. borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
  6775. borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
  6776. borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
  6777. }
  6778. });
  6779. meta.dataset.pivot();
  6780. // Update Points
  6781. helpers.each(points, function(point, index) {
  6782. me.updateElement(point, index, reset);
  6783. }, me);
  6784. // Update bezier control points
  6785. me.updateBezierControlPoints();
  6786. },
  6787. updateElement: function(point, index, reset) {
  6788. var me = this;
  6789. var custom = point.custom || {};
  6790. var dataset = me.getDataset();
  6791. var scale = me.chart.scale;
  6792. var pointElementOptions = me.chart.options.elements.point;
  6793. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  6794. // Compatibility: If the properties are defined with only the old name, use those values
  6795. if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
  6796. dataset.pointRadius = dataset.radius;
  6797. }
  6798. if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
  6799. dataset.pointHitRadius = dataset.hitRadius;
  6800. }
  6801. helpers.extend(point, {
  6802. // Utility
  6803. _datasetIndex: me.index,
  6804. _index: index,
  6805. _scale: scale,
  6806. // Desired view properties
  6807. _model: {
  6808. x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales
  6809. y: reset ? scale.yCenter : pointPosition.y,
  6810. // Appearance
  6811. tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension),
  6812. radius: custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius),
  6813. backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor),
  6814. borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor),
  6815. borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth),
  6816. pointStyle: custom.pointStyle ? custom.pointStyle : helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle),
  6817. rotation: custom.rotation ? custom.rotation : helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointElementOptions.rotation),
  6818. // Tooltip
  6819. hitRadius: custom.hitRadius ? custom.hitRadius : helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius)
  6820. }
  6821. });
  6822. point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y));
  6823. },
  6824. updateBezierControlPoints: function() {
  6825. var chartArea = this.chart.chartArea;
  6826. var meta = this.getMeta();
  6827. helpers.each(meta.data, function(point, index) {
  6828. var model = point._model;
  6829. var controlPoints = helpers.splineCurve(
  6830. helpers.previousItem(meta.data, index, true)._model,
  6831. model,
  6832. helpers.nextItem(meta.data, index, true)._model,
  6833. model.tension
  6834. );
  6835. // Prevent the bezier going outside of the bounds of the graph
  6836. model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, chartArea.right), chartArea.left);
  6837. model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, chartArea.bottom), chartArea.top);
  6838. model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, chartArea.right), chartArea.left);
  6839. model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, chartArea.bottom), chartArea.top);
  6840. // Now pivot the point for animation
  6841. point.pivot();
  6842. });
  6843. },
  6844. setHoverStyle: function(point) {
  6845. // Point
  6846. var dataset = this.chart.data.datasets[point._datasetIndex];
  6847. var custom = point.custom || {};
  6848. var index = point._index;
  6849. var model = point._model;
  6850. point.$previousStyle = {
  6851. backgroundColor: model.backgroundColor,
  6852. borderColor: model.borderColor,
  6853. borderWidth: model.borderWidth,
  6854. radius: model.radius
  6855. };
  6856. model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
  6857. model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
  6858. model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
  6859. model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
  6860. },
  6861. });
  6862. };
  6863. },{"26":26,"41":41,"46":46}],21:[function(require,module,exports){
  6864. 'use strict';
  6865. var defaults = require(26);
  6866. defaults._set('scatter', {
  6867. hover: {
  6868. mode: 'single'
  6869. },
  6870. scales: {
  6871. xAxes: [{
  6872. id: 'x-axis-1', // need an ID so datasets can reference the scale
  6873. type: 'linear', // scatter should not use a category axis
  6874. position: 'bottom'
  6875. }],
  6876. yAxes: [{
  6877. id: 'y-axis-1',
  6878. type: 'linear',
  6879. position: 'left'
  6880. }]
  6881. },
  6882. showLines: false,
  6883. tooltips: {
  6884. callbacks: {
  6885. title: function() {
  6886. return ''; // doesn't make sense for scatter since data are formatted as a point
  6887. },
  6888. label: function(item) {
  6889. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  6890. }
  6891. }
  6892. }
  6893. });
  6894. module.exports = function(Chart) {
  6895. // Scatter charts use line controllers
  6896. Chart.controllers.scatter = Chart.controllers.line;
  6897. };
  6898. },{"26":26}],22:[function(require,module,exports){
  6899. 'use strict';
  6900. var Element = require(27);
  6901. var exports = module.exports = Element.extend({
  6902. chart: null, // the animation associated chart instance
  6903. currentStep: 0, // the current animation step
  6904. numSteps: 60, // default number of steps
  6905. easing: '', // the easing to use for this animation
  6906. render: null, // render function used by the animation service
  6907. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  6908. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  6909. });
  6910. // DEPRECATIONS
  6911. /**
  6912. * Provided for backward compatibility, use Chart.Animation instead
  6913. * @prop Chart.Animation#animationObject
  6914. * @deprecated since version 2.6.0
  6915. * @todo remove at version 3
  6916. */
  6917. Object.defineProperty(exports.prototype, 'animationObject', {
  6918. get: function() {
  6919. return this;
  6920. }
  6921. });
  6922. /**
  6923. * Provided for backward compatibility, use Chart.Animation#chart instead
  6924. * @prop Chart.Animation#chartInstance
  6925. * @deprecated since version 2.6.0
  6926. * @todo remove at version 3
  6927. */
  6928. Object.defineProperty(exports.prototype, 'chartInstance', {
  6929. get: function() {
  6930. return this.chart;
  6931. },
  6932. set: function(value) {
  6933. this.chart = value;
  6934. }
  6935. });
  6936. },{"27":27}],23:[function(require,module,exports){
  6937. /* global window: false */
  6938. 'use strict';
  6939. var defaults = require(26);
  6940. var helpers = require(46);
  6941. defaults._set('global', {
  6942. animation: {
  6943. duration: 1000,
  6944. easing: 'easeOutQuart',
  6945. onProgress: helpers.noop,
  6946. onComplete: helpers.noop
  6947. }
  6948. });
  6949. module.exports = {
  6950. frameDuration: 17,
  6951. animations: [],
  6952. dropFrames: 0,
  6953. request: null,
  6954. /**
  6955. * @param {Chart} chart - The chart to animate.
  6956. * @param {Chart.Animation} animation - The animation that we will animate.
  6957. * @param {Number} duration - The animation duration in ms.
  6958. * @param {Boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  6959. */
  6960. addAnimation: function(chart, animation, duration, lazy) {
  6961. var animations = this.animations;
  6962. var i, ilen;
  6963. animation.chart = chart;
  6964. if (!lazy) {
  6965. chart.animating = true;
  6966. }
  6967. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  6968. if (animations[i].chart === chart) {
  6969. animations[i] = animation;
  6970. return;
  6971. }
  6972. }
  6973. animations.push(animation);
  6974. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  6975. if (animations.length === 1) {
  6976. this.requestAnimationFrame();
  6977. }
  6978. },
  6979. cancelAnimation: function(chart) {
  6980. var index = helpers.findIndex(this.animations, function(animation) {
  6981. return animation.chart === chart;
  6982. });
  6983. if (index !== -1) {
  6984. this.animations.splice(index, 1);
  6985. chart.animating = false;
  6986. }
  6987. },
  6988. requestAnimationFrame: function() {
  6989. var me = this;
  6990. if (me.request === null) {
  6991. // Skip animation frame requests until the active one is executed.
  6992. // This can happen when processing mouse events, e.g. 'mousemove'
  6993. // and 'mouseout' events will trigger multiple renders.
  6994. me.request = helpers.requestAnimFrame.call(window, function() {
  6995. me.request = null;
  6996. me.startDigest();
  6997. });
  6998. }
  6999. },
  7000. /**
  7001. * @private
  7002. */
  7003. startDigest: function() {
  7004. var me = this;
  7005. var startTime = Date.now();
  7006. var framesToDrop = 0;
  7007. if (me.dropFrames > 1) {
  7008. framesToDrop = Math.floor(me.dropFrames);
  7009. me.dropFrames = me.dropFrames % 1;
  7010. }
  7011. me.advance(1 + framesToDrop);
  7012. var endTime = Date.now();
  7013. me.dropFrames += (endTime - startTime) / me.frameDuration;
  7014. // Do we have more stuff to animate?
  7015. if (me.animations.length > 0) {
  7016. me.requestAnimationFrame();
  7017. }
  7018. },
  7019. /**
  7020. * @private
  7021. */
  7022. advance: function(count) {
  7023. var animations = this.animations;
  7024. var animation, chart;
  7025. var i = 0;
  7026. while (i < animations.length) {
  7027. animation = animations[i];
  7028. chart = animation.chart;
  7029. animation.currentStep = (animation.currentStep || 0) + count;
  7030. animation.currentStep = Math.min(animation.currentStep, animation.numSteps);
  7031. helpers.callback(animation.render, [chart, animation], chart);
  7032. helpers.callback(animation.onAnimationProgress, [animation], chart);
  7033. if (animation.currentStep >= animation.numSteps) {
  7034. helpers.callback(animation.onAnimationComplete, [animation], chart);
  7035. chart.animating = false;
  7036. animations.splice(i, 1);
  7037. } else {
  7038. ++i;
  7039. }
  7040. }
  7041. }
  7042. };
  7043. },{"26":26,"46":46}],24:[function(require,module,exports){
  7044. 'use strict';
  7045. var Animation = require(22);
  7046. var animations = require(23);
  7047. var defaults = require(26);
  7048. var helpers = require(46);
  7049. var Interaction = require(29);
  7050. var layouts = require(31);
  7051. var platform = require(49);
  7052. var plugins = require(32);
  7053. var scaleService = require(34);
  7054. var Tooltip = require(36);
  7055. module.exports = function(Chart) {
  7056. // Create a dictionary of chart types, to allow for extension of existing types
  7057. Chart.types = {};
  7058. // Store a reference to each instance - allowing us to globally resize chart instances on window resize.
  7059. // Destroy method on the chart will remove the instance of the chart from this reference.
  7060. Chart.instances = {};
  7061. // Controllers available for dataset visualization eg. bar, line, slice, etc.
  7062. Chart.controllers = {};
  7063. /**
  7064. * Initializes the given config with global and chart default values.
  7065. */
  7066. function initConfig(config) {
  7067. config = config || {};
  7068. // Do NOT use configMerge() for the data object because this method merges arrays
  7069. // and so would change references to labels and datasets, preventing data updates.
  7070. var data = config.data = config.data || {};
  7071. data.datasets = data.datasets || [];
  7072. data.labels = data.labels || [];
  7073. config.options = helpers.configMerge(
  7074. defaults.global,
  7075. defaults[config.type],
  7076. config.options || {});
  7077. return config;
  7078. }
  7079. /**
  7080. * Updates the config of the chart
  7081. * @param chart {Chart} chart to update the options for
  7082. */
  7083. function updateConfig(chart) {
  7084. var newOptions = chart.options;
  7085. helpers.each(chart.scales, function(scale) {
  7086. layouts.removeBox(chart, scale);
  7087. });
  7088. newOptions = helpers.configMerge(
  7089. Chart.defaults.global,
  7090. Chart.defaults[chart.config.type],
  7091. newOptions);
  7092. chart.options = chart.config.options = newOptions;
  7093. chart.ensureScalesHaveIDs();
  7094. chart.buildOrUpdateScales();
  7095. // Tooltip
  7096. chart.tooltip._options = newOptions.tooltips;
  7097. chart.tooltip.initialize();
  7098. }
  7099. function positionIsHorizontal(position) {
  7100. return position === 'top' || position === 'bottom';
  7101. }
  7102. helpers.extend(Chart.prototype, /** @lends Chart */ {
  7103. /**
  7104. * @private
  7105. */
  7106. construct: function(item, config) {
  7107. var me = this;
  7108. config = initConfig(config);
  7109. var context = platform.acquireContext(item, config);
  7110. var canvas = context && context.canvas;
  7111. var height = canvas && canvas.height;
  7112. var width = canvas && canvas.width;
  7113. me.id = helpers.uid();
  7114. me.ctx = context;
  7115. me.canvas = canvas;
  7116. me.config = config;
  7117. me.width = width;
  7118. me.height = height;
  7119. me.aspectRatio = height ? width / height : null;
  7120. me.options = config.options;
  7121. me._bufferedRender = false;
  7122. /**
  7123. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  7124. * the "instance" still need to be defined since it might be called from plugins.
  7125. * @prop Chart#chart
  7126. * @deprecated since version 2.6.0
  7127. * @todo remove at version 3
  7128. * @private
  7129. */
  7130. me.chart = me;
  7131. me.controller = me; // chart.chart.controller #inception
  7132. // Add the chart instance to the global namespace
  7133. Chart.instances[me.id] = me;
  7134. // Define alias to the config data: `chart.data === chart.config.data`
  7135. Object.defineProperty(me, 'data', {
  7136. get: function() {
  7137. return me.config.data;
  7138. },
  7139. set: function(value) {
  7140. me.config.data = value;
  7141. }
  7142. });
  7143. if (!context || !canvas) {
  7144. // The given item is not a compatible context2d element, let's return before finalizing
  7145. // the chart initialization but after setting basic chart / controller properties that
  7146. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  7147. // https://github.com/chartjs/Chart.js/issues/2807
  7148. console.error("Failed to create chart: can't acquire context from the given item");
  7149. return;
  7150. }
  7151. me.initialize();
  7152. me.update();
  7153. },
  7154. /**
  7155. * @private
  7156. */
  7157. initialize: function() {
  7158. var me = this;
  7159. // Before init plugin notification
  7160. plugins.notify(me, 'beforeInit');
  7161. helpers.retinaScale(me, me.options.devicePixelRatio);
  7162. me.bindEvents();
  7163. if (me.options.responsive) {
  7164. // Initial resize before chart draws (must be silent to preserve initial animations).
  7165. me.resize(true);
  7166. }
  7167. // Make sure scales have IDs and are built before we build any controllers.
  7168. me.ensureScalesHaveIDs();
  7169. me.buildOrUpdateScales();
  7170. me.initToolTip();
  7171. // After init plugin notification
  7172. plugins.notify(me, 'afterInit');
  7173. return me;
  7174. },
  7175. clear: function() {
  7176. helpers.canvas.clear(this);
  7177. return this;
  7178. },
  7179. stop: function() {
  7180. // Stops any current animation loop occurring
  7181. animations.cancelAnimation(this);
  7182. return this;
  7183. },
  7184. resize: function(silent) {
  7185. var me = this;
  7186. var options = me.options;
  7187. var canvas = me.canvas;
  7188. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  7189. // the canvas render width and height will be casted to integers so make sure that
  7190. // the canvas display style uses the same integer values to avoid blurring effect.
  7191. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  7192. var newWidth = Math.max(0, Math.floor(helpers.getMaximumWidth(canvas)));
  7193. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas)));
  7194. if (me.width === newWidth && me.height === newHeight) {
  7195. return;
  7196. }
  7197. canvas.width = me.width = newWidth;
  7198. canvas.height = me.height = newHeight;
  7199. canvas.style.width = newWidth + 'px';
  7200. canvas.style.height = newHeight + 'px';
  7201. helpers.retinaScale(me, options.devicePixelRatio);
  7202. if (!silent) {
  7203. // Notify any plugins about the resize
  7204. var newSize = {width: newWidth, height: newHeight};
  7205. plugins.notify(me, 'resize', [newSize]);
  7206. // Notify of resize
  7207. if (me.options.onResize) {
  7208. me.options.onResize(me, newSize);
  7209. }
  7210. me.stop();
  7211. me.update({
  7212. duration: me.options.responsiveAnimationDuration
  7213. });
  7214. }
  7215. },
  7216. ensureScalesHaveIDs: function() {
  7217. var options = this.options;
  7218. var scalesOptions = options.scales || {};
  7219. var scaleOptions = options.scale;
  7220. helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  7221. xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
  7222. });
  7223. helpers.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  7224. yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
  7225. });
  7226. if (scaleOptions) {
  7227. scaleOptions.id = scaleOptions.id || 'scale';
  7228. }
  7229. },
  7230. /**
  7231. * Builds a map of scale ID to scale object for future lookup.
  7232. */
  7233. buildOrUpdateScales: function() {
  7234. var me = this;
  7235. var options = me.options;
  7236. var scales = me.scales || {};
  7237. var items = [];
  7238. var updated = Object.keys(scales).reduce(function(obj, id) {
  7239. obj[id] = false;
  7240. return obj;
  7241. }, {});
  7242. if (options.scales) {
  7243. items = items.concat(
  7244. (options.scales.xAxes || []).map(function(xAxisOptions) {
  7245. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  7246. }),
  7247. (options.scales.yAxes || []).map(function(yAxisOptions) {
  7248. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  7249. })
  7250. );
  7251. }
  7252. if (options.scale) {
  7253. items.push({
  7254. options: options.scale,
  7255. dtype: 'radialLinear',
  7256. isDefault: true,
  7257. dposition: 'chartArea'
  7258. });
  7259. }
  7260. helpers.each(items, function(item) {
  7261. var scaleOptions = item.options;
  7262. var id = scaleOptions.id;
  7263. var scaleType = helpers.valueOrDefault(scaleOptions.type, item.dtype);
  7264. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  7265. scaleOptions.position = item.dposition;
  7266. }
  7267. updated[id] = true;
  7268. var scale = null;
  7269. if (id in scales && scales[id].type === scaleType) {
  7270. scale = scales[id];
  7271. scale.options = scaleOptions;
  7272. scale.ctx = me.ctx;
  7273. scale.chart = me;
  7274. } else {
  7275. var scaleClass = scaleService.getScaleConstructor(scaleType);
  7276. if (!scaleClass) {
  7277. return;
  7278. }
  7279. scale = new scaleClass({
  7280. id: id,
  7281. type: scaleType,
  7282. options: scaleOptions,
  7283. ctx: me.ctx,
  7284. chart: me
  7285. });
  7286. scales[scale.id] = scale;
  7287. }
  7288. scale.mergeTicksOptions();
  7289. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  7290. // and consider it as a regular scale part of the "scales"" map only! This would
  7291. // make the logic easier and remove some useless? custom code.
  7292. if (item.isDefault) {
  7293. me.scale = scale;
  7294. }
  7295. });
  7296. // clear up discarded scales
  7297. helpers.each(updated, function(hasUpdated, id) {
  7298. if (!hasUpdated) {
  7299. delete scales[id];
  7300. }
  7301. });
  7302. me.scales = scales;
  7303. scaleService.addScalesToLayout(this);
  7304. },
  7305. buildOrUpdateControllers: function() {
  7306. var me = this;
  7307. var types = [];
  7308. var newControllers = [];
  7309. helpers.each(me.data.datasets, function(dataset, datasetIndex) {
  7310. var meta = me.getDatasetMeta(datasetIndex);
  7311. var type = dataset.type || me.config.type;
  7312. if (meta.type && meta.type !== type) {
  7313. me.destroyDatasetMeta(datasetIndex);
  7314. meta = me.getDatasetMeta(datasetIndex);
  7315. }
  7316. meta.type = type;
  7317. types.push(meta.type);
  7318. if (meta.controller) {
  7319. meta.controller.updateIndex(datasetIndex);
  7320. meta.controller.linkScales();
  7321. } else {
  7322. var ControllerClass = Chart.controllers[meta.type];
  7323. if (ControllerClass === undefined) {
  7324. throw new Error('"' + meta.type + '" is not a chart type.');
  7325. }
  7326. meta.controller = new ControllerClass(me, datasetIndex);
  7327. newControllers.push(meta.controller);
  7328. }
  7329. }, me);
  7330. return newControllers;
  7331. },
  7332. /**
  7333. * Reset the elements of all datasets
  7334. * @private
  7335. */
  7336. resetElements: function() {
  7337. var me = this;
  7338. helpers.each(me.data.datasets, function(dataset, datasetIndex) {
  7339. me.getDatasetMeta(datasetIndex).controller.reset();
  7340. }, me);
  7341. },
  7342. /**
  7343. * Resets the chart back to it's state before the initial animation
  7344. */
  7345. reset: function() {
  7346. this.resetElements();
  7347. this.tooltip.initialize();
  7348. },
  7349. update: function(config) {
  7350. var me = this;
  7351. if (!config || typeof config !== 'object') {
  7352. // backwards compatibility
  7353. config = {
  7354. duration: config,
  7355. lazy: arguments[1]
  7356. };
  7357. }
  7358. updateConfig(me);
  7359. // plugins options references might have change, let's invalidate the cache
  7360. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  7361. plugins._invalidate(me);
  7362. if (plugins.notify(me, 'beforeUpdate') === false) {
  7363. return;
  7364. }
  7365. // In case the entire data object changed
  7366. me.tooltip._data = me.data;
  7367. // Make sure dataset controllers are updated and new controllers are reset
  7368. var newControllers = me.buildOrUpdateControllers();
  7369. // Make sure all dataset controllers have correct meta data counts
  7370. helpers.each(me.data.datasets, function(dataset, datasetIndex) {
  7371. me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
  7372. }, me);
  7373. me.updateLayout();
  7374. // Can only reset the new controllers after the scales have been updated
  7375. if (me.options.animation && me.options.animation.duration) {
  7376. helpers.each(newControllers, function(controller) {
  7377. controller.reset();
  7378. });
  7379. }
  7380. me.updateDatasets();
  7381. // Need to reset tooltip in case it is displayed with elements that are removed
  7382. // after update.
  7383. me.tooltip.initialize();
  7384. // Last active contains items that were previously in the tooltip.
  7385. // When we reset the tooltip, we need to clear it
  7386. me.lastActive = [];
  7387. // Do this before render so that any plugins that need final scale updates can use it
  7388. plugins.notify(me, 'afterUpdate');
  7389. if (me._bufferedRender) {
  7390. me._bufferedRequest = {
  7391. duration: config.duration,
  7392. easing: config.easing,
  7393. lazy: config.lazy
  7394. };
  7395. } else {
  7396. me.render(config);
  7397. }
  7398. },
  7399. /**
  7400. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  7401. * hook, in which case, plugins will not be called on `afterLayout`.
  7402. * @private
  7403. */
  7404. updateLayout: function() {
  7405. var me = this;
  7406. if (plugins.notify(me, 'beforeLayout') === false) {
  7407. return;
  7408. }
  7409. layouts.update(this, this.width, this.height);
  7410. /**
  7411. * Provided for backward compatibility, use `afterLayout` instead.
  7412. * @method IPlugin#afterScaleUpdate
  7413. * @deprecated since version 2.5.0
  7414. * @todo remove at version 3
  7415. * @private
  7416. */
  7417. plugins.notify(me, 'afterScaleUpdate');
  7418. plugins.notify(me, 'afterLayout');
  7419. },
  7420. /**
  7421. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  7422. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  7423. * @private
  7424. */
  7425. updateDatasets: function() {
  7426. var me = this;
  7427. if (plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  7428. return;
  7429. }
  7430. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  7431. me.updateDataset(i);
  7432. }
  7433. plugins.notify(me, 'afterDatasetsUpdate');
  7434. },
  7435. /**
  7436. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  7437. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  7438. * @private
  7439. */
  7440. updateDataset: function(index) {
  7441. var me = this;
  7442. var meta = me.getDatasetMeta(index);
  7443. var args = {
  7444. meta: meta,
  7445. index: index
  7446. };
  7447. if (plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  7448. return;
  7449. }
  7450. meta.controller.update();
  7451. plugins.notify(me, 'afterDatasetUpdate', [args]);
  7452. },
  7453. render: function(config) {
  7454. var me = this;
  7455. if (!config || typeof config !== 'object') {
  7456. // backwards compatibility
  7457. config = {
  7458. duration: config,
  7459. lazy: arguments[1]
  7460. };
  7461. }
  7462. var duration = config.duration;
  7463. var lazy = config.lazy;
  7464. if (plugins.notify(me, 'beforeRender') === false) {
  7465. return;
  7466. }
  7467. var animationOptions = me.options.animation;
  7468. var onComplete = function(animation) {
  7469. plugins.notify(me, 'afterRender');
  7470. helpers.callback(animationOptions && animationOptions.onComplete, [animation], me);
  7471. };
  7472. if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) {
  7473. var animation = new Animation({
  7474. numSteps: (duration || animationOptions.duration) / 16.66, // 60 fps
  7475. easing: config.easing || animationOptions.easing,
  7476. render: function(chart, animationObject) {
  7477. var easingFunction = helpers.easing.effects[animationObject.easing];
  7478. var currentStep = animationObject.currentStep;
  7479. var stepDecimal = currentStep / animationObject.numSteps;
  7480. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  7481. },
  7482. onAnimationProgress: animationOptions.onProgress,
  7483. onAnimationComplete: onComplete
  7484. });
  7485. animations.addAnimation(me, animation, duration, lazy);
  7486. } else {
  7487. me.draw();
  7488. // See https://github.com/chartjs/Chart.js/issues/3781
  7489. onComplete(new Animation({numSteps: 0, chart: me}));
  7490. }
  7491. return me;
  7492. },
  7493. draw: function(easingValue) {
  7494. var me = this;
  7495. me.clear();
  7496. if (helpers.isNullOrUndef(easingValue)) {
  7497. easingValue = 1;
  7498. }
  7499. me.transition(easingValue);
  7500. if (me.width <= 0 || me.height <= 0) {
  7501. return;
  7502. }
  7503. if (plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  7504. return;
  7505. }
  7506. // Draw all the scales
  7507. helpers.each(me.boxes, function(box) {
  7508. box.draw(me.chartArea);
  7509. }, me);
  7510. if (me.scale) {
  7511. me.scale.draw();
  7512. }
  7513. me.drawDatasets(easingValue);
  7514. me._drawTooltip(easingValue);
  7515. plugins.notify(me, 'afterDraw', [easingValue]);
  7516. },
  7517. /**
  7518. * @private
  7519. */
  7520. transition: function(easingValue) {
  7521. var me = this;
  7522. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  7523. if (me.isDatasetVisible(i)) {
  7524. me.getDatasetMeta(i).controller.transition(easingValue);
  7525. }
  7526. }
  7527. me.tooltip.transition(easingValue);
  7528. },
  7529. /**
  7530. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  7531. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  7532. * @private
  7533. */
  7534. drawDatasets: function(easingValue) {
  7535. var me = this;
  7536. if (plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  7537. return;
  7538. }
  7539. // Draw datasets reversed to support proper line stacking
  7540. for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {
  7541. if (me.isDatasetVisible(i)) {
  7542. me.drawDataset(i, easingValue);
  7543. }
  7544. }
  7545. plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  7546. },
  7547. /**
  7548. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  7549. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  7550. * @private
  7551. */
  7552. drawDataset: function(index, easingValue) {
  7553. var me = this;
  7554. var meta = me.getDatasetMeta(index);
  7555. var args = {
  7556. meta: meta,
  7557. index: index,
  7558. easingValue: easingValue
  7559. };
  7560. if (plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  7561. return;
  7562. }
  7563. meta.controller.draw(easingValue);
  7564. plugins.notify(me, 'afterDatasetDraw', [args]);
  7565. },
  7566. /**
  7567. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  7568. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  7569. * @private
  7570. */
  7571. _drawTooltip: function(easingValue) {
  7572. var me = this;
  7573. var tooltip = me.tooltip;
  7574. var args = {
  7575. tooltip: tooltip,
  7576. easingValue: easingValue
  7577. };
  7578. if (plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  7579. return;
  7580. }
  7581. tooltip.draw();
  7582. plugins.notify(me, 'afterTooltipDraw', [args]);
  7583. },
  7584. // Get the single element that was clicked on
  7585. // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  7586. getElementAtEvent: function(e) {
  7587. return Interaction.modes.single(this, e);
  7588. },
  7589. getElementsAtEvent: function(e) {
  7590. return Interaction.modes.label(this, e, {intersect: true});
  7591. },
  7592. getElementsAtXAxis: function(e) {
  7593. return Interaction.modes['x-axis'](this, e, {intersect: true});
  7594. },
  7595. getElementsAtEventForMode: function(e, mode, options) {
  7596. var method = Interaction.modes[mode];
  7597. if (typeof method === 'function') {
  7598. return method(this, e, options);
  7599. }
  7600. return [];
  7601. },
  7602. getDatasetAtEvent: function(e) {
  7603. return Interaction.modes.dataset(this, e, {intersect: true});
  7604. },
  7605. getDatasetMeta: function(datasetIndex) {
  7606. var me = this;
  7607. var dataset = me.data.datasets[datasetIndex];
  7608. if (!dataset._meta) {
  7609. dataset._meta = {};
  7610. }
  7611. var meta = dataset._meta[me.id];
  7612. if (!meta) {
  7613. meta = dataset._meta[me.id] = {
  7614. type: null,
  7615. data: [],
  7616. dataset: null,
  7617. controller: null,
  7618. hidden: null, // See isDatasetVisible() comment
  7619. xAxisID: null,
  7620. yAxisID: null
  7621. };
  7622. }
  7623. return meta;
  7624. },
  7625. getVisibleDatasetCount: function() {
  7626. var count = 0;
  7627. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  7628. if (this.isDatasetVisible(i)) {
  7629. count++;
  7630. }
  7631. }
  7632. return count;
  7633. },
  7634. isDatasetVisible: function(datasetIndex) {
  7635. var meta = this.getDatasetMeta(datasetIndex);
  7636. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  7637. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  7638. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  7639. },
  7640. generateLegend: function() {
  7641. return this.options.legendCallback(this);
  7642. },
  7643. /**
  7644. * @private
  7645. */
  7646. destroyDatasetMeta: function(datasetIndex) {
  7647. var id = this.id;
  7648. var dataset = this.data.datasets[datasetIndex];
  7649. var meta = dataset._meta && dataset._meta[id];
  7650. if (meta) {
  7651. meta.controller.destroy();
  7652. delete dataset._meta[id];
  7653. }
  7654. },
  7655. destroy: function() {
  7656. var me = this;
  7657. var canvas = me.canvas;
  7658. var i, ilen;
  7659. me.stop();
  7660. // dataset controllers need to cleanup associated data
  7661. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  7662. me.destroyDatasetMeta(i);
  7663. }
  7664. if (canvas) {
  7665. me.unbindEvents();
  7666. helpers.canvas.clear(me);
  7667. platform.releaseContext(me.ctx);
  7668. me.canvas = null;
  7669. me.ctx = null;
  7670. }
  7671. plugins.notify(me, 'destroy');
  7672. delete Chart.instances[me.id];
  7673. },
  7674. toBase64Image: function() {
  7675. return this.canvas.toDataURL.apply(this.canvas, arguments);
  7676. },
  7677. initToolTip: function() {
  7678. var me = this;
  7679. me.tooltip = new Tooltip({
  7680. _chart: me,
  7681. _chartInstance: me, // deprecated, backward compatibility
  7682. _data: me.data,
  7683. _options: me.options.tooltips
  7684. }, me);
  7685. },
  7686. /**
  7687. * @private
  7688. */
  7689. bindEvents: function() {
  7690. var me = this;
  7691. var listeners = me._listeners = {};
  7692. var listener = function() {
  7693. me.eventHandler.apply(me, arguments);
  7694. };
  7695. helpers.each(me.options.events, function(type) {
  7696. platform.addEventListener(me, type, listener);
  7697. listeners[type] = listener;
  7698. });
  7699. // Elements used to detect size change should not be injected for non responsive charts.
  7700. // See https://github.com/chartjs/Chart.js/issues/2210
  7701. if (me.options.responsive) {
  7702. listener = function() {
  7703. me.resize();
  7704. };
  7705. platform.addEventListener(me, 'resize', listener);
  7706. listeners.resize = listener;
  7707. }
  7708. },
  7709. /**
  7710. * @private
  7711. */
  7712. unbindEvents: function() {
  7713. var me = this;
  7714. var listeners = me._listeners;
  7715. if (!listeners) {
  7716. return;
  7717. }
  7718. delete me._listeners;
  7719. helpers.each(listeners, function(listener, type) {
  7720. platform.removeEventListener(me, type, listener);
  7721. });
  7722. },
  7723. updateHoverStyle: function(elements, mode, enabled) {
  7724. var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';
  7725. var element, i, ilen;
  7726. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  7727. element = elements[i];
  7728. if (element) {
  7729. this.getDatasetMeta(element._datasetIndex).controller[method](element);
  7730. }
  7731. }
  7732. },
  7733. /**
  7734. * @private
  7735. */
  7736. eventHandler: function(e) {
  7737. var me = this;
  7738. var tooltip = me.tooltip;
  7739. if (plugins.notify(me, 'beforeEvent', [e]) === false) {
  7740. return;
  7741. }
  7742. // Buffer any update calls so that renders do not occur
  7743. me._bufferedRender = true;
  7744. me._bufferedRequest = null;
  7745. var changed = me.handleEvent(e);
  7746. // for smooth tooltip animations issue #4989
  7747. // the tooltip should be the source of change
  7748. // Animation check workaround:
  7749. // tooltip._start will be null when tooltip isn't animating
  7750. if (tooltip) {
  7751. changed = tooltip._start
  7752. ? tooltip.handleEvent(e)
  7753. : changed | tooltip.handleEvent(e);
  7754. }
  7755. plugins.notify(me, 'afterEvent', [e]);
  7756. var bufferedRequest = me._bufferedRequest;
  7757. if (bufferedRequest) {
  7758. // If we have an update that was triggered, we need to do a normal render
  7759. me.render(bufferedRequest);
  7760. } else if (changed && !me.animating) {
  7761. // If entering, leaving, or changing elements, animate the change via pivot
  7762. me.stop();
  7763. // We only need to render at this point. Updating will cause scales to be
  7764. // recomputed generating flicker & using more memory than necessary.
  7765. me.render({
  7766. duration: me.options.hover.animationDuration,
  7767. lazy: true
  7768. });
  7769. }
  7770. me._bufferedRender = false;
  7771. me._bufferedRequest = null;
  7772. return me;
  7773. },
  7774. /**
  7775. * Handle an event
  7776. * @private
  7777. * @param {IEvent} event the event to handle
  7778. * @return {Boolean} true if the chart needs to re-render
  7779. */
  7780. handleEvent: function(e) {
  7781. var me = this;
  7782. var options = me.options || {};
  7783. var hoverOptions = options.hover;
  7784. var changed = false;
  7785. me.lastActive = me.lastActive || [];
  7786. // Find Active Elements for hover and tooltips
  7787. if (e.type === 'mouseout') {
  7788. me.active = [];
  7789. } else {
  7790. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  7791. }
  7792. // Invoke onHover hook
  7793. // Need to call with native event here to not break backwards compatibility
  7794. helpers.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  7795. if (e.type === 'mouseup' || e.type === 'click') {
  7796. if (options.onClick) {
  7797. // Use e.native here for backwards compatibility
  7798. options.onClick.call(me, e.native, me.active);
  7799. }
  7800. }
  7801. // Remove styling for last active (even if it may still be active)
  7802. if (me.lastActive.length) {
  7803. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  7804. }
  7805. // Built in hover styling
  7806. if (me.active.length && hoverOptions.mode) {
  7807. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  7808. }
  7809. changed = !helpers.arrayEquals(me.active, me.lastActive);
  7810. // Remember Last Actives
  7811. me.lastActive = me.active;
  7812. return changed;
  7813. }
  7814. });
  7815. /**
  7816. * Provided for backward compatibility, use Chart instead.
  7817. * @class Chart.Controller
  7818. * @deprecated since version 2.6.0
  7819. * @todo remove at version 3
  7820. * @private
  7821. */
  7822. Chart.Controller = Chart;
  7823. };
  7824. },{"22":22,"23":23,"26":26,"29":29,"31":31,"32":32,"34":34,"36":36,"46":46,"49":49}],25:[function(require,module,exports){
  7825. 'use strict';
  7826. var helpers = require(46);
  7827. module.exports = function(Chart) {
  7828. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  7829. /**
  7830. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  7831. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  7832. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  7833. */
  7834. function listenArrayEvents(array, listener) {
  7835. if (array._chartjs) {
  7836. array._chartjs.listeners.push(listener);
  7837. return;
  7838. }
  7839. Object.defineProperty(array, '_chartjs', {
  7840. configurable: true,
  7841. enumerable: false,
  7842. value: {
  7843. listeners: [listener]
  7844. }
  7845. });
  7846. arrayEvents.forEach(function(key) {
  7847. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  7848. var base = array[key];
  7849. Object.defineProperty(array, key, {
  7850. configurable: true,
  7851. enumerable: false,
  7852. value: function() {
  7853. var args = Array.prototype.slice.call(arguments);
  7854. var res = base.apply(this, args);
  7855. helpers.each(array._chartjs.listeners, function(object) {
  7856. if (typeof object[method] === 'function') {
  7857. object[method].apply(object, args);
  7858. }
  7859. });
  7860. return res;
  7861. }
  7862. });
  7863. });
  7864. }
  7865. /**
  7866. * Removes the given array event listener and cleanup extra attached properties (such as
  7867. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  7868. */
  7869. function unlistenArrayEvents(array, listener) {
  7870. var stub = array._chartjs;
  7871. if (!stub) {
  7872. return;
  7873. }
  7874. var listeners = stub.listeners;
  7875. var index = listeners.indexOf(listener);
  7876. if (index !== -1) {
  7877. listeners.splice(index, 1);
  7878. }
  7879. if (listeners.length > 0) {
  7880. return;
  7881. }
  7882. arrayEvents.forEach(function(key) {
  7883. delete array[key];
  7884. });
  7885. delete array._chartjs;
  7886. }
  7887. // Base class for all dataset controllers (line, bar, etc)
  7888. Chart.DatasetController = function(chart, datasetIndex) {
  7889. this.initialize(chart, datasetIndex);
  7890. };
  7891. helpers.extend(Chart.DatasetController.prototype, {
  7892. /**
  7893. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  7894. * @type {Chart.core.element}
  7895. */
  7896. datasetElementType: null,
  7897. /**
  7898. * Element type used to generate a meta data (e.g. Chart.element.Point).
  7899. * @type {Chart.core.element}
  7900. */
  7901. dataElementType: null,
  7902. initialize: function(chart, datasetIndex) {
  7903. var me = this;
  7904. me.chart = chart;
  7905. me.index = datasetIndex;
  7906. me.linkScales();
  7907. me.addElements();
  7908. },
  7909. updateIndex: function(datasetIndex) {
  7910. this.index = datasetIndex;
  7911. },
  7912. linkScales: function() {
  7913. var me = this;
  7914. var meta = me.getMeta();
  7915. var dataset = me.getDataset();
  7916. if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) {
  7917. meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
  7918. }
  7919. if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) {
  7920. meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
  7921. }
  7922. },
  7923. getDataset: function() {
  7924. return this.chart.data.datasets[this.index];
  7925. },
  7926. getMeta: function() {
  7927. return this.chart.getDatasetMeta(this.index);
  7928. },
  7929. getScaleForId: function(scaleID) {
  7930. return this.chart.scales[scaleID];
  7931. },
  7932. reset: function() {
  7933. this.update(true);
  7934. },
  7935. /**
  7936. * @private
  7937. */
  7938. destroy: function() {
  7939. if (this._data) {
  7940. unlistenArrayEvents(this._data, this);
  7941. }
  7942. },
  7943. createMetaDataset: function() {
  7944. var me = this;
  7945. var type = me.datasetElementType;
  7946. return type && new type({
  7947. _chart: me.chart,
  7948. _datasetIndex: me.index
  7949. });
  7950. },
  7951. createMetaData: function(index) {
  7952. var me = this;
  7953. var type = me.dataElementType;
  7954. return type && new type({
  7955. _chart: me.chart,
  7956. _datasetIndex: me.index,
  7957. _index: index
  7958. });
  7959. },
  7960. addElements: function() {
  7961. var me = this;
  7962. var meta = me.getMeta();
  7963. var data = me.getDataset().data || [];
  7964. var metaData = meta.data;
  7965. var i, ilen;
  7966. for (i = 0, ilen = data.length; i < ilen; ++i) {
  7967. metaData[i] = metaData[i] || me.createMetaData(i);
  7968. }
  7969. meta.dataset = meta.dataset || me.createMetaDataset();
  7970. },
  7971. addElementAndReset: function(index) {
  7972. var element = this.createMetaData(index);
  7973. this.getMeta().data.splice(index, 0, element);
  7974. this.updateElement(element, index, true);
  7975. },
  7976. buildOrUpdateElements: function() {
  7977. var me = this;
  7978. var dataset = me.getDataset();
  7979. var data = dataset.data || (dataset.data = []);
  7980. // In order to correctly handle data addition/deletion animation (an thus simulate
  7981. // real-time charts), we need to monitor these data modifications and synchronize
  7982. // the internal meta data accordingly.
  7983. if (me._data !== data) {
  7984. if (me._data) {
  7985. // This case happens when the user replaced the data array instance.
  7986. unlistenArrayEvents(me._data, me);
  7987. }
  7988. listenArrayEvents(data, me);
  7989. me._data = data;
  7990. }
  7991. // Re-sync meta data in case the user replaced the data array or if we missed
  7992. // any updates and so make sure that we handle number of datapoints changing.
  7993. me.resyncElements();
  7994. },
  7995. update: helpers.noop,
  7996. transition: function(easingValue) {
  7997. var meta = this.getMeta();
  7998. var elements = meta.data || [];
  7999. var ilen = elements.length;
  8000. var i = 0;
  8001. for (; i < ilen; ++i) {
  8002. elements[i].transition(easingValue);
  8003. }
  8004. if (meta.dataset) {
  8005. meta.dataset.transition(easingValue);
  8006. }
  8007. },
  8008. draw: function() {
  8009. var meta = this.getMeta();
  8010. var elements = meta.data || [];
  8011. var ilen = elements.length;
  8012. var i = 0;
  8013. if (meta.dataset) {
  8014. meta.dataset.draw();
  8015. }
  8016. for (; i < ilen; ++i) {
  8017. elements[i].draw();
  8018. }
  8019. },
  8020. removeHoverStyle: function(element) {
  8021. helpers.merge(element._model, element.$previousStyle || {});
  8022. delete element.$previousStyle;
  8023. },
  8024. setHoverStyle: function(element) {
  8025. var dataset = this.chart.data.datasets[element._datasetIndex];
  8026. var index = element._index;
  8027. var custom = element.custom || {};
  8028. var valueOrDefault = helpers.valueAtIndexOrDefault;
  8029. var getHoverColor = helpers.getHoverColor;
  8030. var model = element._model;
  8031. element.$previousStyle = {
  8032. backgroundColor: model.backgroundColor,
  8033. borderColor: model.borderColor,
  8034. borderWidth: model.borderWidth
  8035. };
  8036. model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor));
  8037. model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor));
  8038. model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
  8039. },
  8040. /**
  8041. * @private
  8042. */
  8043. resyncElements: function() {
  8044. var me = this;
  8045. var meta = me.getMeta();
  8046. var data = me.getDataset().data;
  8047. var numMeta = meta.data.length;
  8048. var numData = data.length;
  8049. if (numData < numMeta) {
  8050. meta.data.splice(numData, numMeta - numData);
  8051. } else if (numData > numMeta) {
  8052. me.insertElements(numMeta, numData - numMeta);
  8053. }
  8054. },
  8055. /**
  8056. * @private
  8057. */
  8058. insertElements: function(start, count) {
  8059. for (var i = 0; i < count; ++i) {
  8060. this.addElementAndReset(start + i);
  8061. }
  8062. },
  8063. /**
  8064. * @private
  8065. */
  8066. onDataPush: function() {
  8067. this.insertElements(this.getDataset().data.length - 1, arguments.length);
  8068. },
  8069. /**
  8070. * @private
  8071. */
  8072. onDataPop: function() {
  8073. this.getMeta().data.pop();
  8074. },
  8075. /**
  8076. * @private
  8077. */
  8078. onDataShift: function() {
  8079. this.getMeta().data.shift();
  8080. },
  8081. /**
  8082. * @private
  8083. */
  8084. onDataSplice: function(start, count) {
  8085. this.getMeta().data.splice(start, count);
  8086. this.insertElements(start, arguments.length - 2);
  8087. },
  8088. /**
  8089. * @private
  8090. */
  8091. onDataUnshift: function() {
  8092. this.insertElements(0, arguments.length);
  8093. }
  8094. });
  8095. Chart.DatasetController.extend = helpers.inherits;
  8096. };
  8097. },{"46":46}],26:[function(require,module,exports){
  8098. 'use strict';
  8099. var helpers = require(46);
  8100. module.exports = {
  8101. /**
  8102. * @private
  8103. */
  8104. _set: function(scope, values) {
  8105. return helpers.merge(this[scope] || (this[scope] = {}), values);
  8106. }
  8107. };
  8108. },{"46":46}],27:[function(require,module,exports){
  8109. 'use strict';
  8110. var color = require(2);
  8111. var helpers = require(46);
  8112. function interpolate(start, view, model, ease) {
  8113. var keys = Object.keys(model);
  8114. var i, ilen, key, actual, origin, target, type, c0, c1;
  8115. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  8116. key = keys[i];
  8117. target = model[key];
  8118. // if a value is added to the model after pivot() has been called, the view
  8119. // doesn't contain it, so let's initialize the view to the target value.
  8120. if (!view.hasOwnProperty(key)) {
  8121. view[key] = target;
  8122. }
  8123. actual = view[key];
  8124. if (actual === target || key[0] === '_') {
  8125. continue;
  8126. }
  8127. if (!start.hasOwnProperty(key)) {
  8128. start[key] = actual;
  8129. }
  8130. origin = start[key];
  8131. type = typeof target;
  8132. if (type === typeof origin) {
  8133. if (type === 'string') {
  8134. c0 = color(origin);
  8135. if (c0.valid) {
  8136. c1 = color(target);
  8137. if (c1.valid) {
  8138. view[key] = c1.mix(c0, ease).rgbString();
  8139. continue;
  8140. }
  8141. }
  8142. } else if (type === 'number' && isFinite(origin) && isFinite(target)) {
  8143. view[key] = origin + (target - origin) * ease;
  8144. continue;
  8145. }
  8146. }
  8147. view[key] = target;
  8148. }
  8149. }
  8150. var Element = function(configuration) {
  8151. helpers.extend(this, configuration);
  8152. this.initialize.apply(this, arguments);
  8153. };
  8154. helpers.extend(Element.prototype, {
  8155. initialize: function() {
  8156. this.hidden = false;
  8157. },
  8158. pivot: function() {
  8159. var me = this;
  8160. if (!me._view) {
  8161. me._view = helpers.clone(me._model);
  8162. }
  8163. me._start = {};
  8164. return me;
  8165. },
  8166. transition: function(ease) {
  8167. var me = this;
  8168. var model = me._model;
  8169. var start = me._start;
  8170. var view = me._view;
  8171. // No animation -> No Transition
  8172. if (!model || ease === 1) {
  8173. me._view = model;
  8174. me._start = null;
  8175. return me;
  8176. }
  8177. if (!view) {
  8178. view = me._view = {};
  8179. }
  8180. if (!start) {
  8181. start = me._start = {};
  8182. }
  8183. interpolate(start, view, model, ease);
  8184. return me;
  8185. },
  8186. tooltipPosition: function() {
  8187. return {
  8188. x: this._model.x,
  8189. y: this._model.y
  8190. };
  8191. },
  8192. hasValue: function() {
  8193. return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y);
  8194. }
  8195. });
  8196. Element.extend = helpers.inherits;
  8197. module.exports = Element;
  8198. },{"2":2,"46":46}],28:[function(require,module,exports){
  8199. /* global window: false */
  8200. /* global document: false */
  8201. 'use strict';
  8202. var color = require(2);
  8203. var defaults = require(26);
  8204. var helpers = require(46);
  8205. var scaleService = require(34);
  8206. module.exports = function() {
  8207. // -- Basic js utility methods
  8208. helpers.configMerge = function(/* objects ... */) {
  8209. return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
  8210. merger: function(key, target, source, options) {
  8211. var tval = target[key] || {};
  8212. var sval = source[key];
  8213. if (key === 'scales') {
  8214. // scale config merging is complex. Add our own function here for that
  8215. target[key] = helpers.scaleMerge(tval, sval);
  8216. } else if (key === 'scale') {
  8217. // used in polar area & radar charts since there is only one scale
  8218. target[key] = helpers.merge(tval, [scaleService.getScaleDefaults(sval.type), sval]);
  8219. } else {
  8220. helpers._merger(key, target, source, options);
  8221. }
  8222. }
  8223. });
  8224. };
  8225. helpers.scaleMerge = function(/* objects ... */) {
  8226. return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
  8227. merger: function(key, target, source, options) {
  8228. if (key === 'xAxes' || key === 'yAxes') {
  8229. var slen = source[key].length;
  8230. var i, type, scale;
  8231. if (!target[key]) {
  8232. target[key] = [];
  8233. }
  8234. for (i = 0; i < slen; ++i) {
  8235. scale = source[key][i];
  8236. type = helpers.valueOrDefault(scale.type, key === 'xAxes' ? 'category' : 'linear');
  8237. if (i >= target[key].length) {
  8238. target[key].push({});
  8239. }
  8240. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  8241. // new/untyped scale or type changed: let's apply the new defaults
  8242. // then merge source scale to correctly overwrite the defaults.
  8243. helpers.merge(target[key][i], [scaleService.getScaleDefaults(type), scale]);
  8244. } else {
  8245. // scales type are the same
  8246. helpers.merge(target[key][i], scale);
  8247. }
  8248. }
  8249. } else {
  8250. helpers._merger(key, target, source, options);
  8251. }
  8252. }
  8253. });
  8254. };
  8255. helpers.where = function(collection, filterCallback) {
  8256. if (helpers.isArray(collection) && Array.prototype.filter) {
  8257. return collection.filter(filterCallback);
  8258. }
  8259. var filtered = [];
  8260. helpers.each(collection, function(item) {
  8261. if (filterCallback(item)) {
  8262. filtered.push(item);
  8263. }
  8264. });
  8265. return filtered;
  8266. };
  8267. helpers.findIndex = Array.prototype.findIndex ?
  8268. function(array, callback, scope) {
  8269. return array.findIndex(callback, scope);
  8270. } :
  8271. function(array, callback, scope) {
  8272. scope = scope === undefined ? array : scope;
  8273. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  8274. if (callback.call(scope, array[i], i, array)) {
  8275. return i;
  8276. }
  8277. }
  8278. return -1;
  8279. };
  8280. helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  8281. // Default to start of the array
  8282. if (helpers.isNullOrUndef(startIndex)) {
  8283. startIndex = -1;
  8284. }
  8285. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8286. var currentItem = arrayToSearch[i];
  8287. if (filterCallback(currentItem)) {
  8288. return currentItem;
  8289. }
  8290. }
  8291. };
  8292. helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8293. // Default to end of the array
  8294. if (helpers.isNullOrUndef(startIndex)) {
  8295. startIndex = arrayToSearch.length;
  8296. }
  8297. for (var i = startIndex - 1; i >= 0; i--) {
  8298. var currentItem = arrayToSearch[i];
  8299. if (filterCallback(currentItem)) {
  8300. return currentItem;
  8301. }
  8302. }
  8303. };
  8304. // -- Math methods
  8305. helpers.isNumber = function(n) {
  8306. return !isNaN(parseFloat(n)) && isFinite(n);
  8307. };
  8308. helpers.almostEquals = function(x, y, epsilon) {
  8309. return Math.abs(x - y) < epsilon;
  8310. };
  8311. helpers.almostWhole = function(x, epsilon) {
  8312. var rounded = Math.round(x);
  8313. return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
  8314. };
  8315. helpers.max = function(array) {
  8316. return array.reduce(function(max, value) {
  8317. if (!isNaN(value)) {
  8318. return Math.max(max, value);
  8319. }
  8320. return max;
  8321. }, Number.NEGATIVE_INFINITY);
  8322. };
  8323. helpers.min = function(array) {
  8324. return array.reduce(function(min, value) {
  8325. if (!isNaN(value)) {
  8326. return Math.min(min, value);
  8327. }
  8328. return min;
  8329. }, Number.POSITIVE_INFINITY);
  8330. };
  8331. helpers.sign = Math.sign ?
  8332. function(x) {
  8333. return Math.sign(x);
  8334. } :
  8335. function(x) {
  8336. x = +x; // convert to a number
  8337. if (x === 0 || isNaN(x)) {
  8338. return x;
  8339. }
  8340. return x > 0 ? 1 : -1;
  8341. };
  8342. helpers.log10 = Math.log10 ?
  8343. function(x) {
  8344. return Math.log10(x);
  8345. } :
  8346. function(x) {
  8347. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  8348. // Check for whole powers of 10,
  8349. // which due to floating point rounding error should be corrected.
  8350. var powerOf10 = Math.round(exponent);
  8351. var isPowerOf10 = x === Math.pow(10, powerOf10);
  8352. return isPowerOf10 ? powerOf10 : exponent;
  8353. };
  8354. helpers.toRadians = function(degrees) {
  8355. return degrees * (Math.PI / 180);
  8356. };
  8357. helpers.toDegrees = function(radians) {
  8358. return radians * (180 / Math.PI);
  8359. };
  8360. // Gets the angle from vertical upright to the point about a centre.
  8361. helpers.getAngleFromPoint = function(centrePoint, anglePoint) {
  8362. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8363. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8364. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8365. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8366. if (angle < (-0.5 * Math.PI)) {
  8367. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8368. }
  8369. return {
  8370. angle: angle,
  8371. distance: radialDistanceFromCenter
  8372. };
  8373. };
  8374. helpers.distanceBetweenPoints = function(pt1, pt2) {
  8375. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8376. };
  8377. helpers.aliasPixel = function(pixelWidth) {
  8378. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8379. };
  8380. helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8381. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8382. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8383. // This function must also respect "skipped" points
  8384. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8385. var current = middlePoint;
  8386. var next = afterPoint.skip ? middlePoint : afterPoint;
  8387. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8388. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8389. var s01 = d01 / (d01 + d12);
  8390. var s12 = d12 / (d01 + d12);
  8391. // If all points are the same, s01 & s02 will be inf
  8392. s01 = isNaN(s01) ? 0 : s01;
  8393. s12 = isNaN(s12) ? 0 : s12;
  8394. var fa = t * s01; // scaling factor for triangle Ta
  8395. var fb = t * s12;
  8396. return {
  8397. previous: {
  8398. x: current.x - fa * (next.x - previous.x),
  8399. y: current.y - fa * (next.y - previous.y)
  8400. },
  8401. next: {
  8402. x: current.x + fb * (next.x - previous.x),
  8403. y: current.y + fb * (next.y - previous.y)
  8404. }
  8405. };
  8406. };
  8407. helpers.EPSILON = Number.EPSILON || 1e-14;
  8408. helpers.splineCurveMonotone = function(points) {
  8409. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8410. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8411. // between the dataset discrete points due to the interpolation.
  8412. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8413. var pointsWithTangents = (points || []).map(function(point) {
  8414. return {
  8415. model: point._model,
  8416. deltaK: 0,
  8417. mK: 0
  8418. };
  8419. });
  8420. // Calculate slopes (deltaK) and initialize tangents (mK)
  8421. var pointsLen = pointsWithTangents.length;
  8422. var i, pointBefore, pointCurrent, pointAfter;
  8423. for (i = 0; i < pointsLen; ++i) {
  8424. pointCurrent = pointsWithTangents[i];
  8425. if (pointCurrent.model.skip) {
  8426. continue;
  8427. }
  8428. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8429. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8430. if (pointAfter && !pointAfter.model.skip) {
  8431. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8432. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  8433. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  8434. }
  8435. if (!pointBefore || pointBefore.model.skip) {
  8436. pointCurrent.mK = pointCurrent.deltaK;
  8437. } else if (!pointAfter || pointAfter.model.skip) {
  8438. pointCurrent.mK = pointBefore.deltaK;
  8439. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  8440. pointCurrent.mK = 0;
  8441. } else {
  8442. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  8443. }
  8444. }
  8445. // Adjust tangents to ensure monotonic properties
  8446. var alphaK, betaK, tauK, squaredMagnitude;
  8447. for (i = 0; i < pointsLen - 1; ++i) {
  8448. pointCurrent = pointsWithTangents[i];
  8449. pointAfter = pointsWithTangents[i + 1];
  8450. if (pointCurrent.model.skip || pointAfter.model.skip) {
  8451. continue;
  8452. }
  8453. if (helpers.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  8454. pointCurrent.mK = pointAfter.mK = 0;
  8455. continue;
  8456. }
  8457. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  8458. betaK = pointAfter.mK / pointCurrent.deltaK;
  8459. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  8460. if (squaredMagnitude <= 9) {
  8461. continue;
  8462. }
  8463. tauK = 3 / Math.sqrt(squaredMagnitude);
  8464. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  8465. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  8466. }
  8467. // Compute control points
  8468. var deltaX;
  8469. for (i = 0; i < pointsLen; ++i) {
  8470. pointCurrent = pointsWithTangents[i];
  8471. if (pointCurrent.model.skip) {
  8472. continue;
  8473. }
  8474. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8475. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8476. if (pointBefore && !pointBefore.model.skip) {
  8477. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  8478. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  8479. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  8480. }
  8481. if (pointAfter && !pointAfter.model.skip) {
  8482. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  8483. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  8484. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  8485. }
  8486. }
  8487. };
  8488. helpers.nextItem = function(collection, index, loop) {
  8489. if (loop) {
  8490. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  8491. }
  8492. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  8493. };
  8494. helpers.previousItem = function(collection, index, loop) {
  8495. if (loop) {
  8496. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  8497. }
  8498. return index <= 0 ? collection[0] : collection[index - 1];
  8499. };
  8500. // Implementation of the nice number algorithm used in determining where axis labels will go
  8501. helpers.niceNum = function(range, round) {
  8502. var exponent = Math.floor(helpers.log10(range));
  8503. var fraction = range / Math.pow(10, exponent);
  8504. var niceFraction;
  8505. if (round) {
  8506. if (fraction < 1.5) {
  8507. niceFraction = 1;
  8508. } else if (fraction < 3) {
  8509. niceFraction = 2;
  8510. } else if (fraction < 7) {
  8511. niceFraction = 5;
  8512. } else {
  8513. niceFraction = 10;
  8514. }
  8515. } else if (fraction <= 1.0) {
  8516. niceFraction = 1;
  8517. } else if (fraction <= 2) {
  8518. niceFraction = 2;
  8519. } else if (fraction <= 5) {
  8520. niceFraction = 5;
  8521. } else {
  8522. niceFraction = 10;
  8523. }
  8524. return niceFraction * Math.pow(10, exponent);
  8525. };
  8526. // Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  8527. helpers.requestAnimFrame = (function() {
  8528. if (typeof window === 'undefined') {
  8529. return function(callback) {
  8530. callback();
  8531. };
  8532. }
  8533. return window.requestAnimationFrame ||
  8534. window.webkitRequestAnimationFrame ||
  8535. window.mozRequestAnimationFrame ||
  8536. window.oRequestAnimationFrame ||
  8537. window.msRequestAnimationFrame ||
  8538. function(callback) {
  8539. return window.setTimeout(callback, 1000 / 60);
  8540. };
  8541. }());
  8542. // -- DOM methods
  8543. helpers.getRelativePosition = function(evt, chart) {
  8544. var mouseX, mouseY;
  8545. var e = evt.originalEvent || evt;
  8546. var canvas = evt.target || evt.srcElement;
  8547. var boundingRect = canvas.getBoundingClientRect();
  8548. var touches = e.touches;
  8549. if (touches && touches.length > 0) {
  8550. mouseX = touches[0].clientX;
  8551. mouseY = touches[0].clientY;
  8552. } else {
  8553. mouseX = e.clientX;
  8554. mouseY = e.clientY;
  8555. }
  8556. // Scale mouse coordinates into canvas coordinates
  8557. // by following the pattern laid out by 'jerryj' in the comments of
  8558. // http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  8559. var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left'));
  8560. var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top'));
  8561. var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right'));
  8562. var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom'));
  8563. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  8564. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  8565. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  8566. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  8567. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  8568. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  8569. return {
  8570. x: mouseX,
  8571. y: mouseY
  8572. };
  8573. };
  8574. // Private helper function to convert max-width/max-height values that may be percentages into a number
  8575. function parseMaxStyle(styleValue, node, parentProperty) {
  8576. var valueInPixels;
  8577. if (typeof styleValue === 'string') {
  8578. valueInPixels = parseInt(styleValue, 10);
  8579. if (styleValue.indexOf('%') !== -1) {
  8580. // percentage * size in dimension
  8581. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  8582. }
  8583. } else {
  8584. valueInPixels = styleValue;
  8585. }
  8586. return valueInPixels;
  8587. }
  8588. /**
  8589. * Returns if the given value contains an effective constraint.
  8590. * @private
  8591. */
  8592. function isConstrainedValue(value) {
  8593. return value !== undefined && value !== null && value !== 'none';
  8594. }
  8595. // Private helper to get a constraint dimension
  8596. // @param domNode : the node to check the constraint on
  8597. // @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight)
  8598. // @param percentageProperty : property of parent to use when calculating width as a percentage
  8599. // @see http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser
  8600. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  8601. var view = document.defaultView;
  8602. var parentNode = helpers._getParentNode(domNode);
  8603. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  8604. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  8605. var hasCNode = isConstrainedValue(constrainedNode);
  8606. var hasCContainer = isConstrainedValue(constrainedContainer);
  8607. var infinity = Number.POSITIVE_INFINITY;
  8608. if (hasCNode || hasCContainer) {
  8609. return Math.min(
  8610. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  8611. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  8612. }
  8613. return 'none';
  8614. }
  8615. // returns Number or undefined if no constraint
  8616. helpers.getConstraintWidth = function(domNode) {
  8617. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  8618. };
  8619. // returns Number or undefined if no constraint
  8620. helpers.getConstraintHeight = function(domNode) {
  8621. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  8622. };
  8623. /**
  8624. * @private
  8625. */
  8626. helpers._calculatePadding = function(container, padding, parentDimension) {
  8627. padding = helpers.getStyle(container, padding);
  8628. return padding.indexOf('%') > -1 ? parentDimension / parseInt(padding, 10) : parseInt(padding, 10);
  8629. };
  8630. /**
  8631. * @private
  8632. */
  8633. helpers._getParentNode = function(domNode) {
  8634. var parent = domNode.parentNode;
  8635. if (parent && parent.host) {
  8636. parent = parent.host;
  8637. }
  8638. return parent;
  8639. };
  8640. helpers.getMaximumWidth = function(domNode) {
  8641. var container = helpers._getParentNode(domNode);
  8642. if (!container) {
  8643. return domNode.clientWidth;
  8644. }
  8645. var clientWidth = container.clientWidth;
  8646. var paddingLeft = helpers._calculatePadding(container, 'padding-left', clientWidth);
  8647. var paddingRight = helpers._calculatePadding(container, 'padding-right', clientWidth);
  8648. var w = clientWidth - paddingLeft - paddingRight;
  8649. var cw = helpers.getConstraintWidth(domNode);
  8650. return isNaN(cw) ? w : Math.min(w, cw);
  8651. };
  8652. helpers.getMaximumHeight = function(domNode) {
  8653. var container = helpers._getParentNode(domNode);
  8654. if (!container) {
  8655. return domNode.clientHeight;
  8656. }
  8657. var clientHeight = container.clientHeight;
  8658. var paddingTop = helpers._calculatePadding(container, 'padding-top', clientHeight);
  8659. var paddingBottom = helpers._calculatePadding(container, 'padding-bottom', clientHeight);
  8660. var h = clientHeight - paddingTop - paddingBottom;
  8661. var ch = helpers.getConstraintHeight(domNode);
  8662. return isNaN(ch) ? h : Math.min(h, ch);
  8663. };
  8664. helpers.getStyle = function(el, property) {
  8665. return el.currentStyle ?
  8666. el.currentStyle[property] :
  8667. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  8668. };
  8669. helpers.retinaScale = function(chart, forceRatio) {
  8670. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  8671. if (pixelRatio === 1) {
  8672. return;
  8673. }
  8674. var canvas = chart.canvas;
  8675. var height = chart.height;
  8676. var width = chart.width;
  8677. canvas.height = height * pixelRatio;
  8678. canvas.width = width * pixelRatio;
  8679. chart.ctx.scale(pixelRatio, pixelRatio);
  8680. // If no style has been set on the canvas, the render size is used as display size,
  8681. // making the chart visually bigger, so let's enforce it to the "correct" values.
  8682. // See https://github.com/chartjs/Chart.js/issues/3575
  8683. if (!canvas.style.height && !canvas.style.width) {
  8684. canvas.style.height = height + 'px';
  8685. canvas.style.width = width + 'px';
  8686. }
  8687. };
  8688. // -- Canvas methods
  8689. helpers.fontString = function(pixelSize, fontStyle, fontFamily) {
  8690. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  8691. };
  8692. helpers.longestText = function(ctx, font, arrayOfThings, cache) {
  8693. cache = cache || {};
  8694. var data = cache.data = cache.data || {};
  8695. var gc = cache.garbageCollect = cache.garbageCollect || [];
  8696. if (cache.font !== font) {
  8697. data = cache.data = {};
  8698. gc = cache.garbageCollect = [];
  8699. cache.font = font;
  8700. }
  8701. ctx.font = font;
  8702. var longest = 0;
  8703. helpers.each(arrayOfThings, function(thing) {
  8704. // Undefined strings and arrays should not be measured
  8705. if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) {
  8706. longest = helpers.measureText(ctx, data, gc, longest, thing);
  8707. } else if (helpers.isArray(thing)) {
  8708. // if it is an array lets measure each element
  8709. // to do maybe simplify this function a bit so we can do this more recursively?
  8710. helpers.each(thing, function(nestedThing) {
  8711. // Undefined strings and arrays should not be measured
  8712. if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) {
  8713. longest = helpers.measureText(ctx, data, gc, longest, nestedThing);
  8714. }
  8715. });
  8716. }
  8717. });
  8718. var gcLen = gc.length / 2;
  8719. if (gcLen > arrayOfThings.length) {
  8720. for (var i = 0; i < gcLen; i++) {
  8721. delete data[gc[i]];
  8722. }
  8723. gc.splice(0, gcLen);
  8724. }
  8725. return longest;
  8726. };
  8727. helpers.measureText = function(ctx, data, gc, longest, string) {
  8728. var textWidth = data[string];
  8729. if (!textWidth) {
  8730. textWidth = data[string] = ctx.measureText(string).width;
  8731. gc.push(string);
  8732. }
  8733. if (textWidth > longest) {
  8734. longest = textWidth;
  8735. }
  8736. return longest;
  8737. };
  8738. helpers.numberOfLabelLines = function(arrayOfThings) {
  8739. var numberOfLines = 1;
  8740. helpers.each(arrayOfThings, function(thing) {
  8741. if (helpers.isArray(thing)) {
  8742. if (thing.length > numberOfLines) {
  8743. numberOfLines = thing.length;
  8744. }
  8745. }
  8746. });
  8747. return numberOfLines;
  8748. };
  8749. helpers.color = !color ?
  8750. function(value) {
  8751. console.error('Color.js not found!');
  8752. return value;
  8753. } :
  8754. function(value) {
  8755. /* global CanvasGradient */
  8756. if (value instanceof CanvasGradient) {
  8757. value = defaults.global.defaultColor;
  8758. }
  8759. return color(value);
  8760. };
  8761. helpers.getHoverColor = function(colorValue) {
  8762. /* global CanvasPattern */
  8763. return (colorValue instanceof CanvasPattern) ?
  8764. colorValue :
  8765. helpers.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  8766. };
  8767. };
  8768. },{"2":2,"26":26,"34":34,"46":46}],29:[function(require,module,exports){
  8769. 'use strict';
  8770. var helpers = require(46);
  8771. /**
  8772. * Helper function to get relative position for an event
  8773. * @param {Event|IEvent} event - The event to get the position for
  8774. * @param {Chart} chart - The chart
  8775. * @returns {Point} the event position
  8776. */
  8777. function getRelativePosition(e, chart) {
  8778. if (e.native) {
  8779. return {
  8780. x: e.x,
  8781. y: e.y
  8782. };
  8783. }
  8784. return helpers.getRelativePosition(e, chart);
  8785. }
  8786. /**
  8787. * Helper function to traverse all of the visible elements in the chart
  8788. * @param chart {chart} the chart
  8789. * @param handler {Function} the callback to execute for each visible item
  8790. */
  8791. function parseVisibleItems(chart, handler) {
  8792. var datasets = chart.data.datasets;
  8793. var meta, i, j, ilen, jlen;
  8794. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  8795. if (!chart.isDatasetVisible(i)) {
  8796. continue;
  8797. }
  8798. meta = chart.getDatasetMeta(i);
  8799. for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
  8800. var element = meta.data[j];
  8801. if (!element._view.skip) {
  8802. handler(element);
  8803. }
  8804. }
  8805. }
  8806. }
  8807. /**
  8808. * Helper function to get the items that intersect the event position
  8809. * @param items {ChartElement[]} elements to filter
  8810. * @param position {Point} the point to be nearest to
  8811. * @return {ChartElement[]} the nearest items
  8812. */
  8813. function getIntersectItems(chart, position) {
  8814. var elements = [];
  8815. parseVisibleItems(chart, function(element) {
  8816. if (element.inRange(position.x, position.y)) {
  8817. elements.push(element);
  8818. }
  8819. });
  8820. return elements;
  8821. }
  8822. /**
  8823. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  8824. * @param chart {Chart} the chart to look at elements from
  8825. * @param position {Point} the point to be nearest to
  8826. * @param intersect {Boolean} if true, only consider items that intersect the position
  8827. * @param distanceMetric {Function} function to provide the distance between points
  8828. * @return {ChartElement[]} the nearest items
  8829. */
  8830. function getNearestItems(chart, position, intersect, distanceMetric) {
  8831. var minDistance = Number.POSITIVE_INFINITY;
  8832. var nearestItems = [];
  8833. parseVisibleItems(chart, function(element) {
  8834. if (intersect && !element.inRange(position.x, position.y)) {
  8835. return;
  8836. }
  8837. var center = element.getCenterPoint();
  8838. var distance = distanceMetric(position, center);
  8839. if (distance < minDistance) {
  8840. nearestItems = [element];
  8841. minDistance = distance;
  8842. } else if (distance === minDistance) {
  8843. // Can have multiple items at the same distance in which case we sort by size
  8844. nearestItems.push(element);
  8845. }
  8846. });
  8847. return nearestItems;
  8848. }
  8849. /**
  8850. * Get a distance metric function for two points based on the
  8851. * axis mode setting
  8852. * @param {String} axis the axis mode. x|y|xy
  8853. */
  8854. function getDistanceMetricForAxis(axis) {
  8855. var useX = axis.indexOf('x') !== -1;
  8856. var useY = axis.indexOf('y') !== -1;
  8857. return function(pt1, pt2) {
  8858. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  8859. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  8860. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  8861. };
  8862. }
  8863. function indexMode(chart, e, options) {
  8864. var position = getRelativePosition(e, chart);
  8865. // Default axis for index mode is 'x' to match old behaviour
  8866. options.axis = options.axis || 'x';
  8867. var distanceMetric = getDistanceMetricForAxis(options.axis);
  8868. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  8869. var elements = [];
  8870. if (!items.length) {
  8871. return [];
  8872. }
  8873. chart.data.datasets.forEach(function(dataset, datasetIndex) {
  8874. if (chart.isDatasetVisible(datasetIndex)) {
  8875. var meta = chart.getDatasetMeta(datasetIndex);
  8876. var element = meta.data[items[0]._index];
  8877. // don't count items that are skipped (null data)
  8878. if (element && !element._view.skip) {
  8879. elements.push(element);
  8880. }
  8881. }
  8882. });
  8883. return elements;
  8884. }
  8885. /**
  8886. * @interface IInteractionOptions
  8887. */
  8888. /**
  8889. * If true, only consider items that intersect the point
  8890. * @name IInterfaceOptions#boolean
  8891. * @type Boolean
  8892. */
  8893. /**
  8894. * Contains interaction related functions
  8895. * @namespace Chart.Interaction
  8896. */
  8897. module.exports = {
  8898. // Helper function for different modes
  8899. modes: {
  8900. single: function(chart, e) {
  8901. var position = getRelativePosition(e, chart);
  8902. var elements = [];
  8903. parseVisibleItems(chart, function(element) {
  8904. if (element.inRange(position.x, position.y)) {
  8905. elements.push(element);
  8906. return elements;
  8907. }
  8908. });
  8909. return elements.slice(0, 1);
  8910. },
  8911. /**
  8912. * @function Chart.Interaction.modes.label
  8913. * @deprecated since version 2.4.0
  8914. * @todo remove at version 3
  8915. * @private
  8916. */
  8917. label: indexMode,
  8918. /**
  8919. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  8920. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  8921. * @function Chart.Interaction.modes.index
  8922. * @since v2.4.0
  8923. * @param chart {chart} the chart we are returning items from
  8924. * @param e {Event} the event we are find things at
  8925. * @param options {IInteractionOptions} options to use during interaction
  8926. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  8927. */
  8928. index: indexMode,
  8929. /**
  8930. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  8931. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  8932. * @function Chart.Interaction.modes.dataset
  8933. * @param chart {chart} the chart we are returning items from
  8934. * @param e {Event} the event we are find things at
  8935. * @param options {IInteractionOptions} options to use during interaction
  8936. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  8937. */
  8938. dataset: function(chart, e, options) {
  8939. var position = getRelativePosition(e, chart);
  8940. options.axis = options.axis || 'xy';
  8941. var distanceMetric = getDistanceMetricForAxis(options.axis);
  8942. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  8943. if (items.length > 0) {
  8944. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  8945. }
  8946. return items;
  8947. },
  8948. /**
  8949. * @function Chart.Interaction.modes.x-axis
  8950. * @deprecated since version 2.4.0. Use index mode and intersect == true
  8951. * @todo remove at version 3
  8952. * @private
  8953. */
  8954. 'x-axis': function(chart, e) {
  8955. return indexMode(chart, e, {intersect: false});
  8956. },
  8957. /**
  8958. * Point mode returns all elements that hit test based on the event position
  8959. * of the event
  8960. * @function Chart.Interaction.modes.intersect
  8961. * @param chart {chart} the chart we are returning items from
  8962. * @param e {Event} the event we are find things at
  8963. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  8964. */
  8965. point: function(chart, e) {
  8966. var position = getRelativePosition(e, chart);
  8967. return getIntersectItems(chart, position);
  8968. },
  8969. /**
  8970. * nearest mode returns the element closest to the point
  8971. * @function Chart.Interaction.modes.intersect
  8972. * @param chart {chart} the chart we are returning items from
  8973. * @param e {Event} the event we are find things at
  8974. * @param options {IInteractionOptions} options to use
  8975. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  8976. */
  8977. nearest: function(chart, e, options) {
  8978. var position = getRelativePosition(e, chart);
  8979. options.axis = options.axis || 'xy';
  8980. var distanceMetric = getDistanceMetricForAxis(options.axis);
  8981. var nearestItems = getNearestItems(chart, position, options.intersect, distanceMetric);
  8982. // We have multiple items at the same distance from the event. Now sort by smallest
  8983. if (nearestItems.length > 1) {
  8984. nearestItems.sort(function(a, b) {
  8985. var sizeA = a.getArea();
  8986. var sizeB = b.getArea();
  8987. var ret = sizeA - sizeB;
  8988. if (ret === 0) {
  8989. // if equal sort by dataset index
  8990. ret = a._datasetIndex - b._datasetIndex;
  8991. }
  8992. return ret;
  8993. });
  8994. }
  8995. // Return only 1 item
  8996. return nearestItems.slice(0, 1);
  8997. },
  8998. /**
  8999. * x mode returns the elements that hit-test at the current x coordinate
  9000. * @function Chart.Interaction.modes.x
  9001. * @param chart {chart} the chart we are returning items from
  9002. * @param e {Event} the event we are find things at
  9003. * @param options {IInteractionOptions} options to use
  9004. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  9005. */
  9006. x: function(chart, e, options) {
  9007. var position = getRelativePosition(e, chart);
  9008. var items = [];
  9009. var intersectsItem = false;
  9010. parseVisibleItems(chart, function(element) {
  9011. if (element.inXRange(position.x)) {
  9012. items.push(element);
  9013. }
  9014. if (element.inRange(position.x, position.y)) {
  9015. intersectsItem = true;
  9016. }
  9017. });
  9018. // If we want to trigger on an intersect and we don't have any items
  9019. // that intersect the position, return nothing
  9020. if (options.intersect && !intersectsItem) {
  9021. items = [];
  9022. }
  9023. return items;
  9024. },
  9025. /**
  9026. * y mode returns the elements that hit-test at the current y coordinate
  9027. * @function Chart.Interaction.modes.y
  9028. * @param chart {chart} the chart we are returning items from
  9029. * @param e {Event} the event we are find things at
  9030. * @param options {IInteractionOptions} options to use
  9031. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  9032. */
  9033. y: function(chart, e, options) {
  9034. var position = getRelativePosition(e, chart);
  9035. var items = [];
  9036. var intersectsItem = false;
  9037. parseVisibleItems(chart, function(element) {
  9038. if (element.inYRange(position.y)) {
  9039. items.push(element);
  9040. }
  9041. if (element.inRange(position.x, position.y)) {
  9042. intersectsItem = true;
  9043. }
  9044. });
  9045. // If we want to trigger on an intersect and we don't have any items
  9046. // that intersect the position, return nothing
  9047. if (options.intersect && !intersectsItem) {
  9048. items = [];
  9049. }
  9050. return items;
  9051. }
  9052. }
  9053. };
  9054. },{"46":46}],30:[function(require,module,exports){
  9055. 'use strict';
  9056. var defaults = require(26);
  9057. defaults._set('global', {
  9058. responsive: true,
  9059. responsiveAnimationDuration: 0,
  9060. maintainAspectRatio: true,
  9061. events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
  9062. hover: {
  9063. onHover: null,
  9064. mode: 'nearest',
  9065. intersect: true,
  9066. animationDuration: 400
  9067. },
  9068. onClick: null,
  9069. defaultColor: 'rgba(0,0,0,0.1)',
  9070. defaultFontColor: '#666',
  9071. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  9072. defaultFontSize: 12,
  9073. defaultFontStyle: 'normal',
  9074. showLines: true,
  9075. // Element defaults defined in element extensions
  9076. elements: {},
  9077. // Layout options such as padding
  9078. layout: {
  9079. padding: {
  9080. top: 0,
  9081. right: 0,
  9082. bottom: 0,
  9083. left: 0
  9084. }
  9085. }
  9086. });
  9087. module.exports = function() {
  9088. // Occupy the global variable of Chart, and create a simple base class
  9089. var Chart = function(item, config) {
  9090. this.construct(item, config);
  9091. return this;
  9092. };
  9093. Chart.Chart = Chart;
  9094. return Chart;
  9095. };
  9096. },{"26":26}],31:[function(require,module,exports){
  9097. 'use strict';
  9098. var helpers = require(46);
  9099. function filterByPosition(array, position) {
  9100. return helpers.where(array, function(v) {
  9101. return v.position === position;
  9102. });
  9103. }
  9104. function sortByWeight(array, reverse) {
  9105. array.forEach(function(v, i) {
  9106. v._tmpIndex_ = i;
  9107. return v;
  9108. });
  9109. array.sort(function(a, b) {
  9110. var v0 = reverse ? b : a;
  9111. var v1 = reverse ? a : b;
  9112. return v0.weight === v1.weight ?
  9113. v0._tmpIndex_ - v1._tmpIndex_ :
  9114. v0.weight - v1.weight;
  9115. });
  9116. array.forEach(function(v) {
  9117. delete v._tmpIndex_;
  9118. });
  9119. }
  9120. /**
  9121. * @interface ILayoutItem
  9122. * @prop {String} position - The position of the item in the chart layout. Possible values are
  9123. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  9124. * @prop {Number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  9125. * @prop {Boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  9126. * @prop {Function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  9127. * @prop {Function} update - Takes two parameters: width and height. Returns size of item
  9128. * @prop {Function} getPadding - Returns an object with padding on the edges
  9129. * @prop {Number} width - Width of item. Must be valid after update()
  9130. * @prop {Number} height - Height of item. Must be valid after update()
  9131. * @prop {Number} left - Left edge of the item. Set by layout system and cannot be used in update
  9132. * @prop {Number} top - Top edge of the item. Set by layout system and cannot be used in update
  9133. * @prop {Number} right - Right edge of the item. Set by layout system and cannot be used in update
  9134. * @prop {Number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  9135. */
  9136. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  9137. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  9138. // It is this service's responsibility of carrying out that layout.
  9139. module.exports = {
  9140. defaults: {},
  9141. /**
  9142. * Register a box to a chart.
  9143. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  9144. * @param {Chart} chart - the chart to use
  9145. * @param {ILayoutItem} item - the item to add to be layed out
  9146. */
  9147. addBox: function(chart, item) {
  9148. if (!chart.boxes) {
  9149. chart.boxes = [];
  9150. }
  9151. // initialize item with default values
  9152. item.fullWidth = item.fullWidth || false;
  9153. item.position = item.position || 'top';
  9154. item.weight = item.weight || 0;
  9155. chart.boxes.push(item);
  9156. },
  9157. /**
  9158. * Remove a layoutItem from a chart
  9159. * @param {Chart} chart - the chart to remove the box from
  9160. * @param {Object} layoutItem - the item to remove from the layout
  9161. */
  9162. removeBox: function(chart, layoutItem) {
  9163. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  9164. if (index !== -1) {
  9165. chart.boxes.splice(index, 1);
  9166. }
  9167. },
  9168. /**
  9169. * Sets (or updates) options on the given `item`.
  9170. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  9171. * @param {Object} item - the item to configure with the given options
  9172. * @param {Object} options - the new item options.
  9173. */
  9174. configure: function(chart, item, options) {
  9175. var props = ['fullWidth', 'position', 'weight'];
  9176. var ilen = props.length;
  9177. var i = 0;
  9178. var prop;
  9179. for (; i < ilen; ++i) {
  9180. prop = props[i];
  9181. if (options.hasOwnProperty(prop)) {
  9182. item[prop] = options[prop];
  9183. }
  9184. }
  9185. },
  9186. /**
  9187. * Fits boxes of the given chart into the given size by having each box measure itself
  9188. * then running a fitting algorithm
  9189. * @param {Chart} chart - the chart
  9190. * @param {Number} width - the width to fit into
  9191. * @param {Number} height - the height to fit into
  9192. */
  9193. update: function(chart, width, height) {
  9194. if (!chart) {
  9195. return;
  9196. }
  9197. var layoutOptions = chart.options.layout || {};
  9198. var padding = helpers.options.toPadding(layoutOptions.padding);
  9199. var leftPadding = padding.left;
  9200. var rightPadding = padding.right;
  9201. var topPadding = padding.top;
  9202. var bottomPadding = padding.bottom;
  9203. var leftBoxes = filterByPosition(chart.boxes, 'left');
  9204. var rightBoxes = filterByPosition(chart.boxes, 'right');
  9205. var topBoxes = filterByPosition(chart.boxes, 'top');
  9206. var bottomBoxes = filterByPosition(chart.boxes, 'bottom');
  9207. var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');
  9208. // Sort boxes by weight. A higher weight is further away from the chart area
  9209. sortByWeight(leftBoxes, true);
  9210. sortByWeight(rightBoxes, false);
  9211. sortByWeight(topBoxes, true);
  9212. sortByWeight(bottomBoxes, false);
  9213. // Essentially we now have any number of boxes on each of the 4 sides.
  9214. // Our canvas looks like the following.
  9215. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  9216. // B1 is the bottom axis
  9217. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  9218. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  9219. // an error will be thrown.
  9220. //
  9221. // |----------------------------------------------------|
  9222. // | T1 (Full Width) |
  9223. // |----------------------------------------------------|
  9224. // | | | T2 | |
  9225. // | |----|-------------------------------------|----|
  9226. // | | | C1 | | C2 | |
  9227. // | | |----| |----| |
  9228. // | | | | |
  9229. // | L1 | L2 | ChartArea (C0) | R1 |
  9230. // | | | | |
  9231. // | | |----| |----| |
  9232. // | | | C3 | | C4 | |
  9233. // | |----|-------------------------------------|----|
  9234. // | | | B1 | |
  9235. // |----------------------------------------------------|
  9236. // | B2 (Full Width) |
  9237. // |----------------------------------------------------|
  9238. //
  9239. // What we do to find the best sizing, we do the following
  9240. // 1. Determine the minimum size of the chart area.
  9241. // 2. Split the remaining width equally between each vertical axis
  9242. // 3. Split the remaining height equally between each horizontal axis
  9243. // 4. Give each layout the maximum size it can be. The layout will return it's minimum size
  9244. // 5. Adjust the sizes of each axis based on it's minimum reported size.
  9245. // 6. Refit each axis
  9246. // 7. Position each axis in the final location
  9247. // 8. Tell the chart the final location of the chart area
  9248. // 9. Tell any axes that overlay the chart area the positions of the chart area
  9249. // Step 1
  9250. var chartWidth = width - leftPadding - rightPadding;
  9251. var chartHeight = height - topPadding - bottomPadding;
  9252. var chartAreaWidth = chartWidth / 2; // min 50%
  9253. var chartAreaHeight = chartHeight / 2; // min 50%
  9254. // Step 2
  9255. var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length);
  9256. // Step 3
  9257. var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length);
  9258. // Step 4
  9259. var maxChartAreaWidth = chartWidth;
  9260. var maxChartAreaHeight = chartHeight;
  9261. var minBoxSizes = [];
  9262. function getMinimumBoxSize(box) {
  9263. var minSize;
  9264. var isHorizontal = box.isHorizontal();
  9265. if (isHorizontal) {
  9266. minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight);
  9267. maxChartAreaHeight -= minSize.height;
  9268. } else {
  9269. minSize = box.update(verticalBoxWidth, maxChartAreaHeight);
  9270. maxChartAreaWidth -= minSize.width;
  9271. }
  9272. minBoxSizes.push({
  9273. horizontal: isHorizontal,
  9274. minSize: minSize,
  9275. box: box,
  9276. });
  9277. }
  9278. helpers.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize);
  9279. // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
  9280. var maxHorizontalLeftPadding = 0;
  9281. var maxHorizontalRightPadding = 0;
  9282. var maxVerticalTopPadding = 0;
  9283. var maxVerticalBottomPadding = 0;
  9284. helpers.each(topBoxes.concat(bottomBoxes), function(horizontalBox) {
  9285. if (horizontalBox.getPadding) {
  9286. var boxPadding = horizontalBox.getPadding();
  9287. maxHorizontalLeftPadding = Math.max(maxHorizontalLeftPadding, boxPadding.left);
  9288. maxHorizontalRightPadding = Math.max(maxHorizontalRightPadding, boxPadding.right);
  9289. }
  9290. });
  9291. helpers.each(leftBoxes.concat(rightBoxes), function(verticalBox) {
  9292. if (verticalBox.getPadding) {
  9293. var boxPadding = verticalBox.getPadding();
  9294. maxVerticalTopPadding = Math.max(maxVerticalTopPadding, boxPadding.top);
  9295. maxVerticalBottomPadding = Math.max(maxVerticalBottomPadding, boxPadding.bottom);
  9296. }
  9297. });
  9298. // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
  9299. // be if the axes are drawn at their minimum sizes.
  9300. // Steps 5 & 6
  9301. var totalLeftBoxesWidth = leftPadding;
  9302. var totalRightBoxesWidth = rightPadding;
  9303. var totalTopBoxesHeight = topPadding;
  9304. var totalBottomBoxesHeight = bottomPadding;
  9305. // Function to fit a box
  9306. function fitBox(box) {
  9307. var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBox) {
  9308. return minBox.box === box;
  9309. });
  9310. if (minBoxSize) {
  9311. if (box.isHorizontal()) {
  9312. var scaleMargin = {
  9313. left: Math.max(totalLeftBoxesWidth, maxHorizontalLeftPadding),
  9314. right: Math.max(totalRightBoxesWidth, maxHorizontalRightPadding),
  9315. top: 0,
  9316. bottom: 0
  9317. };
  9318. // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
  9319. // on the margin. Sometimes they need to increase in size slightly
  9320. box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
  9321. } else {
  9322. box.update(minBoxSize.minSize.width, maxChartAreaHeight);
  9323. }
  9324. }
  9325. }
  9326. // Update, and calculate the left and right margins for the horizontal boxes
  9327. helpers.each(leftBoxes.concat(rightBoxes), fitBox);
  9328. helpers.each(leftBoxes, function(box) {
  9329. totalLeftBoxesWidth += box.width;
  9330. });
  9331. helpers.each(rightBoxes, function(box) {
  9332. totalRightBoxesWidth += box.width;
  9333. });
  9334. // Set the Left and Right margins for the horizontal boxes
  9335. helpers.each(topBoxes.concat(bottomBoxes), fitBox);
  9336. // Figure out how much margin is on the top and bottom of the vertical boxes
  9337. helpers.each(topBoxes, function(box) {
  9338. totalTopBoxesHeight += box.height;
  9339. });
  9340. helpers.each(bottomBoxes, function(box) {
  9341. totalBottomBoxesHeight += box.height;
  9342. });
  9343. function finalFitVerticalBox(box) {
  9344. var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minSize) {
  9345. return minSize.box === box;
  9346. });
  9347. var scaleMargin = {
  9348. left: 0,
  9349. right: 0,
  9350. top: totalTopBoxesHeight,
  9351. bottom: totalBottomBoxesHeight
  9352. };
  9353. if (minBoxSize) {
  9354. box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin);
  9355. }
  9356. }
  9357. // Let the left layout know the final margin
  9358. helpers.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox);
  9359. // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
  9360. totalLeftBoxesWidth = leftPadding;
  9361. totalRightBoxesWidth = rightPadding;
  9362. totalTopBoxesHeight = topPadding;
  9363. totalBottomBoxesHeight = bottomPadding;
  9364. helpers.each(leftBoxes, function(box) {
  9365. totalLeftBoxesWidth += box.width;
  9366. });
  9367. helpers.each(rightBoxes, function(box) {
  9368. totalRightBoxesWidth += box.width;
  9369. });
  9370. helpers.each(topBoxes, function(box) {
  9371. totalTopBoxesHeight += box.height;
  9372. });
  9373. helpers.each(bottomBoxes, function(box) {
  9374. totalBottomBoxesHeight += box.height;
  9375. });
  9376. // We may be adding some padding to account for rotated x axis labels
  9377. var leftPaddingAddition = Math.max(maxHorizontalLeftPadding - totalLeftBoxesWidth, 0);
  9378. totalLeftBoxesWidth += leftPaddingAddition;
  9379. totalRightBoxesWidth += Math.max(maxHorizontalRightPadding - totalRightBoxesWidth, 0);
  9380. var topPaddingAddition = Math.max(maxVerticalTopPadding - totalTopBoxesHeight, 0);
  9381. totalTopBoxesHeight += topPaddingAddition;
  9382. totalBottomBoxesHeight += Math.max(maxVerticalBottomPadding - totalBottomBoxesHeight, 0);
  9383. // Figure out if our chart area changed. This would occur if the dataset layout label rotation
  9384. // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
  9385. // without calling `fit` again
  9386. var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight;
  9387. var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth;
  9388. if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
  9389. helpers.each(leftBoxes, function(box) {
  9390. box.height = newMaxChartAreaHeight;
  9391. });
  9392. helpers.each(rightBoxes, function(box) {
  9393. box.height = newMaxChartAreaHeight;
  9394. });
  9395. helpers.each(topBoxes, function(box) {
  9396. if (!box.fullWidth) {
  9397. box.width = newMaxChartAreaWidth;
  9398. }
  9399. });
  9400. helpers.each(bottomBoxes, function(box) {
  9401. if (!box.fullWidth) {
  9402. box.width = newMaxChartAreaWidth;
  9403. }
  9404. });
  9405. maxChartAreaHeight = newMaxChartAreaHeight;
  9406. maxChartAreaWidth = newMaxChartAreaWidth;
  9407. }
  9408. // Step 7 - Position the boxes
  9409. var left = leftPadding + leftPaddingAddition;
  9410. var top = topPadding + topPaddingAddition;
  9411. function placeBox(box) {
  9412. if (box.isHorizontal()) {
  9413. box.left = box.fullWidth ? leftPadding : totalLeftBoxesWidth;
  9414. box.right = box.fullWidth ? width - rightPadding : totalLeftBoxesWidth + maxChartAreaWidth;
  9415. box.top = top;
  9416. box.bottom = top + box.height;
  9417. // Move to next point
  9418. top = box.bottom;
  9419. } else {
  9420. box.left = left;
  9421. box.right = left + box.width;
  9422. box.top = totalTopBoxesHeight;
  9423. box.bottom = totalTopBoxesHeight + maxChartAreaHeight;
  9424. // Move to next point
  9425. left = box.right;
  9426. }
  9427. }
  9428. helpers.each(leftBoxes.concat(topBoxes), placeBox);
  9429. // Account for chart width and height
  9430. left += maxChartAreaWidth;
  9431. top += maxChartAreaHeight;
  9432. helpers.each(rightBoxes, placeBox);
  9433. helpers.each(bottomBoxes, placeBox);
  9434. // Step 8
  9435. chart.chartArea = {
  9436. left: totalLeftBoxesWidth,
  9437. top: totalTopBoxesHeight,
  9438. right: totalLeftBoxesWidth + maxChartAreaWidth,
  9439. bottom: totalTopBoxesHeight + maxChartAreaHeight
  9440. };
  9441. // Step 9
  9442. helpers.each(chartAreaBoxes, function(box) {
  9443. box.left = chart.chartArea.left;
  9444. box.top = chart.chartArea.top;
  9445. box.right = chart.chartArea.right;
  9446. box.bottom = chart.chartArea.bottom;
  9447. box.update(maxChartAreaWidth, maxChartAreaHeight);
  9448. });
  9449. }
  9450. };
  9451. },{"46":46}],32:[function(require,module,exports){
  9452. 'use strict';
  9453. var defaults = require(26);
  9454. var helpers = require(46);
  9455. defaults._set('global', {
  9456. plugins: {}
  9457. });
  9458. /**
  9459. * The plugin service singleton
  9460. * @namespace Chart.plugins
  9461. * @since 2.1.0
  9462. */
  9463. module.exports = {
  9464. /**
  9465. * Globally registered plugins.
  9466. * @private
  9467. */
  9468. _plugins: [],
  9469. /**
  9470. * This identifier is used to invalidate the descriptors cache attached to each chart
  9471. * when a global plugin is registered or unregistered. In this case, the cache ID is
  9472. * incremented and descriptors are regenerated during following API calls.
  9473. * @private
  9474. */
  9475. _cacheId: 0,
  9476. /**
  9477. * Registers the given plugin(s) if not already registered.
  9478. * @param {Array|Object} plugins plugin instance(s).
  9479. */
  9480. register: function(plugins) {
  9481. var p = this._plugins;
  9482. ([]).concat(plugins).forEach(function(plugin) {
  9483. if (p.indexOf(plugin) === -1) {
  9484. p.push(plugin);
  9485. }
  9486. });
  9487. this._cacheId++;
  9488. },
  9489. /**
  9490. * Unregisters the given plugin(s) only if registered.
  9491. * @param {Array|Object} plugins plugin instance(s).
  9492. */
  9493. unregister: function(plugins) {
  9494. var p = this._plugins;
  9495. ([]).concat(plugins).forEach(function(plugin) {
  9496. var idx = p.indexOf(plugin);
  9497. if (idx !== -1) {
  9498. p.splice(idx, 1);
  9499. }
  9500. });
  9501. this._cacheId++;
  9502. },
  9503. /**
  9504. * Remove all registered plugins.
  9505. * @since 2.1.5
  9506. */
  9507. clear: function() {
  9508. this._plugins = [];
  9509. this._cacheId++;
  9510. },
  9511. /**
  9512. * Returns the number of registered plugins?
  9513. * @returns {Number}
  9514. * @since 2.1.5
  9515. */
  9516. count: function() {
  9517. return this._plugins.length;
  9518. },
  9519. /**
  9520. * Returns all registered plugin instances.
  9521. * @returns {Array} array of plugin objects.
  9522. * @since 2.1.5
  9523. */
  9524. getAll: function() {
  9525. return this._plugins;
  9526. },
  9527. /**
  9528. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  9529. * This method immediately returns as soon as a plugin explicitly returns false. The
  9530. * returned value can be used, for instance, to interrupt the current action.
  9531. * @param {Object} chart - The chart instance for which plugins should be called.
  9532. * @param {String} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  9533. * @param {Array} [args] - Extra arguments to apply to the hook call.
  9534. * @returns {Boolean} false if any of the plugins return false, else returns true.
  9535. */
  9536. notify: function(chart, hook, args) {
  9537. var descriptors = this.descriptors(chart);
  9538. var ilen = descriptors.length;
  9539. var i, descriptor, plugin, params, method;
  9540. for (i = 0; i < ilen; ++i) {
  9541. descriptor = descriptors[i];
  9542. plugin = descriptor.plugin;
  9543. method = plugin[hook];
  9544. if (typeof method === 'function') {
  9545. params = [chart].concat(args || []);
  9546. params.push(descriptor.options);
  9547. if (method.apply(plugin, params) === false) {
  9548. return false;
  9549. }
  9550. }
  9551. }
  9552. return true;
  9553. },
  9554. /**
  9555. * Returns descriptors of enabled plugins for the given chart.
  9556. * @returns {Array} [{ plugin, options }]
  9557. * @private
  9558. */
  9559. descriptors: function(chart) {
  9560. var cache = chart.$plugins || (chart.$plugins = {});
  9561. if (cache.id === this._cacheId) {
  9562. return cache.descriptors;
  9563. }
  9564. var plugins = [];
  9565. var descriptors = [];
  9566. var config = (chart && chart.config) || {};
  9567. var options = (config.options && config.options.plugins) || {};
  9568. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  9569. var idx = plugins.indexOf(plugin);
  9570. if (idx !== -1) {
  9571. return;
  9572. }
  9573. var id = plugin.id;
  9574. var opts = options[id];
  9575. if (opts === false) {
  9576. return;
  9577. }
  9578. if (opts === true) {
  9579. opts = helpers.clone(defaults.global.plugins[id]);
  9580. }
  9581. plugins.push(plugin);
  9582. descriptors.push({
  9583. plugin: plugin,
  9584. options: opts || {}
  9585. });
  9586. });
  9587. cache.descriptors = descriptors;
  9588. cache.id = this._cacheId;
  9589. return descriptors;
  9590. },
  9591. /**
  9592. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  9593. * but in some cases, this reference can be changed by the user when updating options.
  9594. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  9595. * @private
  9596. */
  9597. _invalidate: function(chart) {
  9598. delete chart.$plugins;
  9599. }
  9600. };
  9601. /**
  9602. * Plugin extension hooks.
  9603. * @interface IPlugin
  9604. * @since 2.1.0
  9605. */
  9606. /**
  9607. * @method IPlugin#beforeInit
  9608. * @desc Called before initializing `chart`.
  9609. * @param {Chart.Controller} chart - The chart instance.
  9610. * @param {Object} options - The plugin options.
  9611. */
  9612. /**
  9613. * @method IPlugin#afterInit
  9614. * @desc Called after `chart` has been initialized and before the first update.
  9615. * @param {Chart.Controller} chart - The chart instance.
  9616. * @param {Object} options - The plugin options.
  9617. */
  9618. /**
  9619. * @method IPlugin#beforeUpdate
  9620. * @desc Called before updating `chart`. If any plugin returns `false`, the update
  9621. * is cancelled (and thus subsequent render(s)) until another `update` is triggered.
  9622. * @param {Chart.Controller} chart - The chart instance.
  9623. * @param {Object} options - The plugin options.
  9624. * @returns {Boolean} `false` to cancel the chart update.
  9625. */
  9626. /**
  9627. * @method IPlugin#afterUpdate
  9628. * @desc Called after `chart` has been updated and before rendering. Note that this
  9629. * hook will not be called if the chart update has been previously cancelled.
  9630. * @param {Chart.Controller} chart - The chart instance.
  9631. * @param {Object} options - The plugin options.
  9632. */
  9633. /**
  9634. * @method IPlugin#beforeDatasetsUpdate
  9635. * @desc Called before updating the `chart` datasets. If any plugin returns `false`,
  9636. * the datasets update is cancelled until another `update` is triggered.
  9637. * @param {Chart.Controller} chart - The chart instance.
  9638. * @param {Object} options - The plugin options.
  9639. * @returns {Boolean} false to cancel the datasets update.
  9640. * @since version 2.1.5
  9641. */
  9642. /**
  9643. * @method IPlugin#afterDatasetsUpdate
  9644. * @desc Called after the `chart` datasets have been updated. Note that this hook
  9645. * will not be called if the datasets update has been previously cancelled.
  9646. * @param {Chart.Controller} chart - The chart instance.
  9647. * @param {Object} options - The plugin options.
  9648. * @since version 2.1.5
  9649. */
  9650. /**
  9651. * @method IPlugin#beforeDatasetUpdate
  9652. * @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin
  9653. * returns `false`, the datasets update is cancelled until another `update` is triggered.
  9654. * @param {Chart} chart - The chart instance.
  9655. * @param {Object} args - The call arguments.
  9656. * @param {Number} args.index - The dataset index.
  9657. * @param {Object} args.meta - The dataset metadata.
  9658. * @param {Object} options - The plugin options.
  9659. * @returns {Boolean} `false` to cancel the chart datasets drawing.
  9660. */
  9661. /**
  9662. * @method IPlugin#afterDatasetUpdate
  9663. * @desc Called after the `chart` datasets at the given `args.index` has been updated. Note
  9664. * that this hook will not be called if the datasets update has been previously cancelled.
  9665. * @param {Chart} chart - The chart instance.
  9666. * @param {Object} args - The call arguments.
  9667. * @param {Number} args.index - The dataset index.
  9668. * @param {Object} args.meta - The dataset metadata.
  9669. * @param {Object} options - The plugin options.
  9670. */
  9671. /**
  9672. * @method IPlugin#beforeLayout
  9673. * @desc Called before laying out `chart`. If any plugin returns `false`,
  9674. * the layout update is cancelled until another `update` is triggered.
  9675. * @param {Chart.Controller} chart - The chart instance.
  9676. * @param {Object} options - The plugin options.
  9677. * @returns {Boolean} `false` to cancel the chart layout.
  9678. */
  9679. /**
  9680. * @method IPlugin#afterLayout
  9681. * @desc Called after the `chart` has been layed out. Note that this hook will not
  9682. * be called if the layout update has been previously cancelled.
  9683. * @param {Chart.Controller} chart - The chart instance.
  9684. * @param {Object} options - The plugin options.
  9685. */
  9686. /**
  9687. * @method IPlugin#beforeRender
  9688. * @desc Called before rendering `chart`. If any plugin returns `false`,
  9689. * the rendering is cancelled until another `render` is triggered.
  9690. * @param {Chart.Controller} chart - The chart instance.
  9691. * @param {Object} options - The plugin options.
  9692. * @returns {Boolean} `false` to cancel the chart rendering.
  9693. */
  9694. /**
  9695. * @method IPlugin#afterRender
  9696. * @desc Called after the `chart` has been fully rendered (and animation completed). Note
  9697. * that this hook will not be called if the rendering has been previously cancelled.
  9698. * @param {Chart.Controller} chart - The chart instance.
  9699. * @param {Object} options - The plugin options.
  9700. */
  9701. /**
  9702. * @method IPlugin#beforeDraw
  9703. * @desc Called before drawing `chart` at every animation frame specified by the given
  9704. * easing value. If any plugin returns `false`, the frame drawing is cancelled until
  9705. * another `render` is triggered.
  9706. * @param {Chart.Controller} chart - The chart instance.
  9707. * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
  9708. * @param {Object} options - The plugin options.
  9709. * @returns {Boolean} `false` to cancel the chart drawing.
  9710. */
  9711. /**
  9712. * @method IPlugin#afterDraw
  9713. * @desc Called after the `chart` has been drawn for the specific easing value. Note
  9714. * that this hook will not be called if the drawing has been previously cancelled.
  9715. * @param {Chart.Controller} chart - The chart instance.
  9716. * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
  9717. * @param {Object} options - The plugin options.
  9718. */
  9719. /**
  9720. * @method IPlugin#beforeDatasetsDraw
  9721. * @desc Called before drawing the `chart` datasets. If any plugin returns `false`,
  9722. * the datasets drawing is cancelled until another `render` is triggered.
  9723. * @param {Chart.Controller} chart - The chart instance.
  9724. * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
  9725. * @param {Object} options - The plugin options.
  9726. * @returns {Boolean} `false` to cancel the chart datasets drawing.
  9727. */
  9728. /**
  9729. * @method IPlugin#afterDatasetsDraw
  9730. * @desc Called after the `chart` datasets have been drawn. Note that this hook
  9731. * will not be called if the datasets drawing has been previously cancelled.
  9732. * @param {Chart.Controller} chart - The chart instance.
  9733. * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
  9734. * @param {Object} options - The plugin options.
  9735. */
  9736. /**
  9737. * @method IPlugin#beforeDatasetDraw
  9738. * @desc Called before drawing the `chart` dataset at the given `args.index` (datasets
  9739. * are drawn in the reverse order). If any plugin returns `false`, the datasets drawing
  9740. * is cancelled until another `render` is triggered.
  9741. * @param {Chart} chart - The chart instance.
  9742. * @param {Object} args - The call arguments.
  9743. * @param {Number} args.index - The dataset index.
  9744. * @param {Object} args.meta - The dataset metadata.
  9745. * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
  9746. * @param {Object} options - The plugin options.
  9747. * @returns {Boolean} `false` to cancel the chart datasets drawing.
  9748. */
  9749. /**
  9750. * @method IPlugin#afterDatasetDraw
  9751. * @desc Called after the `chart` datasets at the given `args.index` have been drawn
  9752. * (datasets are drawn in the reverse order). Note that this hook will not be called
  9753. * if the datasets drawing has been previously cancelled.
  9754. * @param {Chart} chart - The chart instance.
  9755. * @param {Object} args - The call arguments.
  9756. * @param {Number} args.index - The dataset index.
  9757. * @param {Object} args.meta - The dataset metadata.
  9758. * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
  9759. * @param {Object} options - The plugin options.
  9760. */
  9761. /**
  9762. * @method IPlugin#beforeTooltipDraw
  9763. * @desc Called before drawing the `tooltip`. If any plugin returns `false`,
  9764. * the tooltip drawing is cancelled until another `render` is triggered.
  9765. * @param {Chart} chart - The chart instance.
  9766. * @param {Object} args - The call arguments.
  9767. * @param {Object} args.tooltip - The tooltip.
  9768. * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
  9769. * @param {Object} options - The plugin options.
  9770. * @returns {Boolean} `false` to cancel the chart tooltip drawing.
  9771. */
  9772. /**
  9773. * @method IPlugin#afterTooltipDraw
  9774. * @desc Called after drawing the `tooltip`. Note that this hook will not
  9775. * be called if the tooltip drawing has been previously cancelled.
  9776. * @param {Chart} chart - The chart instance.
  9777. * @param {Object} args - The call arguments.
  9778. * @param {Object} args.tooltip - The tooltip.
  9779. * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
  9780. * @param {Object} options - The plugin options.
  9781. */
  9782. /**
  9783. * @method IPlugin#beforeEvent
  9784. * @desc Called before processing the specified `event`. If any plugin returns `false`,
  9785. * the event will be discarded.
  9786. * @param {Chart.Controller} chart - The chart instance.
  9787. * @param {IEvent} event - The event object.
  9788. * @param {Object} options - The plugin options.
  9789. */
  9790. /**
  9791. * @method IPlugin#afterEvent
  9792. * @desc Called after the `event` has been consumed. Note that this hook
  9793. * will not be called if the `event` has been previously discarded.
  9794. * @param {Chart.Controller} chart - The chart instance.
  9795. * @param {IEvent} event - The event object.
  9796. * @param {Object} options - The plugin options.
  9797. */
  9798. /**
  9799. * @method IPlugin#resize
  9800. * @desc Called after the chart as been resized.
  9801. * @param {Chart.Controller} chart - The chart instance.
  9802. * @param {Number} size - The new canvas display size (eq. canvas.style width & height).
  9803. * @param {Object} options - The plugin options.
  9804. */
  9805. /**
  9806. * @method IPlugin#destroy
  9807. * @desc Called after the chart as been destroyed.
  9808. * @param {Chart.Controller} chart - The chart instance.
  9809. * @param {Object} options - The plugin options.
  9810. */
  9811. },{"26":26,"46":46}],33:[function(require,module,exports){
  9812. 'use strict';
  9813. var defaults = require(26);
  9814. var Element = require(27);
  9815. var helpers = require(46);
  9816. var Ticks = require(35);
  9817. defaults._set('scale', {
  9818. display: true,
  9819. position: 'left',
  9820. offset: false,
  9821. // grid line settings
  9822. gridLines: {
  9823. display: true,
  9824. color: 'rgba(0, 0, 0, 0.1)',
  9825. lineWidth: 1,
  9826. drawBorder: true,
  9827. drawOnChartArea: true,
  9828. drawTicks: true,
  9829. tickMarkLength: 10,
  9830. zeroLineWidth: 1,
  9831. zeroLineColor: 'rgba(0,0,0,0.25)',
  9832. zeroLineBorderDash: [],
  9833. zeroLineBorderDashOffset: 0.0,
  9834. offsetGridLines: false,
  9835. borderDash: [],
  9836. borderDashOffset: 0.0
  9837. },
  9838. // scale label
  9839. scaleLabel: {
  9840. // display property
  9841. display: false,
  9842. // actual label
  9843. labelString: '',
  9844. // line height
  9845. lineHeight: 1.2,
  9846. // top/bottom padding
  9847. padding: {
  9848. top: 4,
  9849. bottom: 4
  9850. }
  9851. },
  9852. // label settings
  9853. ticks: {
  9854. beginAtZero: false,
  9855. minRotation: 0,
  9856. maxRotation: 50,
  9857. mirror: false,
  9858. padding: 0,
  9859. reverse: false,
  9860. display: true,
  9861. autoSkip: true,
  9862. autoSkipPadding: 0,
  9863. labelOffset: 0,
  9864. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  9865. callback: Ticks.formatters.values,
  9866. minor: {},
  9867. major: {}
  9868. }
  9869. });
  9870. function labelsFromTicks(ticks) {
  9871. var labels = [];
  9872. var i, ilen;
  9873. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  9874. labels.push(ticks[i].label);
  9875. }
  9876. return labels;
  9877. }
  9878. function getLineValue(scale, index, offsetGridLines) {
  9879. var lineValue = scale.getPixelForTick(index);
  9880. if (offsetGridLines) {
  9881. if (index === 0) {
  9882. lineValue -= (scale.getPixelForTick(1) - lineValue) / 2;
  9883. } else {
  9884. lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2;
  9885. }
  9886. }
  9887. return lineValue;
  9888. }
  9889. function computeTextSize(context, tick, font) {
  9890. return helpers.isArray(tick) ?
  9891. helpers.longestText(context, font, tick) :
  9892. context.measureText(tick).width;
  9893. }
  9894. function parseFontOptions(options) {
  9895. var valueOrDefault = helpers.valueOrDefault;
  9896. var globalDefaults = defaults.global;
  9897. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  9898. var style = valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle);
  9899. var family = valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily);
  9900. return {
  9901. size: size,
  9902. style: style,
  9903. family: family,
  9904. font: helpers.fontString(size, style, family)
  9905. };
  9906. }
  9907. function parseLineHeight(options) {
  9908. return helpers.options.toLineHeight(
  9909. helpers.valueOrDefault(options.lineHeight, 1.2),
  9910. helpers.valueOrDefault(options.fontSize, defaults.global.defaultFontSize));
  9911. }
  9912. module.exports = Element.extend({
  9913. /**
  9914. * Get the padding needed for the scale
  9915. * @method getPadding
  9916. * @private
  9917. * @returns {Padding} the necessary padding
  9918. */
  9919. getPadding: function() {
  9920. var me = this;
  9921. return {
  9922. left: me.paddingLeft || 0,
  9923. top: me.paddingTop || 0,
  9924. right: me.paddingRight || 0,
  9925. bottom: me.paddingBottom || 0
  9926. };
  9927. },
  9928. /**
  9929. * Returns the scale tick objects ({label, major})
  9930. * @since 2.7
  9931. */
  9932. getTicks: function() {
  9933. return this._ticks;
  9934. },
  9935. // These methods are ordered by lifecyle. Utilities then follow.
  9936. // Any function defined here is inherited by all scale types.
  9937. // Any function can be extended by the scale type
  9938. mergeTicksOptions: function() {
  9939. var ticks = this.options.ticks;
  9940. if (ticks.minor === false) {
  9941. ticks.minor = {
  9942. display: false
  9943. };
  9944. }
  9945. if (ticks.major === false) {
  9946. ticks.major = {
  9947. display: false
  9948. };
  9949. }
  9950. for (var key in ticks) {
  9951. if (key !== 'major' && key !== 'minor') {
  9952. if (typeof ticks.minor[key] === 'undefined') {
  9953. ticks.minor[key] = ticks[key];
  9954. }
  9955. if (typeof ticks.major[key] === 'undefined') {
  9956. ticks.major[key] = ticks[key];
  9957. }
  9958. }
  9959. }
  9960. },
  9961. beforeUpdate: function() {
  9962. helpers.callback(this.options.beforeUpdate, [this]);
  9963. },
  9964. update: function(maxWidth, maxHeight, margins) {
  9965. var me = this;
  9966. var i, ilen, labels, label, ticks, tick;
  9967. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  9968. me.beforeUpdate();
  9969. // Absorb the master measurements
  9970. me.maxWidth = maxWidth;
  9971. me.maxHeight = maxHeight;
  9972. me.margins = helpers.extend({
  9973. left: 0,
  9974. right: 0,
  9975. top: 0,
  9976. bottom: 0
  9977. }, margins);
  9978. me.longestTextCache = me.longestTextCache || {};
  9979. // Dimensions
  9980. me.beforeSetDimensions();
  9981. me.setDimensions();
  9982. me.afterSetDimensions();
  9983. // Data min/max
  9984. me.beforeDataLimits();
  9985. me.determineDataLimits();
  9986. me.afterDataLimits();
  9987. // Ticks - `this.ticks` is now DEPRECATED!
  9988. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  9989. // and must not be accessed directly from outside this class. `this.ticks` being
  9990. // around for long time and not marked as private, we can't change its structure
  9991. // without unexpected breaking changes. If you need to access the scale ticks,
  9992. // use scale.getTicks() instead.
  9993. me.beforeBuildTicks();
  9994. // New implementations should return an array of objects but for BACKWARD COMPAT,
  9995. // we still support no return (`this.ticks` internally set by calling this method).
  9996. ticks = me.buildTicks() || [];
  9997. me.afterBuildTicks();
  9998. me.beforeTickToLabelConversion();
  9999. // New implementations should return the formatted tick labels but for BACKWARD
  10000. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  10001. // this method and supposed to contain only string values).
  10002. labels = me.convertTicksToLabels(ticks) || me.ticks;
  10003. me.afterTickToLabelConversion();
  10004. me.ticks = labels; // BACKWARD COMPATIBILITY
  10005. // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change!
  10006. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  10007. for (i = 0, ilen = labels.length; i < ilen; ++i) {
  10008. label = labels[i];
  10009. tick = ticks[i];
  10010. if (!tick) {
  10011. ticks.push(tick = {
  10012. label: label,
  10013. major: false
  10014. });
  10015. } else {
  10016. tick.label = label;
  10017. }
  10018. }
  10019. me._ticks = ticks;
  10020. // Tick Rotation
  10021. me.beforeCalculateTickRotation();
  10022. me.calculateTickRotation();
  10023. me.afterCalculateTickRotation();
  10024. // Fit
  10025. me.beforeFit();
  10026. me.fit();
  10027. me.afterFit();
  10028. //
  10029. me.afterUpdate();
  10030. return me.minSize;
  10031. },
  10032. afterUpdate: function() {
  10033. helpers.callback(this.options.afterUpdate, [this]);
  10034. },
  10035. //
  10036. beforeSetDimensions: function() {
  10037. helpers.callback(this.options.beforeSetDimensions, [this]);
  10038. },
  10039. setDimensions: function() {
  10040. var me = this;
  10041. // Set the unconstrained dimension before label rotation
  10042. if (me.isHorizontal()) {
  10043. // Reset position before calculating rotation
  10044. me.width = me.maxWidth;
  10045. me.left = 0;
  10046. me.right = me.width;
  10047. } else {
  10048. me.height = me.maxHeight;
  10049. // Reset position before calculating rotation
  10050. me.top = 0;
  10051. me.bottom = me.height;
  10052. }
  10053. // Reset padding
  10054. me.paddingLeft = 0;
  10055. me.paddingTop = 0;
  10056. me.paddingRight = 0;
  10057. me.paddingBottom = 0;
  10058. },
  10059. afterSetDimensions: function() {
  10060. helpers.callback(this.options.afterSetDimensions, [this]);
  10061. },
  10062. // Data limits
  10063. beforeDataLimits: function() {
  10064. helpers.callback(this.options.beforeDataLimits, [this]);
  10065. },
  10066. determineDataLimits: helpers.noop,
  10067. afterDataLimits: function() {
  10068. helpers.callback(this.options.afterDataLimits, [this]);
  10069. },
  10070. //
  10071. beforeBuildTicks: function() {
  10072. helpers.callback(this.options.beforeBuildTicks, [this]);
  10073. },
  10074. buildTicks: helpers.noop,
  10075. afterBuildTicks: function() {
  10076. helpers.callback(this.options.afterBuildTicks, [this]);
  10077. },
  10078. beforeTickToLabelConversion: function() {
  10079. helpers.callback(this.options.beforeTickToLabelConversion, [this]);
  10080. },
  10081. convertTicksToLabels: function() {
  10082. var me = this;
  10083. // Convert ticks to strings
  10084. var tickOpts = me.options.ticks;
  10085. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  10086. },
  10087. afterTickToLabelConversion: function() {
  10088. helpers.callback(this.options.afterTickToLabelConversion, [this]);
  10089. },
  10090. //
  10091. beforeCalculateTickRotation: function() {
  10092. helpers.callback(this.options.beforeCalculateTickRotation, [this]);
  10093. },
  10094. calculateTickRotation: function() {
  10095. var me = this;
  10096. var context = me.ctx;
  10097. var tickOpts = me.options.ticks;
  10098. var labels = labelsFromTicks(me._ticks);
  10099. // Get the width of each grid by calculating the difference
  10100. // between x offsets between 0 and 1.
  10101. var tickFont = parseFontOptions(tickOpts);
  10102. context.font = tickFont.font;
  10103. var labelRotation = tickOpts.minRotation || 0;
  10104. if (labels.length && me.options.display && me.isHorizontal()) {
  10105. var originalLabelWidth = helpers.longestText(context, tickFont.font, labels, me.longestTextCache);
  10106. var labelWidth = originalLabelWidth;
  10107. var cosRotation, sinRotation;
  10108. // Allow 3 pixels x2 padding either side for label readability
  10109. var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
  10110. // Max label rotation can be set or default to 90 - also act as a loop counter
  10111. while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {
  10112. var angleRadians = helpers.toRadians(labelRotation);
  10113. cosRotation = Math.cos(angleRadians);
  10114. sinRotation = Math.sin(angleRadians);
  10115. if (sinRotation * originalLabelWidth > me.maxHeight) {
  10116. // go back one step
  10117. labelRotation--;
  10118. break;
  10119. }
  10120. labelRotation++;
  10121. labelWidth = cosRotation * originalLabelWidth;
  10122. }
  10123. }
  10124. me.labelRotation = labelRotation;
  10125. },
  10126. afterCalculateTickRotation: function() {
  10127. helpers.callback(this.options.afterCalculateTickRotation, [this]);
  10128. },
  10129. //
  10130. beforeFit: function() {
  10131. helpers.callback(this.options.beforeFit, [this]);
  10132. },
  10133. fit: function() {
  10134. var me = this;
  10135. // Reset
  10136. var minSize = me.minSize = {
  10137. width: 0,
  10138. height: 0
  10139. };
  10140. var labels = labelsFromTicks(me._ticks);
  10141. var opts = me.options;
  10142. var tickOpts = opts.ticks;
  10143. var scaleLabelOpts = opts.scaleLabel;
  10144. var gridLineOpts = opts.gridLines;
  10145. var display = opts.display;
  10146. var isHorizontal = me.isHorizontal();
  10147. var tickFont = parseFontOptions(tickOpts);
  10148. var tickMarkLength = opts.gridLines.tickMarkLength;
  10149. // Width
  10150. if (isHorizontal) {
  10151. // subtract the margins to line up with the chartArea if we are a full width scale
  10152. minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
  10153. } else {
  10154. minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
  10155. }
  10156. // height
  10157. if (isHorizontal) {
  10158. minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
  10159. } else {
  10160. minSize.height = me.maxHeight; // fill all the height
  10161. }
  10162. // Are we showing a title for the scale?
  10163. if (scaleLabelOpts.display && display) {
  10164. var scaleLabelLineHeight = parseLineHeight(scaleLabelOpts);
  10165. var scaleLabelPadding = helpers.options.toPadding(scaleLabelOpts.padding);
  10166. var deltaHeight = scaleLabelLineHeight + scaleLabelPadding.height;
  10167. if (isHorizontal) {
  10168. minSize.height += deltaHeight;
  10169. } else {
  10170. minSize.width += deltaHeight;
  10171. }
  10172. }
  10173. // Don't bother fitting the ticks if we are not showing them
  10174. if (tickOpts.display && display) {
  10175. var largestTextWidth = helpers.longestText(me.ctx, tickFont.font, labels, me.longestTextCache);
  10176. var tallestLabelHeightInLines = helpers.numberOfLabelLines(labels);
  10177. var lineSpace = tickFont.size * 0.5;
  10178. var tickPadding = me.options.ticks.padding;
  10179. if (isHorizontal) {
  10180. // A horizontal axis is more constrained by the height.
  10181. me.longestLabelWidth = largestTextWidth;
  10182. var angleRadians = helpers.toRadians(me.labelRotation);
  10183. var cosRotation = Math.cos(angleRadians);
  10184. var sinRotation = Math.sin(angleRadians);
  10185. // TODO - improve this calculation
  10186. var labelHeight = (sinRotation * largestTextWidth)
  10187. + (tickFont.size * tallestLabelHeightInLines)
  10188. + (lineSpace * (tallestLabelHeightInLines - 1))
  10189. + lineSpace; // padding
  10190. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  10191. me.ctx.font = tickFont.font;
  10192. var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.font);
  10193. var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.font);
  10194. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  10195. // which means that the right padding is dominated by the font height
  10196. if (me.labelRotation !== 0) {
  10197. me.paddingLeft = opts.position === 'bottom' ? (cosRotation * firstLabelWidth) + 3 : (cosRotation * lineSpace) + 3; // add 3 px to move away from canvas edges
  10198. me.paddingRight = opts.position === 'bottom' ? (cosRotation * lineSpace) + 3 : (cosRotation * lastLabelWidth) + 3;
  10199. } else {
  10200. me.paddingLeft = firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges
  10201. me.paddingRight = lastLabelWidth / 2 + 3;
  10202. }
  10203. } else {
  10204. // A vertical axis is more constrained by the width. Labels are the
  10205. // dominant factor here, so get that length first and account for padding
  10206. if (tickOpts.mirror) {
  10207. largestTextWidth = 0;
  10208. } else {
  10209. // use lineSpace for consistency with horizontal axis
  10210. // tickPadding is not implemented for horizontal
  10211. largestTextWidth += tickPadding + lineSpace;
  10212. }
  10213. minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth);
  10214. me.paddingTop = tickFont.size / 2;
  10215. me.paddingBottom = tickFont.size / 2;
  10216. }
  10217. }
  10218. me.handleMargins();
  10219. me.width = minSize.width;
  10220. me.height = minSize.height;
  10221. },
  10222. /**
  10223. * Handle margins and padding interactions
  10224. * @private
  10225. */
  10226. handleMargins: function() {
  10227. var me = this;
  10228. if (me.margins) {
  10229. me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
  10230. me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
  10231. me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
  10232. me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
  10233. }
  10234. },
  10235. afterFit: function() {
  10236. helpers.callback(this.options.afterFit, [this]);
  10237. },
  10238. // Shared Methods
  10239. isHorizontal: function() {
  10240. return this.options.position === 'top' || this.options.position === 'bottom';
  10241. },
  10242. isFullWidth: function() {
  10243. return (this.options.fullWidth);
  10244. },
  10245. // 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
  10246. getRightValue: function(rawValue) {
  10247. // Null and undefined values first
  10248. if (helpers.isNullOrUndef(rawValue)) {
  10249. return NaN;
  10250. }
  10251. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  10252. if (typeof rawValue === 'number' && !isFinite(rawValue)) {
  10253. return NaN;
  10254. }
  10255. // If it is in fact an object, dive in one more level
  10256. if (rawValue) {
  10257. if (this.isHorizontal()) {
  10258. if (rawValue.x !== undefined) {
  10259. return this.getRightValue(rawValue.x);
  10260. }
  10261. } else if (rawValue.y !== undefined) {
  10262. return this.getRightValue(rawValue.y);
  10263. }
  10264. }
  10265. // Value is good, return it
  10266. return rawValue;
  10267. },
  10268. /**
  10269. * Used to get the value to display in the tooltip for the data at the given index
  10270. * @param index
  10271. * @param datasetIndex
  10272. */
  10273. getLabelForIndex: helpers.noop,
  10274. /**
  10275. * Returns the location of the given data point. Value can either be an index or a numerical value
  10276. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10277. * @param value
  10278. * @param index
  10279. * @param datasetIndex
  10280. */
  10281. getPixelForValue: helpers.noop,
  10282. /**
  10283. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  10284. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10285. * @param pixel
  10286. */
  10287. getValueForPixel: helpers.noop,
  10288. /**
  10289. * Returns the location of the tick at the given index
  10290. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10291. */
  10292. getPixelForTick: function(index) {
  10293. var me = this;
  10294. var offset = me.options.offset;
  10295. if (me.isHorizontal()) {
  10296. var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
  10297. var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
  10298. var pixel = (tickWidth * index) + me.paddingLeft;
  10299. if (offset) {
  10300. pixel += tickWidth / 2;
  10301. }
  10302. var finalVal = me.left + Math.round(pixel);
  10303. finalVal += me.isFullWidth() ? me.margins.left : 0;
  10304. return finalVal;
  10305. }
  10306. var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
  10307. return me.top + (index * (innerHeight / (me._ticks.length - 1)));
  10308. },
  10309. /**
  10310. * Utility for getting the pixel location of a percentage of scale
  10311. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10312. */
  10313. getPixelForDecimal: function(decimal) {
  10314. var me = this;
  10315. if (me.isHorizontal()) {
  10316. var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
  10317. var valueOffset = (innerWidth * decimal) + me.paddingLeft;
  10318. var finalVal = me.left + Math.round(valueOffset);
  10319. finalVal += me.isFullWidth() ? me.margins.left : 0;
  10320. return finalVal;
  10321. }
  10322. return me.top + (decimal * me.height);
  10323. },
  10324. /**
  10325. * Returns the pixel for the minimum chart value
  10326. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10327. */
  10328. getBasePixel: function() {
  10329. return this.getPixelForValue(this.getBaseValue());
  10330. },
  10331. getBaseValue: function() {
  10332. var me = this;
  10333. var min = me.min;
  10334. var max = me.max;
  10335. return me.beginAtZero ? 0 :
  10336. min < 0 && max < 0 ? max :
  10337. min > 0 && max > 0 ? min :
  10338. 0;
  10339. },
  10340. /**
  10341. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  10342. * @private
  10343. */
  10344. _autoSkip: function(ticks) {
  10345. var skipRatio;
  10346. var me = this;
  10347. var isHorizontal = me.isHorizontal();
  10348. var optionTicks = me.options.ticks.minor;
  10349. var tickCount = ticks.length;
  10350. var labelRotationRadians = helpers.toRadians(me.labelRotation);
  10351. var cosRotation = Math.cos(labelRotationRadians);
  10352. var longestRotatedLabel = me.longestLabelWidth * cosRotation;
  10353. var result = [];
  10354. var i, tick, shouldSkip;
  10355. // figure out the maximum number of gridlines to show
  10356. var maxTicks;
  10357. if (optionTicks.maxTicksLimit) {
  10358. maxTicks = optionTicks.maxTicksLimit;
  10359. }
  10360. if (isHorizontal) {
  10361. skipRatio = false;
  10362. if ((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount > (me.width - (me.paddingLeft + me.paddingRight))) {
  10363. skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount) / (me.width - (me.paddingLeft + me.paddingRight)));
  10364. }
  10365. // if they defined a max number of optionTicks,
  10366. // increase skipRatio until that number is met
  10367. if (maxTicks && tickCount > maxTicks) {
  10368. skipRatio = Math.max(skipRatio, Math.floor(tickCount / maxTicks));
  10369. }
  10370. }
  10371. for (i = 0; i < tickCount; i++) {
  10372. tick = ticks[i];
  10373. // Since we always show the last tick,we need may need to hide the last shown one before
  10374. shouldSkip = (skipRatio > 1 && i % skipRatio > 0) || (i % skipRatio === 0 && i + skipRatio >= tickCount);
  10375. if (shouldSkip && i !== tickCount - 1) {
  10376. // leave tick in place but make sure it's not displayed (#4635)
  10377. delete tick.label;
  10378. }
  10379. result.push(tick);
  10380. }
  10381. return result;
  10382. },
  10383. // Actually draw the scale on the canvas
  10384. // @param {rectangle} chartArea : the area of the chart to draw full grid lines on
  10385. draw: function(chartArea) {
  10386. var me = this;
  10387. var options = me.options;
  10388. if (!options.display) {
  10389. return;
  10390. }
  10391. var context = me.ctx;
  10392. var globalDefaults = defaults.global;
  10393. var optionTicks = options.ticks.minor;
  10394. var optionMajorTicks = options.ticks.major || optionTicks;
  10395. var gridLines = options.gridLines;
  10396. var scaleLabel = options.scaleLabel;
  10397. var isRotated = me.labelRotation !== 0;
  10398. var isHorizontal = me.isHorizontal();
  10399. var ticks = optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks();
  10400. var tickFontColor = helpers.valueOrDefault(optionTicks.fontColor, globalDefaults.defaultFontColor);
  10401. var tickFont = parseFontOptions(optionTicks);
  10402. var majorTickFontColor = helpers.valueOrDefault(optionMajorTicks.fontColor, globalDefaults.defaultFontColor);
  10403. var majorTickFont = parseFontOptions(optionMajorTicks);
  10404. var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;
  10405. var scaleLabelFontColor = helpers.valueOrDefault(scaleLabel.fontColor, globalDefaults.defaultFontColor);
  10406. var scaleLabelFont = parseFontOptions(scaleLabel);
  10407. var scaleLabelPadding = helpers.options.toPadding(scaleLabel.padding);
  10408. var labelRotationRadians = helpers.toRadians(me.labelRotation);
  10409. var itemsToDraw = [];
  10410. var axisWidth = me.options.gridLines.lineWidth;
  10411. var xTickStart = options.position === 'right' ? me.left : me.right - axisWidth - tl;
  10412. var xTickEnd = options.position === 'right' ? me.left + tl : me.right;
  10413. var yTickStart = options.position === 'bottom' ? me.top + axisWidth : me.bottom - tl - axisWidth;
  10414. var yTickEnd = options.position === 'bottom' ? me.top + axisWidth + tl : me.bottom + axisWidth;
  10415. helpers.each(ticks, function(tick, index) {
  10416. // autoskipper skipped this tick (#4635)
  10417. if (helpers.isNullOrUndef(tick.label)) {
  10418. return;
  10419. }
  10420. var label = tick.label;
  10421. var lineWidth, lineColor, borderDash, borderDashOffset;
  10422. if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) {
  10423. // Draw the first index specially
  10424. lineWidth = gridLines.zeroLineWidth;
  10425. lineColor = gridLines.zeroLineColor;
  10426. borderDash = gridLines.zeroLineBorderDash;
  10427. borderDashOffset = gridLines.zeroLineBorderDashOffset;
  10428. } else {
  10429. lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, index);
  10430. lineColor = helpers.valueAtIndexOrDefault(gridLines.color, index);
  10431. borderDash = helpers.valueOrDefault(gridLines.borderDash, globalDefaults.borderDash);
  10432. borderDashOffset = helpers.valueOrDefault(gridLines.borderDashOffset, globalDefaults.borderDashOffset);
  10433. }
  10434. // Common properties
  10435. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY;
  10436. var textAlign = 'middle';
  10437. var textBaseline = 'middle';
  10438. var tickPadding = optionTicks.padding;
  10439. if (isHorizontal) {
  10440. var labelYOffset = tl + tickPadding;
  10441. if (options.position === 'bottom') {
  10442. // bottom
  10443. textBaseline = !isRotated ? 'top' : 'middle';
  10444. textAlign = !isRotated ? 'center' : 'right';
  10445. labelY = me.top + labelYOffset;
  10446. } else {
  10447. // top
  10448. textBaseline = !isRotated ? 'bottom' : 'middle';
  10449. textAlign = !isRotated ? 'center' : 'left';
  10450. labelY = me.bottom - labelYOffset;
  10451. }
  10452. var xLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);
  10453. if (xLineValue < me.left) {
  10454. lineColor = 'rgba(0,0,0,0)';
  10455. }
  10456. xLineValue += helpers.aliasPixel(lineWidth);
  10457. labelX = me.getPixelForTick(index) + optionTicks.labelOffset; // x values for optionTicks (need to consider offsetLabel option)
  10458. tx1 = tx2 = x1 = x2 = xLineValue;
  10459. ty1 = yTickStart;
  10460. ty2 = yTickEnd;
  10461. y1 = chartArea.top;
  10462. y2 = chartArea.bottom + axisWidth;
  10463. } else {
  10464. var isLeft = options.position === 'left';
  10465. var labelXOffset;
  10466. if (optionTicks.mirror) {
  10467. textAlign = isLeft ? 'left' : 'right';
  10468. labelXOffset = tickPadding;
  10469. } else {
  10470. textAlign = isLeft ? 'right' : 'left';
  10471. labelXOffset = tl + tickPadding;
  10472. }
  10473. labelX = isLeft ? me.right - labelXOffset : me.left + labelXOffset;
  10474. var yLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1);
  10475. if (yLineValue < me.top) {
  10476. lineColor = 'rgba(0,0,0,0)';
  10477. }
  10478. yLineValue += helpers.aliasPixel(lineWidth);
  10479. labelY = me.getPixelForTick(index) + optionTicks.labelOffset;
  10480. tx1 = xTickStart;
  10481. tx2 = xTickEnd;
  10482. x1 = chartArea.left;
  10483. x2 = chartArea.right + axisWidth;
  10484. ty1 = ty2 = y1 = y2 = yLineValue;
  10485. }
  10486. itemsToDraw.push({
  10487. tx1: tx1,
  10488. ty1: ty1,
  10489. tx2: tx2,
  10490. ty2: ty2,
  10491. x1: x1,
  10492. y1: y1,
  10493. x2: x2,
  10494. y2: y2,
  10495. labelX: labelX,
  10496. labelY: labelY,
  10497. glWidth: lineWidth,
  10498. glColor: lineColor,
  10499. glBorderDash: borderDash,
  10500. glBorderDashOffset: borderDashOffset,
  10501. rotation: -1 * labelRotationRadians,
  10502. label: label,
  10503. major: tick.major,
  10504. textBaseline: textBaseline,
  10505. textAlign: textAlign
  10506. });
  10507. });
  10508. // Draw all of the tick labels, tick marks, and grid lines at the correct places
  10509. helpers.each(itemsToDraw, function(itemToDraw) {
  10510. if (gridLines.display) {
  10511. context.save();
  10512. context.lineWidth = itemToDraw.glWidth;
  10513. context.strokeStyle = itemToDraw.glColor;
  10514. if (context.setLineDash) {
  10515. context.setLineDash(itemToDraw.glBorderDash);
  10516. context.lineDashOffset = itemToDraw.glBorderDashOffset;
  10517. }
  10518. context.beginPath();
  10519. if (gridLines.drawTicks) {
  10520. context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
  10521. context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
  10522. }
  10523. if (gridLines.drawOnChartArea) {
  10524. context.moveTo(itemToDraw.x1, itemToDraw.y1);
  10525. context.lineTo(itemToDraw.x2, itemToDraw.y2);
  10526. }
  10527. context.stroke();
  10528. context.restore();
  10529. }
  10530. if (optionTicks.display) {
  10531. // Make sure we draw text in the correct color and font
  10532. context.save();
  10533. context.translate(itemToDraw.labelX, itemToDraw.labelY);
  10534. context.rotate(itemToDraw.rotation);
  10535. context.font = itemToDraw.major ? majorTickFont.font : tickFont.font;
  10536. context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;
  10537. context.textBaseline = itemToDraw.textBaseline;
  10538. context.textAlign = itemToDraw.textAlign;
  10539. var label = itemToDraw.label;
  10540. if (helpers.isArray(label)) {
  10541. var lineCount = label.length;
  10542. var lineHeight = tickFont.size * 1.5;
  10543. var y = me.isHorizontal() ? 0 : -lineHeight * (lineCount - 1) / 2;
  10544. for (var i = 0; i < lineCount; ++i) {
  10545. // We just make sure the multiline element is a string here..
  10546. context.fillText('' + label[i], 0, y);
  10547. // apply same lineSpacing as calculated @ L#320
  10548. y += lineHeight;
  10549. }
  10550. } else {
  10551. context.fillText(label, 0, 0);
  10552. }
  10553. context.restore();
  10554. }
  10555. });
  10556. if (scaleLabel.display) {
  10557. // Draw the scale label
  10558. var scaleLabelX;
  10559. var scaleLabelY;
  10560. var rotation = 0;
  10561. var halfLineHeight = parseLineHeight(scaleLabel) / 2;
  10562. if (isHorizontal) {
  10563. scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
  10564. scaleLabelY = options.position === 'bottom'
  10565. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  10566. : me.top + halfLineHeight + scaleLabelPadding.top;
  10567. } else {
  10568. var isLeft = options.position === 'left';
  10569. scaleLabelX = isLeft
  10570. ? me.left + halfLineHeight + scaleLabelPadding.top
  10571. : me.right - halfLineHeight - scaleLabelPadding.top;
  10572. scaleLabelY = me.top + ((me.bottom - me.top) / 2);
  10573. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  10574. }
  10575. context.save();
  10576. context.translate(scaleLabelX, scaleLabelY);
  10577. context.rotate(rotation);
  10578. context.textAlign = 'center';
  10579. context.textBaseline = 'middle';
  10580. context.fillStyle = scaleLabelFontColor; // render in correct colour
  10581. context.font = scaleLabelFont.font;
  10582. context.fillText(scaleLabel.labelString, 0, 0);
  10583. context.restore();
  10584. }
  10585. if (gridLines.drawBorder) {
  10586. // Draw the line at the edge of the axis
  10587. context.lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, 0);
  10588. context.strokeStyle = helpers.valueAtIndexOrDefault(gridLines.color, 0);
  10589. var x1 = me.left;
  10590. var x2 = me.right + axisWidth;
  10591. var y1 = me.top;
  10592. var y2 = me.bottom + axisWidth;
  10593. var aliasPixel = helpers.aliasPixel(context.lineWidth);
  10594. if (isHorizontal) {
  10595. y1 = y2 = options.position === 'top' ? me.bottom : me.top;
  10596. y1 += aliasPixel;
  10597. y2 += aliasPixel;
  10598. } else {
  10599. x1 = x2 = options.position === 'left' ? me.right : me.left;
  10600. x1 += aliasPixel;
  10601. x2 += aliasPixel;
  10602. }
  10603. context.beginPath();
  10604. context.moveTo(x1, y1);
  10605. context.lineTo(x2, y2);
  10606. context.stroke();
  10607. }
  10608. }
  10609. });
  10610. },{"26":26,"27":27,"35":35,"46":46}],34:[function(require,module,exports){
  10611. 'use strict';
  10612. var defaults = require(26);
  10613. var helpers = require(46);
  10614. var layouts = require(31);
  10615. module.exports = {
  10616. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  10617. // use the new chart options to grab the correct scale
  10618. constructors: {},
  10619. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  10620. // old browsers
  10621. // Scale config defaults
  10622. defaults: {},
  10623. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  10624. this.constructors[type] = scaleConstructor;
  10625. this.defaults[type] = helpers.clone(scaleDefaults);
  10626. },
  10627. getScaleConstructor: function(type) {
  10628. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  10629. },
  10630. getScaleDefaults: function(type) {
  10631. // Return the scale defaults merged with the global settings so that we always use the latest ones
  10632. return this.defaults.hasOwnProperty(type) ? helpers.merge({}, [defaults.scale, this.defaults[type]]) : {};
  10633. },
  10634. updateScaleDefaults: function(type, additions) {
  10635. var me = this;
  10636. if (me.defaults.hasOwnProperty(type)) {
  10637. me.defaults[type] = helpers.extend(me.defaults[type], additions);
  10638. }
  10639. },
  10640. addScalesToLayout: function(chart) {
  10641. // Adds each scale to the chart.boxes array to be sized accordingly
  10642. helpers.each(chart.scales, function(scale) {
  10643. // Set ILayoutItem parameters for backwards compatibility
  10644. scale.fullWidth = scale.options.fullWidth;
  10645. scale.position = scale.options.position;
  10646. scale.weight = scale.options.weight;
  10647. layouts.addBox(chart, scale);
  10648. });
  10649. }
  10650. };
  10651. },{"26":26,"31":31,"46":46}],35:[function(require,module,exports){
  10652. 'use strict';
  10653. var helpers = require(46);
  10654. /**
  10655. * Namespace to hold static tick generation functions
  10656. * @namespace Chart.Ticks
  10657. */
  10658. module.exports = {
  10659. /**
  10660. * Namespace to hold formatters for different types of ticks
  10661. * @namespace Chart.Ticks.formatters
  10662. */
  10663. formatters: {
  10664. /**
  10665. * Formatter for value labels
  10666. * @method Chart.Ticks.formatters.values
  10667. * @param value the value to display
  10668. * @return {String|Array} the label to display
  10669. */
  10670. values: function(value) {
  10671. return helpers.isArray(value) ? value : '' + value;
  10672. },
  10673. /**
  10674. * Formatter for linear numeric ticks
  10675. * @method Chart.Ticks.formatters.linear
  10676. * @param tickValue {Number} the value to be formatted
  10677. * @param index {Number} the position of the tickValue parameter in the ticks array
  10678. * @param ticks {Array<Number>} the list of ticks being converted
  10679. * @return {String} string representation of the tickValue parameter
  10680. */
  10681. linear: function(tickValue, index, ticks) {
  10682. // If we have lots of ticks, don't use the ones
  10683. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  10684. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  10685. if (Math.abs(delta) > 1) {
  10686. if (tickValue !== Math.floor(tickValue)) {
  10687. // not an integer
  10688. delta = tickValue - Math.floor(tickValue);
  10689. }
  10690. }
  10691. var logDelta = helpers.log10(Math.abs(delta));
  10692. var tickString = '';
  10693. if (tickValue !== 0) {
  10694. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  10695. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  10696. var logTick = helpers.log10(Math.abs(tickValue));
  10697. tickString = tickValue.toExponential(Math.floor(logTick) - Math.floor(logDelta));
  10698. } else {
  10699. var numDecimal = -1 * Math.floor(logDelta);
  10700. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  10701. tickString = tickValue.toFixed(numDecimal);
  10702. }
  10703. } else {
  10704. tickString = '0'; // never show decimal places for 0
  10705. }
  10706. return tickString;
  10707. },
  10708. logarithmic: function(tickValue, index, ticks) {
  10709. var remain = tickValue / (Math.pow(10, Math.floor(helpers.log10(tickValue))));
  10710. if (tickValue === 0) {
  10711. return '0';
  10712. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  10713. return tickValue.toExponential();
  10714. }
  10715. return '';
  10716. }
  10717. }
  10718. };
  10719. },{"46":46}],36:[function(require,module,exports){
  10720. 'use strict';
  10721. var defaults = require(26);
  10722. var Element = require(27);
  10723. var helpers = require(46);
  10724. defaults._set('global', {
  10725. tooltips: {
  10726. enabled: true,
  10727. custom: null,
  10728. mode: 'nearest',
  10729. position: 'average',
  10730. intersect: true,
  10731. backgroundColor: 'rgba(0,0,0,0.8)',
  10732. titleFontStyle: 'bold',
  10733. titleSpacing: 2,
  10734. titleMarginBottom: 6,
  10735. titleFontColor: '#fff',
  10736. titleAlign: 'left',
  10737. bodySpacing: 2,
  10738. bodyFontColor: '#fff',
  10739. bodyAlign: 'left',
  10740. footerFontStyle: 'bold',
  10741. footerSpacing: 2,
  10742. footerMarginTop: 6,
  10743. footerFontColor: '#fff',
  10744. footerAlign: 'left',
  10745. yPadding: 6,
  10746. xPadding: 6,
  10747. caretPadding: 2,
  10748. caretSize: 5,
  10749. cornerRadius: 6,
  10750. multiKeyBackground: '#fff',
  10751. displayColors: true,
  10752. borderColor: 'rgba(0,0,0,0)',
  10753. borderWidth: 0,
  10754. callbacks: {
  10755. // Args are: (tooltipItems, data)
  10756. beforeTitle: helpers.noop,
  10757. title: function(tooltipItems, data) {
  10758. // Pick first xLabel for now
  10759. var title = '';
  10760. var labels = data.labels;
  10761. var labelCount = labels ? labels.length : 0;
  10762. if (tooltipItems.length > 0) {
  10763. var item = tooltipItems[0];
  10764. if (item.xLabel) {
  10765. title = item.xLabel;
  10766. } else if (labelCount > 0 && item.index < labelCount) {
  10767. title = labels[item.index];
  10768. }
  10769. }
  10770. return title;
  10771. },
  10772. afterTitle: helpers.noop,
  10773. // Args are: (tooltipItems, data)
  10774. beforeBody: helpers.noop,
  10775. // Args are: (tooltipItem, data)
  10776. beforeLabel: helpers.noop,
  10777. label: function(tooltipItem, data) {
  10778. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  10779. if (label) {
  10780. label += ': ';
  10781. }
  10782. label += tooltipItem.yLabel;
  10783. return label;
  10784. },
  10785. labelColor: function(tooltipItem, chart) {
  10786. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  10787. var activeElement = meta.data[tooltipItem.index];
  10788. var view = activeElement._view;
  10789. return {
  10790. borderColor: view.borderColor,
  10791. backgroundColor: view.backgroundColor
  10792. };
  10793. },
  10794. labelTextColor: function() {
  10795. return this._options.bodyFontColor;
  10796. },
  10797. afterLabel: helpers.noop,
  10798. // Args are: (tooltipItems, data)
  10799. afterBody: helpers.noop,
  10800. // Args are: (tooltipItems, data)
  10801. beforeFooter: helpers.noop,
  10802. footer: helpers.noop,
  10803. afterFooter: helpers.noop
  10804. }
  10805. }
  10806. });
  10807. var positioners = {
  10808. /**
  10809. * Average mode places the tooltip at the average position of the elements shown
  10810. * @function Chart.Tooltip.positioners.average
  10811. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  10812. * @returns {Point} tooltip position
  10813. */
  10814. average: function(elements) {
  10815. if (!elements.length) {
  10816. return false;
  10817. }
  10818. var i, len;
  10819. var x = 0;
  10820. var y = 0;
  10821. var count = 0;
  10822. for (i = 0, len = elements.length; i < len; ++i) {
  10823. var el = elements[i];
  10824. if (el && el.hasValue()) {
  10825. var pos = el.tooltipPosition();
  10826. x += pos.x;
  10827. y += pos.y;
  10828. ++count;
  10829. }
  10830. }
  10831. return {
  10832. x: Math.round(x / count),
  10833. y: Math.round(y / count)
  10834. };
  10835. },
  10836. /**
  10837. * Gets the tooltip position nearest of the item nearest to the event position
  10838. * @function Chart.Tooltip.positioners.nearest
  10839. * @param elements {Chart.Element[]} the tooltip elements
  10840. * @param eventPosition {Point} the position of the event in canvas coordinates
  10841. * @returns {Point} the tooltip position
  10842. */
  10843. nearest: function(elements, eventPosition) {
  10844. var x = eventPosition.x;
  10845. var y = eventPosition.y;
  10846. var minDistance = Number.POSITIVE_INFINITY;
  10847. var i, len, nearestElement;
  10848. for (i = 0, len = elements.length; i < len; ++i) {
  10849. var el = elements[i];
  10850. if (el && el.hasValue()) {
  10851. var center = el.getCenterPoint();
  10852. var d = helpers.distanceBetweenPoints(eventPosition, center);
  10853. if (d < minDistance) {
  10854. minDistance = d;
  10855. nearestElement = el;
  10856. }
  10857. }
  10858. }
  10859. if (nearestElement) {
  10860. var tp = nearestElement.tooltipPosition();
  10861. x = tp.x;
  10862. y = tp.y;
  10863. }
  10864. return {
  10865. x: x,
  10866. y: y
  10867. };
  10868. }
  10869. };
  10870. /**
  10871. * Helper method to merge the opacity into a color
  10872. */
  10873. function mergeOpacity(colorString, opacity) {
  10874. var color = helpers.color(colorString);
  10875. return color.alpha(opacity * color.alpha()).rgbaString();
  10876. }
  10877. // Helper to push or concat based on if the 2nd parameter is an array or not
  10878. function pushOrConcat(base, toPush) {
  10879. if (toPush) {
  10880. if (helpers.isArray(toPush)) {
  10881. // base = base.concat(toPush);
  10882. Array.prototype.push.apply(base, toPush);
  10883. } else {
  10884. base.push(toPush);
  10885. }
  10886. }
  10887. return base;
  10888. }
  10889. /**
  10890. * Returns array of strings split by newline
  10891. * @param {String} value - The value to split by newline.
  10892. * @returns {Array} value if newline present - Returned from String split() method
  10893. * @function
  10894. */
  10895. function splitNewlines(str) {
  10896. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  10897. return str.split('\n');
  10898. }
  10899. return str;
  10900. }
  10901. // Private helper to create a tooltip item model
  10902. // @param element : the chart element (point, arc, bar) to create the tooltip item for
  10903. // @return : new tooltip item
  10904. function createTooltipItem(element) {
  10905. var xScale = element._xScale;
  10906. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  10907. var index = element._index;
  10908. var datasetIndex = element._datasetIndex;
  10909. return {
  10910. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  10911. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  10912. index: index,
  10913. datasetIndex: datasetIndex,
  10914. x: element._model.x,
  10915. y: element._model.y
  10916. };
  10917. }
  10918. /**
  10919. * Helper to get the reset model for the tooltip
  10920. * @param tooltipOpts {Object} the tooltip options
  10921. */
  10922. function getBaseModel(tooltipOpts) {
  10923. var globalDefaults = defaults.global;
  10924. var valueOrDefault = helpers.valueOrDefault;
  10925. return {
  10926. // Positioning
  10927. xPadding: tooltipOpts.xPadding,
  10928. yPadding: tooltipOpts.yPadding,
  10929. xAlign: tooltipOpts.xAlign,
  10930. yAlign: tooltipOpts.yAlign,
  10931. // Body
  10932. bodyFontColor: tooltipOpts.bodyFontColor,
  10933. _bodyFontFamily: valueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  10934. _bodyFontStyle: valueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  10935. _bodyAlign: tooltipOpts.bodyAlign,
  10936. bodyFontSize: valueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  10937. bodySpacing: tooltipOpts.bodySpacing,
  10938. // Title
  10939. titleFontColor: tooltipOpts.titleFontColor,
  10940. _titleFontFamily: valueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  10941. _titleFontStyle: valueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  10942. titleFontSize: valueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  10943. _titleAlign: tooltipOpts.titleAlign,
  10944. titleSpacing: tooltipOpts.titleSpacing,
  10945. titleMarginBottom: tooltipOpts.titleMarginBottom,
  10946. // Footer
  10947. footerFontColor: tooltipOpts.footerFontColor,
  10948. _footerFontFamily: valueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  10949. _footerFontStyle: valueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  10950. footerFontSize: valueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  10951. _footerAlign: tooltipOpts.footerAlign,
  10952. footerSpacing: tooltipOpts.footerSpacing,
  10953. footerMarginTop: tooltipOpts.footerMarginTop,
  10954. // Appearance
  10955. caretSize: tooltipOpts.caretSize,
  10956. cornerRadius: tooltipOpts.cornerRadius,
  10957. backgroundColor: tooltipOpts.backgroundColor,
  10958. opacity: 0,
  10959. legendColorBackground: tooltipOpts.multiKeyBackground,
  10960. displayColors: tooltipOpts.displayColors,
  10961. borderColor: tooltipOpts.borderColor,
  10962. borderWidth: tooltipOpts.borderWidth
  10963. };
  10964. }
  10965. /**
  10966. * Get the size of the tooltip
  10967. */
  10968. function getTooltipSize(tooltip, model) {
  10969. var ctx = tooltip._chart.ctx;
  10970. var height = model.yPadding * 2; // Tooltip Padding
  10971. var width = 0;
  10972. // Count of all lines in the body
  10973. var body = model.body;
  10974. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  10975. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  10976. }, 0);
  10977. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  10978. var titleLineCount = model.title.length;
  10979. var footerLineCount = model.footer.length;
  10980. var titleFontSize = model.titleFontSize;
  10981. var bodyFontSize = model.bodyFontSize;
  10982. var footerFontSize = model.footerFontSize;
  10983. height += titleLineCount * titleFontSize; // Title Lines
  10984. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  10985. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  10986. height += combinedBodyLength * bodyFontSize; // Body Lines
  10987. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  10988. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  10989. height += footerLineCount * (footerFontSize); // Footer Lines
  10990. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  10991. // Title width
  10992. var widthPadding = 0;
  10993. var maxLineWidth = function(line) {
  10994. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  10995. };
  10996. ctx.font = helpers.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  10997. helpers.each(model.title, maxLineWidth);
  10998. // Body width
  10999. ctx.font = helpers.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  11000. helpers.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  11001. // Body lines may include some extra width due to the color box
  11002. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  11003. helpers.each(body, function(bodyItem) {
  11004. helpers.each(bodyItem.before, maxLineWidth);
  11005. helpers.each(bodyItem.lines, maxLineWidth);
  11006. helpers.each(bodyItem.after, maxLineWidth);
  11007. });
  11008. // Reset back to 0
  11009. widthPadding = 0;
  11010. // Footer width
  11011. ctx.font = helpers.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  11012. helpers.each(model.footer, maxLineWidth);
  11013. // Add padding
  11014. width += 2 * model.xPadding;
  11015. return {
  11016. width: width,
  11017. height: height
  11018. };
  11019. }
  11020. /**
  11021. * Helper to get the alignment of a tooltip given the size
  11022. */
  11023. function determineAlignment(tooltip, size) {
  11024. var model = tooltip._model;
  11025. var chart = tooltip._chart;
  11026. var chartArea = tooltip._chart.chartArea;
  11027. var xAlign = 'center';
  11028. var yAlign = 'center';
  11029. if (model.y < size.height) {
  11030. yAlign = 'top';
  11031. } else if (model.y > (chart.height - size.height)) {
  11032. yAlign = 'bottom';
  11033. }
  11034. var lf, rf; // functions to determine left, right alignment
  11035. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  11036. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  11037. var midX = (chartArea.left + chartArea.right) / 2;
  11038. var midY = (chartArea.top + chartArea.bottom) / 2;
  11039. if (yAlign === 'center') {
  11040. lf = function(x) {
  11041. return x <= midX;
  11042. };
  11043. rf = function(x) {
  11044. return x > midX;
  11045. };
  11046. } else {
  11047. lf = function(x) {
  11048. return x <= (size.width / 2);
  11049. };
  11050. rf = function(x) {
  11051. return x >= (chart.width - (size.width / 2));
  11052. };
  11053. }
  11054. olf = function(x) {
  11055. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  11056. };
  11057. orf = function(x) {
  11058. return x - size.width - model.caretSize - model.caretPadding < 0;
  11059. };
  11060. yf = function(y) {
  11061. return y <= midY ? 'top' : 'bottom';
  11062. };
  11063. if (lf(model.x)) {
  11064. xAlign = 'left';
  11065. // Is tooltip too wide and goes over the right side of the chart.?
  11066. if (olf(model.x)) {
  11067. xAlign = 'center';
  11068. yAlign = yf(model.y);
  11069. }
  11070. } else if (rf(model.x)) {
  11071. xAlign = 'right';
  11072. // Is tooltip too wide and goes outside left edge of canvas?
  11073. if (orf(model.x)) {
  11074. xAlign = 'center';
  11075. yAlign = yf(model.y);
  11076. }
  11077. }
  11078. var opts = tooltip._options;
  11079. return {
  11080. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  11081. yAlign: opts.yAlign ? opts.yAlign : yAlign
  11082. };
  11083. }
  11084. /**
  11085. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  11086. */
  11087. function getBackgroundPoint(vm, size, alignment, chart) {
  11088. // Background Position
  11089. var x = vm.x;
  11090. var y = vm.y;
  11091. var caretSize = vm.caretSize;
  11092. var caretPadding = vm.caretPadding;
  11093. var cornerRadius = vm.cornerRadius;
  11094. var xAlign = alignment.xAlign;
  11095. var yAlign = alignment.yAlign;
  11096. var paddingAndSize = caretSize + caretPadding;
  11097. var radiusAndPadding = cornerRadius + caretPadding;
  11098. if (xAlign === 'right') {
  11099. x -= size.width;
  11100. } else if (xAlign === 'center') {
  11101. x -= (size.width / 2);
  11102. if (x + size.width > chart.width) {
  11103. x = chart.width - size.width;
  11104. }
  11105. if (x < 0) {
  11106. x = 0;
  11107. }
  11108. }
  11109. if (yAlign === 'top') {
  11110. y += paddingAndSize;
  11111. } else if (yAlign === 'bottom') {
  11112. y -= size.height + paddingAndSize;
  11113. } else {
  11114. y -= (size.height / 2);
  11115. }
  11116. if (yAlign === 'center') {
  11117. if (xAlign === 'left') {
  11118. x += paddingAndSize;
  11119. } else if (xAlign === 'right') {
  11120. x -= paddingAndSize;
  11121. }
  11122. } else if (xAlign === 'left') {
  11123. x -= radiusAndPadding;
  11124. } else if (xAlign === 'right') {
  11125. x += radiusAndPadding;
  11126. }
  11127. return {
  11128. x: x,
  11129. y: y
  11130. };
  11131. }
  11132. /**
  11133. * Helper to build before and after body lines
  11134. */
  11135. function getBeforeAfterBodyLines(callback) {
  11136. return pushOrConcat([], splitNewlines(callback));
  11137. }
  11138. var exports = module.exports = Element.extend({
  11139. initialize: function() {
  11140. this._model = getBaseModel(this._options);
  11141. this._lastActive = [];
  11142. },
  11143. // Get the title
  11144. // Args are: (tooltipItem, data)
  11145. getTitle: function() {
  11146. var me = this;
  11147. var opts = me._options;
  11148. var callbacks = opts.callbacks;
  11149. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  11150. var title = callbacks.title.apply(me, arguments);
  11151. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  11152. var lines = [];
  11153. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  11154. lines = pushOrConcat(lines, splitNewlines(title));
  11155. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  11156. return lines;
  11157. },
  11158. // Args are: (tooltipItem, data)
  11159. getBeforeBody: function() {
  11160. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  11161. },
  11162. // Args are: (tooltipItem, data)
  11163. getBody: function(tooltipItems, data) {
  11164. var me = this;
  11165. var callbacks = me._options.callbacks;
  11166. var bodyItems = [];
  11167. helpers.each(tooltipItems, function(tooltipItem) {
  11168. var bodyItem = {
  11169. before: [],
  11170. lines: [],
  11171. after: []
  11172. };
  11173. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  11174. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  11175. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  11176. bodyItems.push(bodyItem);
  11177. });
  11178. return bodyItems;
  11179. },
  11180. // Args are: (tooltipItem, data)
  11181. getAfterBody: function() {
  11182. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  11183. },
  11184. // Get the footer and beforeFooter and afterFooter lines
  11185. // Args are: (tooltipItem, data)
  11186. getFooter: function() {
  11187. var me = this;
  11188. var callbacks = me._options.callbacks;
  11189. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  11190. var footer = callbacks.footer.apply(me, arguments);
  11191. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  11192. var lines = [];
  11193. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  11194. lines = pushOrConcat(lines, splitNewlines(footer));
  11195. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  11196. return lines;
  11197. },
  11198. update: function(changed) {
  11199. var me = this;
  11200. var opts = me._options;
  11201. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  11202. // 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
  11203. // which breaks any animations.
  11204. var existingModel = me._model;
  11205. var model = me._model = getBaseModel(opts);
  11206. var active = me._active;
  11207. var data = me._data;
  11208. // In the case where active.length === 0 we need to keep these at existing values for good animations
  11209. var alignment = {
  11210. xAlign: existingModel.xAlign,
  11211. yAlign: existingModel.yAlign
  11212. };
  11213. var backgroundPoint = {
  11214. x: existingModel.x,
  11215. y: existingModel.y
  11216. };
  11217. var tooltipSize = {
  11218. width: existingModel.width,
  11219. height: existingModel.height
  11220. };
  11221. var tooltipPosition = {
  11222. x: existingModel.caretX,
  11223. y: existingModel.caretY
  11224. };
  11225. var i, len;
  11226. if (active.length) {
  11227. model.opacity = 1;
  11228. var labelColors = [];
  11229. var labelTextColors = [];
  11230. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  11231. var tooltipItems = [];
  11232. for (i = 0, len = active.length; i < len; ++i) {
  11233. tooltipItems.push(createTooltipItem(active[i]));
  11234. }
  11235. // If the user provided a filter function, use it to modify the tooltip items
  11236. if (opts.filter) {
  11237. tooltipItems = tooltipItems.filter(function(a) {
  11238. return opts.filter(a, data);
  11239. });
  11240. }
  11241. // If the user provided a sorting function, use it to modify the tooltip items
  11242. if (opts.itemSort) {
  11243. tooltipItems = tooltipItems.sort(function(a, b) {
  11244. return opts.itemSort(a, b, data);
  11245. });
  11246. }
  11247. // Determine colors for boxes
  11248. helpers.each(tooltipItems, function(tooltipItem) {
  11249. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  11250. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  11251. });
  11252. // Build the Text Lines
  11253. model.title = me.getTitle(tooltipItems, data);
  11254. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  11255. model.body = me.getBody(tooltipItems, data);
  11256. model.afterBody = me.getAfterBody(tooltipItems, data);
  11257. model.footer = me.getFooter(tooltipItems, data);
  11258. // Initial positioning and colors
  11259. model.x = Math.round(tooltipPosition.x);
  11260. model.y = Math.round(tooltipPosition.y);
  11261. model.caretPadding = opts.caretPadding;
  11262. model.labelColors = labelColors;
  11263. model.labelTextColors = labelTextColors;
  11264. // data points
  11265. model.dataPoints = tooltipItems;
  11266. // We need to determine alignment of the tooltip
  11267. tooltipSize = getTooltipSize(this, model);
  11268. alignment = determineAlignment(this, tooltipSize);
  11269. // Final Size and Position
  11270. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  11271. } else {
  11272. model.opacity = 0;
  11273. }
  11274. model.xAlign = alignment.xAlign;
  11275. model.yAlign = alignment.yAlign;
  11276. model.x = backgroundPoint.x;
  11277. model.y = backgroundPoint.y;
  11278. model.width = tooltipSize.width;
  11279. model.height = tooltipSize.height;
  11280. // Point where the caret on the tooltip points to
  11281. model.caretX = tooltipPosition.x;
  11282. model.caretY = tooltipPosition.y;
  11283. me._model = model;
  11284. if (changed && opts.custom) {
  11285. opts.custom.call(me, model);
  11286. }
  11287. return me;
  11288. },
  11289. drawCaret: function(tooltipPoint, size) {
  11290. var ctx = this._chart.ctx;
  11291. var vm = this._view;
  11292. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  11293. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  11294. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  11295. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  11296. },
  11297. getCaretPosition: function(tooltipPoint, size, vm) {
  11298. var x1, x2, x3, y1, y2, y3;
  11299. var caretSize = vm.caretSize;
  11300. var cornerRadius = vm.cornerRadius;
  11301. var xAlign = vm.xAlign;
  11302. var yAlign = vm.yAlign;
  11303. var ptX = tooltipPoint.x;
  11304. var ptY = tooltipPoint.y;
  11305. var width = size.width;
  11306. var height = size.height;
  11307. if (yAlign === 'center') {
  11308. y2 = ptY + (height / 2);
  11309. if (xAlign === 'left') {
  11310. x1 = ptX;
  11311. x2 = x1 - caretSize;
  11312. x3 = x1;
  11313. y1 = y2 + caretSize;
  11314. y3 = y2 - caretSize;
  11315. } else {
  11316. x1 = ptX + width;
  11317. x2 = x1 + caretSize;
  11318. x3 = x1;
  11319. y1 = y2 - caretSize;
  11320. y3 = y2 + caretSize;
  11321. }
  11322. } else {
  11323. if (xAlign === 'left') {
  11324. x2 = ptX + cornerRadius + (caretSize);
  11325. x1 = x2 - caretSize;
  11326. x3 = x2 + caretSize;
  11327. } else if (xAlign === 'right') {
  11328. x2 = ptX + width - cornerRadius - caretSize;
  11329. x1 = x2 - caretSize;
  11330. x3 = x2 + caretSize;
  11331. } else {
  11332. x2 = vm.caretX;
  11333. x1 = x2 - caretSize;
  11334. x3 = x2 + caretSize;
  11335. }
  11336. if (yAlign === 'top') {
  11337. y1 = ptY;
  11338. y2 = y1 - caretSize;
  11339. y3 = y1;
  11340. } else {
  11341. y1 = ptY + height;
  11342. y2 = y1 + caretSize;
  11343. y3 = y1;
  11344. // invert drawing order
  11345. var tmp = x3;
  11346. x3 = x1;
  11347. x1 = tmp;
  11348. }
  11349. }
  11350. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  11351. },
  11352. drawTitle: function(pt, vm, ctx, opacity) {
  11353. var title = vm.title;
  11354. if (title.length) {
  11355. ctx.textAlign = vm._titleAlign;
  11356. ctx.textBaseline = 'top';
  11357. var titleFontSize = vm.titleFontSize;
  11358. var titleSpacing = vm.titleSpacing;
  11359. ctx.fillStyle = mergeOpacity(vm.titleFontColor, opacity);
  11360. ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  11361. var i, len;
  11362. for (i = 0, len = title.length; i < len; ++i) {
  11363. ctx.fillText(title[i], pt.x, pt.y);
  11364. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  11365. if (i + 1 === title.length) {
  11366. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  11367. }
  11368. }
  11369. }
  11370. },
  11371. drawBody: function(pt, vm, ctx, opacity) {
  11372. var bodyFontSize = vm.bodyFontSize;
  11373. var bodySpacing = vm.bodySpacing;
  11374. var body = vm.body;
  11375. ctx.textAlign = vm._bodyAlign;
  11376. ctx.textBaseline = 'top';
  11377. ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  11378. // Before Body
  11379. var xLinePadding = 0;
  11380. var fillLineOfText = function(line) {
  11381. ctx.fillText(line, pt.x + xLinePadding, pt.y);
  11382. pt.y += bodyFontSize + bodySpacing;
  11383. };
  11384. // Before body lines
  11385. ctx.fillStyle = mergeOpacity(vm.bodyFontColor, opacity);
  11386. helpers.each(vm.beforeBody, fillLineOfText);
  11387. var drawColorBoxes = vm.displayColors;
  11388. xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0;
  11389. // Draw body lines now
  11390. helpers.each(body, function(bodyItem, i) {
  11391. var textColor = mergeOpacity(vm.labelTextColors[i], opacity);
  11392. ctx.fillStyle = textColor;
  11393. helpers.each(bodyItem.before, fillLineOfText);
  11394. helpers.each(bodyItem.lines, function(line) {
  11395. // Draw Legend-like boxes if needed
  11396. if (drawColorBoxes) {
  11397. // Fill a white rect so that colours merge nicely if the opacity is < 1
  11398. ctx.fillStyle = mergeOpacity(vm.legendColorBackground, opacity);
  11399. ctx.fillRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
  11400. // Border
  11401. ctx.lineWidth = 1;
  11402. ctx.strokeStyle = mergeOpacity(vm.labelColors[i].borderColor, opacity);
  11403. ctx.strokeRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
  11404. // Inner square
  11405. ctx.fillStyle = mergeOpacity(vm.labelColors[i].backgroundColor, opacity);
  11406. ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  11407. ctx.fillStyle = textColor;
  11408. }
  11409. fillLineOfText(line);
  11410. });
  11411. helpers.each(bodyItem.after, fillLineOfText);
  11412. });
  11413. // Reset back to 0 for after body
  11414. xLinePadding = 0;
  11415. // After body lines
  11416. helpers.each(vm.afterBody, fillLineOfText);
  11417. pt.y -= bodySpacing; // Remove last body spacing
  11418. },
  11419. drawFooter: function(pt, vm, ctx, opacity) {
  11420. var footer = vm.footer;
  11421. if (footer.length) {
  11422. pt.y += vm.footerMarginTop;
  11423. ctx.textAlign = vm._footerAlign;
  11424. ctx.textBaseline = 'top';
  11425. ctx.fillStyle = mergeOpacity(vm.footerFontColor, opacity);
  11426. ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  11427. helpers.each(footer, function(line) {
  11428. ctx.fillText(line, pt.x, pt.y);
  11429. pt.y += vm.footerFontSize + vm.footerSpacing;
  11430. });
  11431. }
  11432. },
  11433. drawBackground: function(pt, vm, ctx, tooltipSize, opacity) {
  11434. ctx.fillStyle = mergeOpacity(vm.backgroundColor, opacity);
  11435. ctx.strokeStyle = mergeOpacity(vm.borderColor, opacity);
  11436. ctx.lineWidth = vm.borderWidth;
  11437. var xAlign = vm.xAlign;
  11438. var yAlign = vm.yAlign;
  11439. var x = pt.x;
  11440. var y = pt.y;
  11441. var width = tooltipSize.width;
  11442. var height = tooltipSize.height;
  11443. var radius = vm.cornerRadius;
  11444. ctx.beginPath();
  11445. ctx.moveTo(x + radius, y);
  11446. if (yAlign === 'top') {
  11447. this.drawCaret(pt, tooltipSize);
  11448. }
  11449. ctx.lineTo(x + width - radius, y);
  11450. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  11451. if (yAlign === 'center' && xAlign === 'right') {
  11452. this.drawCaret(pt, tooltipSize);
  11453. }
  11454. ctx.lineTo(x + width, y + height - radius);
  11455. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  11456. if (yAlign === 'bottom') {
  11457. this.drawCaret(pt, tooltipSize);
  11458. }
  11459. ctx.lineTo(x + radius, y + height);
  11460. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  11461. if (yAlign === 'center' && xAlign === 'left') {
  11462. this.drawCaret(pt, tooltipSize);
  11463. }
  11464. ctx.lineTo(x, y + radius);
  11465. ctx.quadraticCurveTo(x, y, x + radius, y);
  11466. ctx.closePath();
  11467. ctx.fill();
  11468. if (vm.borderWidth > 0) {
  11469. ctx.stroke();
  11470. }
  11471. },
  11472. draw: function() {
  11473. var ctx = this._chart.ctx;
  11474. var vm = this._view;
  11475. if (vm.opacity === 0) {
  11476. return;
  11477. }
  11478. var tooltipSize = {
  11479. width: vm.width,
  11480. height: vm.height
  11481. };
  11482. var pt = {
  11483. x: vm.x,
  11484. y: vm.y
  11485. };
  11486. // IE11/Edge does not like very small opacities, so snap to 0
  11487. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  11488. // Truthy/falsey value for empty tooltip
  11489. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  11490. if (this._options.enabled && hasTooltipContent) {
  11491. // Draw Background
  11492. this.drawBackground(pt, vm, ctx, tooltipSize, opacity);
  11493. // Draw Title, Body, and Footer
  11494. pt.x += vm.xPadding;
  11495. pt.y += vm.yPadding;
  11496. // Titles
  11497. this.drawTitle(pt, vm, ctx, opacity);
  11498. // Body
  11499. this.drawBody(pt, vm, ctx, opacity);
  11500. // Footer
  11501. this.drawFooter(pt, vm, ctx, opacity);
  11502. }
  11503. },
  11504. /**
  11505. * Handle an event
  11506. * @private
  11507. * @param {IEvent} event - The event to handle
  11508. * @returns {Boolean} true if the tooltip changed
  11509. */
  11510. handleEvent: function(e) {
  11511. var me = this;
  11512. var options = me._options;
  11513. var changed = false;
  11514. me._lastActive = me._lastActive || [];
  11515. // Find Active Elements for tooltips
  11516. if (e.type === 'mouseout') {
  11517. me._active = [];
  11518. } else {
  11519. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  11520. }
  11521. // Remember Last Actives
  11522. changed = !helpers.arrayEquals(me._active, me._lastActive);
  11523. // Only handle target event on tooltip change
  11524. if (changed) {
  11525. me._lastActive = me._active;
  11526. if (options.enabled || options.custom) {
  11527. me._eventPosition = {
  11528. x: e.x,
  11529. y: e.y
  11530. };
  11531. me.update(true);
  11532. me.pivot();
  11533. }
  11534. }
  11535. return changed;
  11536. }
  11537. });
  11538. /**
  11539. * @namespace Chart.Tooltip.positioners
  11540. */
  11541. exports.positioners = positioners;
  11542. },{"26":26,"27":27,"46":46}],37:[function(require,module,exports){
  11543. 'use strict';
  11544. var defaults = require(26);
  11545. var Element = require(27);
  11546. var helpers = require(46);
  11547. defaults._set('global', {
  11548. elements: {
  11549. arc: {
  11550. backgroundColor: defaults.global.defaultColor,
  11551. borderColor: '#fff',
  11552. borderWidth: 2
  11553. }
  11554. }
  11555. });
  11556. module.exports = Element.extend({
  11557. inLabelRange: function(mouseX) {
  11558. var vm = this._view;
  11559. if (vm) {
  11560. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  11561. }
  11562. return false;
  11563. },
  11564. inRange: function(chartX, chartY) {
  11565. var vm = this._view;
  11566. if (vm) {
  11567. var pointRelativePosition = helpers.getAngleFromPoint(vm, {x: chartX, y: chartY});
  11568. var angle = pointRelativePosition.angle;
  11569. var distance = pointRelativePosition.distance;
  11570. // Sanitise angle range
  11571. var startAngle = vm.startAngle;
  11572. var endAngle = vm.endAngle;
  11573. while (endAngle < startAngle) {
  11574. endAngle += 2.0 * Math.PI;
  11575. }
  11576. while (angle > endAngle) {
  11577. angle -= 2.0 * Math.PI;
  11578. }
  11579. while (angle < startAngle) {
  11580. angle += 2.0 * Math.PI;
  11581. }
  11582. // Check if within the range of the open/close angle
  11583. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  11584. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  11585. return (betweenAngles && withinRadius);
  11586. }
  11587. return false;
  11588. },
  11589. getCenterPoint: function() {
  11590. var vm = this._view;
  11591. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  11592. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  11593. return {
  11594. x: vm.x + Math.cos(halfAngle) * halfRadius,
  11595. y: vm.y + Math.sin(halfAngle) * halfRadius
  11596. };
  11597. },
  11598. getArea: function() {
  11599. var vm = this._view;
  11600. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  11601. },
  11602. tooltipPosition: function() {
  11603. var vm = this._view;
  11604. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  11605. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  11606. return {
  11607. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  11608. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  11609. };
  11610. },
  11611. draw: function() {
  11612. var ctx = this._chart.ctx;
  11613. var vm = this._view;
  11614. var sA = vm.startAngle;
  11615. var eA = vm.endAngle;
  11616. ctx.beginPath();
  11617. ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
  11618. ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
  11619. ctx.closePath();
  11620. ctx.strokeStyle = vm.borderColor;
  11621. ctx.lineWidth = vm.borderWidth;
  11622. ctx.fillStyle = vm.backgroundColor;
  11623. ctx.fill();
  11624. ctx.lineJoin = 'bevel';
  11625. if (vm.borderWidth) {
  11626. ctx.stroke();
  11627. }
  11628. }
  11629. });
  11630. },{"26":26,"27":27,"46":46}],38:[function(require,module,exports){
  11631. 'use strict';
  11632. var defaults = require(26);
  11633. var Element = require(27);
  11634. var helpers = require(46);
  11635. var globalDefaults = defaults.global;
  11636. defaults._set('global', {
  11637. elements: {
  11638. line: {
  11639. tension: 0.4,
  11640. backgroundColor: globalDefaults.defaultColor,
  11641. borderWidth: 3,
  11642. borderColor: globalDefaults.defaultColor,
  11643. borderCapStyle: 'butt',
  11644. borderDash: [],
  11645. borderDashOffset: 0.0,
  11646. borderJoinStyle: 'miter',
  11647. capBezierPoints: true,
  11648. fill: true, // do we fill in the area between the line and its base axis
  11649. }
  11650. }
  11651. });
  11652. module.exports = Element.extend({
  11653. draw: function() {
  11654. var me = this;
  11655. var vm = me._view;
  11656. var ctx = me._chart.ctx;
  11657. var spanGaps = vm.spanGaps;
  11658. var points = me._children.slice(); // clone array
  11659. var globalOptionLineElements = globalDefaults.elements.line;
  11660. var lastDrawnIndex = -1;
  11661. var index, current, previous, currentVM;
  11662. // If we are looping, adding the first point again
  11663. if (me._loop && points.length) {
  11664. points.push(points[0]);
  11665. }
  11666. ctx.save();
  11667. // Stroke Line Options
  11668. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  11669. // IE 9 and 10 do not support line dash
  11670. if (ctx.setLineDash) {
  11671. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  11672. }
  11673. ctx.lineDashOffset = vm.borderDashOffset || globalOptionLineElements.borderDashOffset;
  11674. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  11675. ctx.lineWidth = vm.borderWidth || globalOptionLineElements.borderWidth;
  11676. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  11677. // Stroke Line
  11678. ctx.beginPath();
  11679. lastDrawnIndex = -1;
  11680. for (index = 0; index < points.length; ++index) {
  11681. current = points[index];
  11682. previous = helpers.previousItem(points, index);
  11683. currentVM = current._view;
  11684. // First point moves to it's starting position no matter what
  11685. if (index === 0) {
  11686. if (!currentVM.skip) {
  11687. ctx.moveTo(currentVM.x, currentVM.y);
  11688. lastDrawnIndex = index;
  11689. }
  11690. } else {
  11691. previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
  11692. if (!currentVM.skip) {
  11693. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  11694. // There was a gap and this is the first point after the gap
  11695. ctx.moveTo(currentVM.x, currentVM.y);
  11696. } else {
  11697. // Line to next point
  11698. helpers.canvas.lineTo(ctx, previous._view, current._view);
  11699. }
  11700. lastDrawnIndex = index;
  11701. }
  11702. }
  11703. }
  11704. ctx.stroke();
  11705. ctx.restore();
  11706. }
  11707. });
  11708. },{"26":26,"27":27,"46":46}],39:[function(require,module,exports){
  11709. 'use strict';
  11710. var defaults = require(26);
  11711. var Element = require(27);
  11712. var helpers = require(46);
  11713. var defaultColor = defaults.global.defaultColor;
  11714. defaults._set('global', {
  11715. elements: {
  11716. point: {
  11717. radius: 3,
  11718. pointStyle: 'circle',
  11719. backgroundColor: defaultColor,
  11720. borderColor: defaultColor,
  11721. borderWidth: 1,
  11722. // Hover
  11723. hitRadius: 1,
  11724. hoverRadius: 4,
  11725. hoverBorderWidth: 1
  11726. }
  11727. }
  11728. });
  11729. function xRange(mouseX) {
  11730. var vm = this._view;
  11731. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  11732. }
  11733. function yRange(mouseY) {
  11734. var vm = this._view;
  11735. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  11736. }
  11737. module.exports = Element.extend({
  11738. inRange: function(mouseX, mouseY) {
  11739. var vm = this._view;
  11740. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  11741. },
  11742. inLabelRange: xRange,
  11743. inXRange: xRange,
  11744. inYRange: yRange,
  11745. getCenterPoint: function() {
  11746. var vm = this._view;
  11747. return {
  11748. x: vm.x,
  11749. y: vm.y
  11750. };
  11751. },
  11752. getArea: function() {
  11753. return Math.PI * Math.pow(this._view.radius, 2);
  11754. },
  11755. tooltipPosition: function() {
  11756. var vm = this._view;
  11757. return {
  11758. x: vm.x,
  11759. y: vm.y,
  11760. padding: vm.radius + vm.borderWidth
  11761. };
  11762. },
  11763. draw: function(chartArea) {
  11764. var vm = this._view;
  11765. var model = this._model;
  11766. var ctx = this._chart.ctx;
  11767. var pointStyle = vm.pointStyle;
  11768. var rotation = vm.rotation;
  11769. var radius = vm.radius;
  11770. var x = vm.x;
  11771. var y = vm.y;
  11772. var errMargin = 1.01; // 1.01 is margin for Accumulated error. (Especially Edge, IE.)
  11773. if (vm.skip) {
  11774. return;
  11775. }
  11776. // Clipping for Points.
  11777. if (chartArea === undefined || (model.x >= chartArea.left && chartArea.right * errMargin >= model.x && model.y >= chartArea.top && chartArea.bottom * errMargin >= model.y)) {
  11778. ctx.strokeStyle = vm.borderColor || defaultColor;
  11779. ctx.lineWidth = helpers.valueOrDefault(vm.borderWidth, defaults.global.elements.point.borderWidth);
  11780. ctx.fillStyle = vm.backgroundColor || defaultColor;
  11781. helpers.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  11782. }
  11783. }
  11784. });
  11785. },{"26":26,"27":27,"46":46}],40:[function(require,module,exports){
  11786. 'use strict';
  11787. var defaults = require(26);
  11788. var Element = require(27);
  11789. defaults._set('global', {
  11790. elements: {
  11791. rectangle: {
  11792. backgroundColor: defaults.global.defaultColor,
  11793. borderColor: defaults.global.defaultColor,
  11794. borderSkipped: 'bottom',
  11795. borderWidth: 0
  11796. }
  11797. }
  11798. });
  11799. function isVertical(bar) {
  11800. return bar._view.width !== undefined;
  11801. }
  11802. /**
  11803. * Helper function to get the bounds of the bar regardless of the orientation
  11804. * @param bar {Chart.Element.Rectangle} the bar
  11805. * @return {Bounds} bounds of the bar
  11806. * @private
  11807. */
  11808. function getBarBounds(bar) {
  11809. var vm = bar._view;
  11810. var x1, x2, y1, y2;
  11811. if (isVertical(bar)) {
  11812. // vertical
  11813. var halfWidth = vm.width / 2;
  11814. x1 = vm.x - halfWidth;
  11815. x2 = vm.x + halfWidth;
  11816. y1 = Math.min(vm.y, vm.base);
  11817. y2 = Math.max(vm.y, vm.base);
  11818. } else {
  11819. // horizontal bar
  11820. var halfHeight = vm.height / 2;
  11821. x1 = Math.min(vm.x, vm.base);
  11822. x2 = Math.max(vm.x, vm.base);
  11823. y1 = vm.y - halfHeight;
  11824. y2 = vm.y + halfHeight;
  11825. }
  11826. return {
  11827. left: x1,
  11828. top: y1,
  11829. right: x2,
  11830. bottom: y2
  11831. };
  11832. }
  11833. module.exports = Element.extend({
  11834. draw: function() {
  11835. var ctx = this._chart.ctx;
  11836. var vm = this._view;
  11837. var left, right, top, bottom, signX, signY, borderSkipped;
  11838. var borderWidth = vm.borderWidth;
  11839. if (!vm.horizontal) {
  11840. // bar
  11841. left = vm.x - vm.width / 2;
  11842. right = vm.x + vm.width / 2;
  11843. top = vm.y;
  11844. bottom = vm.base;
  11845. signX = 1;
  11846. signY = bottom > top ? 1 : -1;
  11847. borderSkipped = vm.borderSkipped || 'bottom';
  11848. } else {
  11849. // horizontal bar
  11850. left = vm.base;
  11851. right = vm.x;
  11852. top = vm.y - vm.height / 2;
  11853. bottom = vm.y + vm.height / 2;
  11854. signX = right > left ? 1 : -1;
  11855. signY = 1;
  11856. borderSkipped = vm.borderSkipped || 'left';
  11857. }
  11858. // Canvas doesn't allow us to stroke inside the width so we can
  11859. // adjust the sizes to fit if we're setting a stroke on the line
  11860. if (borderWidth) {
  11861. // borderWidth shold be less than bar width and bar height.
  11862. var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));
  11863. borderWidth = borderWidth > barSize ? barSize : borderWidth;
  11864. var halfStroke = borderWidth / 2;
  11865. // Adjust borderWidth when bar top position is near vm.base(zero).
  11866. var borderLeft = left + (borderSkipped !== 'left' ? halfStroke * signX : 0);
  11867. var borderRight = right + (borderSkipped !== 'right' ? -halfStroke * signX : 0);
  11868. var borderTop = top + (borderSkipped !== 'top' ? halfStroke * signY : 0);
  11869. var borderBottom = bottom + (borderSkipped !== 'bottom' ? -halfStroke * signY : 0);
  11870. // not become a vertical line?
  11871. if (borderLeft !== borderRight) {
  11872. top = borderTop;
  11873. bottom = borderBottom;
  11874. }
  11875. // not become a horizontal line?
  11876. if (borderTop !== borderBottom) {
  11877. left = borderLeft;
  11878. right = borderRight;
  11879. }
  11880. }
  11881. ctx.beginPath();
  11882. ctx.fillStyle = vm.backgroundColor;
  11883. ctx.strokeStyle = vm.borderColor;
  11884. ctx.lineWidth = borderWidth;
  11885. // Corner points, from bottom-left to bottom-right clockwise
  11886. // | 1 2 |
  11887. // | 0 3 |
  11888. var corners = [
  11889. [left, bottom],
  11890. [left, top],
  11891. [right, top],
  11892. [right, bottom]
  11893. ];
  11894. // Find first (starting) corner with fallback to 'bottom'
  11895. var borders = ['bottom', 'left', 'top', 'right'];
  11896. var startCorner = borders.indexOf(borderSkipped, 0);
  11897. if (startCorner === -1) {
  11898. startCorner = 0;
  11899. }
  11900. function cornerAt(index) {
  11901. return corners[(startCorner + index) % 4];
  11902. }
  11903. // Draw rectangle from 'startCorner'
  11904. var corner = cornerAt(0);
  11905. ctx.moveTo(corner[0], corner[1]);
  11906. for (var i = 1; i < 4; i++) {
  11907. corner = cornerAt(i);
  11908. ctx.lineTo(corner[0], corner[1]);
  11909. }
  11910. ctx.fill();
  11911. if (borderWidth) {
  11912. ctx.stroke();
  11913. }
  11914. },
  11915. height: function() {
  11916. var vm = this._view;
  11917. return vm.base - vm.y;
  11918. },
  11919. inRange: function(mouseX, mouseY) {
  11920. var inRange = false;
  11921. if (this._view) {
  11922. var bounds = getBarBounds(this);
  11923. inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom;
  11924. }
  11925. return inRange;
  11926. },
  11927. inLabelRange: function(mouseX, mouseY) {
  11928. var me = this;
  11929. if (!me._view) {
  11930. return false;
  11931. }
  11932. var inRange = false;
  11933. var bounds = getBarBounds(me);
  11934. if (isVertical(me)) {
  11935. inRange = mouseX >= bounds.left && mouseX <= bounds.right;
  11936. } else {
  11937. inRange = mouseY >= bounds.top && mouseY <= bounds.bottom;
  11938. }
  11939. return inRange;
  11940. },
  11941. inXRange: function(mouseX) {
  11942. var bounds = getBarBounds(this);
  11943. return mouseX >= bounds.left && mouseX <= bounds.right;
  11944. },
  11945. inYRange: function(mouseY) {
  11946. var bounds = getBarBounds(this);
  11947. return mouseY >= bounds.top && mouseY <= bounds.bottom;
  11948. },
  11949. getCenterPoint: function() {
  11950. var vm = this._view;
  11951. var x, y;
  11952. if (isVertical(this)) {
  11953. x = vm.x;
  11954. y = (vm.y + vm.base) / 2;
  11955. } else {
  11956. x = (vm.x + vm.base) / 2;
  11957. y = vm.y;
  11958. }
  11959. return {x: x, y: y};
  11960. },
  11961. getArea: function() {
  11962. var vm = this._view;
  11963. return vm.width * Math.abs(vm.y - vm.base);
  11964. },
  11965. tooltipPosition: function() {
  11966. var vm = this._view;
  11967. return {
  11968. x: vm.x,
  11969. y: vm.y
  11970. };
  11971. }
  11972. });
  11973. },{"26":26,"27":27}],41:[function(require,module,exports){
  11974. 'use strict';
  11975. module.exports = {};
  11976. module.exports.Arc = require(37);
  11977. module.exports.Line = require(38);
  11978. module.exports.Point = require(39);
  11979. module.exports.Rectangle = require(40);
  11980. },{"37":37,"38":38,"39":39,"40":40}],42:[function(require,module,exports){
  11981. 'use strict';
  11982. var helpers = require(43);
  11983. /**
  11984. * @namespace Chart.helpers.canvas
  11985. */
  11986. var exports = module.exports = {
  11987. /**
  11988. * Clears the entire canvas associated to the given `chart`.
  11989. * @param {Chart} chart - The chart for which to clear the canvas.
  11990. */
  11991. clear: function(chart) {
  11992. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  11993. },
  11994. /**
  11995. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  11996. * given size (width, height) and the same `radius` for all corners.
  11997. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  11998. * @param {Number} x - The x axis of the coordinate for the rectangle starting point.
  11999. * @param {Number} y - The y axis of the coordinate for the rectangle starting point.
  12000. * @param {Number} width - The rectangle's width.
  12001. * @param {Number} height - The rectangle's height.
  12002. * @param {Number} radius - The rounded amount (in pixels) for the four corners.
  12003. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  12004. */
  12005. roundedRect: function(ctx, x, y, width, height, radius) {
  12006. if (radius) {
  12007. // NOTE(SB) `epsilon` helps to prevent minor artifacts appearing
  12008. // on Chrome when `r` is exactly half the height or the width.
  12009. var epsilon = 0.0000001;
  12010. var r = Math.min(radius, (height / 2) - epsilon, (width / 2) - epsilon);
  12011. ctx.moveTo(x + r, y);
  12012. ctx.lineTo(x + width - r, y);
  12013. ctx.arcTo(x + width, y, x + width, y + r, r);
  12014. ctx.lineTo(x + width, y + height - r);
  12015. ctx.arcTo(x + width, y + height, x + width - r, y + height, r);
  12016. ctx.lineTo(x + r, y + height);
  12017. ctx.arcTo(x, y + height, x, y + height - r, r);
  12018. ctx.lineTo(x, y + r);
  12019. ctx.arcTo(x, y, x + r, y, r);
  12020. ctx.closePath();
  12021. ctx.moveTo(x, y);
  12022. } else {
  12023. ctx.rect(x, y, width, height);
  12024. }
  12025. },
  12026. drawPoint: function(ctx, style, radius, x, y, rotation) {
  12027. var type, edgeLength, xOffset, yOffset, height, size;
  12028. rotation = rotation || 0;
  12029. if (style && typeof style === 'object') {
  12030. type = style.toString();
  12031. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  12032. ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height);
  12033. return;
  12034. }
  12035. }
  12036. if (isNaN(radius) || radius <= 0) {
  12037. return;
  12038. }
  12039. ctx.save();
  12040. ctx.translate(x, y);
  12041. ctx.rotate(rotation * Math.PI / 180);
  12042. ctx.beginPath();
  12043. switch (style) {
  12044. // Default includes circle
  12045. default:
  12046. ctx.arc(0, 0, radius, 0, Math.PI * 2);
  12047. ctx.closePath();
  12048. break;
  12049. case 'triangle':
  12050. edgeLength = 3 * radius / Math.sqrt(3);
  12051. height = edgeLength * Math.sqrt(3) / 2;
  12052. ctx.moveTo(-edgeLength / 2, height / 3);
  12053. ctx.lineTo(edgeLength / 2, height / 3);
  12054. ctx.lineTo(0, -2 * height / 3);
  12055. ctx.closePath();
  12056. break;
  12057. case 'rect':
  12058. size = 1 / Math.SQRT2 * radius;
  12059. ctx.rect(-size, -size, 2 * size, 2 * size);
  12060. break;
  12061. case 'rectRounded':
  12062. var offset = radius / Math.SQRT2;
  12063. var leftX = -offset;
  12064. var topY = -offset;
  12065. var sideSize = Math.SQRT2 * radius;
  12066. // NOTE(SB) the rounded rect implementation changed to use `arcTo`
  12067. // instead of `quadraticCurveTo` since it generates better results
  12068. // when rect is almost a circle. 0.425 (instead of 0.5) produces
  12069. // results visually closer to the previous impl.
  12070. this.roundedRect(ctx, leftX, topY, sideSize, sideSize, radius * 0.425);
  12071. break;
  12072. case 'rectRot':
  12073. size = 1 / Math.SQRT2 * radius;
  12074. ctx.moveTo(-size, 0);
  12075. ctx.lineTo(0, size);
  12076. ctx.lineTo(size, 0);
  12077. ctx.lineTo(0, -size);
  12078. ctx.closePath();
  12079. break;
  12080. case 'cross':
  12081. ctx.moveTo(0, radius);
  12082. ctx.lineTo(0, -radius);
  12083. ctx.moveTo(-radius, 0);
  12084. ctx.lineTo(radius, 0);
  12085. break;
  12086. case 'crossRot':
  12087. xOffset = Math.cos(Math.PI / 4) * radius;
  12088. yOffset = Math.sin(Math.PI / 4) * radius;
  12089. ctx.moveTo(-xOffset, -yOffset);
  12090. ctx.lineTo(xOffset, yOffset);
  12091. ctx.moveTo(-xOffset, yOffset);
  12092. ctx.lineTo(xOffset, -yOffset);
  12093. break;
  12094. case 'star':
  12095. ctx.moveTo(0, radius);
  12096. ctx.lineTo(0, -radius);
  12097. ctx.moveTo(-radius, 0);
  12098. ctx.lineTo(radius, 0);
  12099. xOffset = Math.cos(Math.PI / 4) * radius;
  12100. yOffset = Math.sin(Math.PI / 4) * radius;
  12101. ctx.moveTo(-xOffset, -yOffset);
  12102. ctx.lineTo(xOffset, yOffset);
  12103. ctx.moveTo(-xOffset, yOffset);
  12104. ctx.lineTo(xOffset, -yOffset);
  12105. break;
  12106. case 'line':
  12107. ctx.moveTo(-radius, 0);
  12108. ctx.lineTo(radius, 0);
  12109. break;
  12110. case 'dash':
  12111. ctx.moveTo(0, 0);
  12112. ctx.lineTo(radius, 0);
  12113. break;
  12114. }
  12115. ctx.fill();
  12116. ctx.stroke();
  12117. ctx.restore();
  12118. },
  12119. clipArea: function(ctx, area) {
  12120. ctx.save();
  12121. ctx.beginPath();
  12122. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  12123. ctx.clip();
  12124. },
  12125. unclipArea: function(ctx) {
  12126. ctx.restore();
  12127. },
  12128. lineTo: function(ctx, previous, target, flip) {
  12129. if (target.steppedLine) {
  12130. if ((target.steppedLine === 'after' && !flip) || (target.steppedLine !== 'after' && flip)) {
  12131. ctx.lineTo(previous.x, target.y);
  12132. } else {
  12133. ctx.lineTo(target.x, previous.y);
  12134. }
  12135. ctx.lineTo(target.x, target.y);
  12136. return;
  12137. }
  12138. if (!target.tension) {
  12139. ctx.lineTo(target.x, target.y);
  12140. return;
  12141. }
  12142. ctx.bezierCurveTo(
  12143. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  12144. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  12145. flip ? target.controlPointNextX : target.controlPointPreviousX,
  12146. flip ? target.controlPointNextY : target.controlPointPreviousY,
  12147. target.x,
  12148. target.y);
  12149. }
  12150. };
  12151. // DEPRECATIONS
  12152. /**
  12153. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  12154. * @namespace Chart.helpers.clear
  12155. * @deprecated since version 2.7.0
  12156. * @todo remove at version 3
  12157. * @private
  12158. */
  12159. helpers.clear = exports.clear;
  12160. /**
  12161. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  12162. * @namespace Chart.helpers.drawRoundedRectangle
  12163. * @deprecated since version 2.7.0
  12164. * @todo remove at version 3
  12165. * @private
  12166. */
  12167. helpers.drawRoundedRectangle = function(ctx) {
  12168. ctx.beginPath();
  12169. exports.roundedRect.apply(exports, arguments);
  12170. };
  12171. },{"43":43}],43:[function(require,module,exports){
  12172. 'use strict';
  12173. /**
  12174. * @namespace Chart.helpers
  12175. */
  12176. var helpers = {
  12177. /**
  12178. * An empty function that can be used, for example, for optional callback.
  12179. */
  12180. noop: function() {},
  12181. /**
  12182. * Returns a unique id, sequentially generated from a global variable.
  12183. * @returns {Number}
  12184. * @function
  12185. */
  12186. uid: (function() {
  12187. var id = 0;
  12188. return function() {
  12189. return id++;
  12190. };
  12191. }()),
  12192. /**
  12193. * Returns true if `value` is neither null nor undefined, else returns false.
  12194. * @param {*} value - The value to test.
  12195. * @returns {Boolean}
  12196. * @since 2.7.0
  12197. */
  12198. isNullOrUndef: function(value) {
  12199. return value === null || typeof value === 'undefined';
  12200. },
  12201. /**
  12202. * Returns true if `value` is an array, else returns false.
  12203. * @param {*} value - The value to test.
  12204. * @returns {Boolean}
  12205. * @function
  12206. */
  12207. isArray: Array.isArray ? Array.isArray : function(value) {
  12208. return Object.prototype.toString.call(value) === '[object Array]';
  12209. },
  12210. /**
  12211. * Returns true if `value` is an object (excluding null), else returns false.
  12212. * @param {*} value - The value to test.
  12213. * @returns {Boolean}
  12214. * @since 2.7.0
  12215. */
  12216. isObject: function(value) {
  12217. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  12218. },
  12219. /**
  12220. * Returns `value` if defined, else returns `defaultValue`.
  12221. * @param {*} value - The value to return if defined.
  12222. * @param {*} defaultValue - The value to return if `value` is undefined.
  12223. * @returns {*}
  12224. */
  12225. valueOrDefault: function(value, defaultValue) {
  12226. return typeof value === 'undefined' ? defaultValue : value;
  12227. },
  12228. /**
  12229. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  12230. * @param {Array} value - The array to lookup for value at `index`.
  12231. * @param {Number} index - The index in `value` to lookup for value.
  12232. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  12233. * @returns {*}
  12234. */
  12235. valueAtIndexOrDefault: function(value, index, defaultValue) {
  12236. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  12237. },
  12238. /**
  12239. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  12240. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  12241. * @param {Function} fn - The function to call.
  12242. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  12243. * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
  12244. * @returns {*}
  12245. */
  12246. callback: function(fn, args, thisArg) {
  12247. if (fn && typeof fn.call === 'function') {
  12248. return fn.apply(thisArg, args);
  12249. }
  12250. },
  12251. /**
  12252. * Note(SB) for performance sake, this method should only be used when loopable type
  12253. * is unknown or in none intensive code (not called often and small loopable). Else
  12254. * it's preferable to use a regular for() loop and save extra function calls.
  12255. * @param {Object|Array} loopable - The object or array to be iterated.
  12256. * @param {Function} fn - The function to call for each item.
  12257. * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
  12258. * @param {Boolean} [reverse] - If true, iterates backward on the loopable.
  12259. */
  12260. each: function(loopable, fn, thisArg, reverse) {
  12261. var i, len, keys;
  12262. if (helpers.isArray(loopable)) {
  12263. len = loopable.length;
  12264. if (reverse) {
  12265. for (i = len - 1; i >= 0; i--) {
  12266. fn.call(thisArg, loopable[i], i);
  12267. }
  12268. } else {
  12269. for (i = 0; i < len; i++) {
  12270. fn.call(thisArg, loopable[i], i);
  12271. }
  12272. }
  12273. } else if (helpers.isObject(loopable)) {
  12274. keys = Object.keys(loopable);
  12275. len = keys.length;
  12276. for (i = 0; i < len; i++) {
  12277. fn.call(thisArg, loopable[keys[i]], keys[i]);
  12278. }
  12279. }
  12280. },
  12281. /**
  12282. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  12283. * @see http://stackoverflow.com/a/14853974
  12284. * @param {Array} a0 - The array to compare
  12285. * @param {Array} a1 - The array to compare
  12286. * @returns {Boolean}
  12287. */
  12288. arrayEquals: function(a0, a1) {
  12289. var i, ilen, v0, v1;
  12290. if (!a0 || !a1 || a0.length !== a1.length) {
  12291. return false;
  12292. }
  12293. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  12294. v0 = a0[i];
  12295. v1 = a1[i];
  12296. if (v0 instanceof Array && v1 instanceof Array) {
  12297. if (!helpers.arrayEquals(v0, v1)) {
  12298. return false;
  12299. }
  12300. } else if (v0 !== v1) {
  12301. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  12302. return false;
  12303. }
  12304. }
  12305. return true;
  12306. },
  12307. /**
  12308. * Returns a deep copy of `source` without keeping references on objects and arrays.
  12309. * @param {*} source - The value to clone.
  12310. * @returns {*}
  12311. */
  12312. clone: function(source) {
  12313. if (helpers.isArray(source)) {
  12314. return source.map(helpers.clone);
  12315. }
  12316. if (helpers.isObject(source)) {
  12317. var target = {};
  12318. var keys = Object.keys(source);
  12319. var klen = keys.length;
  12320. var k = 0;
  12321. for (; k < klen; ++k) {
  12322. target[keys[k]] = helpers.clone(source[keys[k]]);
  12323. }
  12324. return target;
  12325. }
  12326. return source;
  12327. },
  12328. /**
  12329. * The default merger when Chart.helpers.merge is called without merger option.
  12330. * Note(SB): this method is also used by configMerge and scaleMerge as fallback.
  12331. * @private
  12332. */
  12333. _merger: function(key, target, source, options) {
  12334. var tval = target[key];
  12335. var sval = source[key];
  12336. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  12337. helpers.merge(tval, sval, options);
  12338. } else {
  12339. target[key] = helpers.clone(sval);
  12340. }
  12341. },
  12342. /**
  12343. * Merges source[key] in target[key] only if target[key] is undefined.
  12344. * @private
  12345. */
  12346. _mergerIf: function(key, target, source) {
  12347. var tval = target[key];
  12348. var sval = source[key];
  12349. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  12350. helpers.mergeIf(tval, sval);
  12351. } else if (!target.hasOwnProperty(key)) {
  12352. target[key] = helpers.clone(sval);
  12353. }
  12354. },
  12355. /**
  12356. * Recursively deep copies `source` properties into `target` with the given `options`.
  12357. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  12358. * @param {Object} target - The target object in which all sources are merged into.
  12359. * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
  12360. * @param {Object} [options] - Merging options:
  12361. * @param {Function} [options.merger] - The merge method (key, target, source, options)
  12362. * @returns {Object} The `target` object.
  12363. */
  12364. merge: function(target, source, options) {
  12365. var sources = helpers.isArray(source) ? source : [source];
  12366. var ilen = sources.length;
  12367. var merge, i, keys, klen, k;
  12368. if (!helpers.isObject(target)) {
  12369. return target;
  12370. }
  12371. options = options || {};
  12372. merge = options.merger || helpers._merger;
  12373. for (i = 0; i < ilen; ++i) {
  12374. source = sources[i];
  12375. if (!helpers.isObject(source)) {
  12376. continue;
  12377. }
  12378. keys = Object.keys(source);
  12379. for (k = 0, klen = keys.length; k < klen; ++k) {
  12380. merge(keys[k], target, source, options);
  12381. }
  12382. }
  12383. return target;
  12384. },
  12385. /**
  12386. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  12387. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  12388. * @param {Object} target - The target object in which all sources are merged into.
  12389. * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
  12390. * @returns {Object} The `target` object.
  12391. */
  12392. mergeIf: function(target, source) {
  12393. return helpers.merge(target, source, {merger: helpers._mergerIf});
  12394. },
  12395. /**
  12396. * Applies the contents of two or more objects together into the first object.
  12397. * @param {Object} target - The target object in which all objects are merged into.
  12398. * @param {Object} arg1 - Object containing additional properties to merge in target.
  12399. * @param {Object} argN - Additional objects containing properties to merge in target.
  12400. * @returns {Object} The `target` object.
  12401. */
  12402. extend: function(target) {
  12403. var setFn = function(value, key) {
  12404. target[key] = value;
  12405. };
  12406. for (var i = 1, ilen = arguments.length; i < ilen; ++i) {
  12407. helpers.each(arguments[i], setFn);
  12408. }
  12409. return target;
  12410. },
  12411. /**
  12412. * Basic javascript inheritance based on the model created in Backbone.js
  12413. */
  12414. inherits: function(extensions) {
  12415. var me = this;
  12416. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  12417. return me.apply(this, arguments);
  12418. };
  12419. var Surrogate = function() {
  12420. this.constructor = ChartElement;
  12421. };
  12422. Surrogate.prototype = me.prototype;
  12423. ChartElement.prototype = new Surrogate();
  12424. ChartElement.extend = helpers.inherits;
  12425. if (extensions) {
  12426. helpers.extend(ChartElement.prototype, extensions);
  12427. }
  12428. ChartElement.__super__ = me.prototype;
  12429. return ChartElement;
  12430. }
  12431. };
  12432. module.exports = helpers;
  12433. // DEPRECATIONS
  12434. /**
  12435. * Provided for backward compatibility, use Chart.helpers.callback instead.
  12436. * @function Chart.helpers.callCallback
  12437. * @deprecated since version 2.6.0
  12438. * @todo remove at version 3
  12439. * @private
  12440. */
  12441. helpers.callCallback = helpers.callback;
  12442. /**
  12443. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  12444. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  12445. * @function Chart.helpers.indexOf
  12446. * @deprecated since version 2.7.0
  12447. * @todo remove at version 3
  12448. * @private
  12449. */
  12450. helpers.indexOf = function(array, item, fromIndex) {
  12451. return Array.prototype.indexOf.call(array, item, fromIndex);
  12452. };
  12453. /**
  12454. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  12455. * @function Chart.helpers.getValueOrDefault
  12456. * @deprecated since version 2.7.0
  12457. * @todo remove at version 3
  12458. * @private
  12459. */
  12460. helpers.getValueOrDefault = helpers.valueOrDefault;
  12461. /**
  12462. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  12463. * @function Chart.helpers.getValueAtIndexOrDefault
  12464. * @deprecated since version 2.7.0
  12465. * @todo remove at version 3
  12466. * @private
  12467. */
  12468. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  12469. },{}],44:[function(require,module,exports){
  12470. 'use strict';
  12471. var helpers = require(43);
  12472. /**
  12473. * Easing functions adapted from Robert Penner's easing equations.
  12474. * @namespace Chart.helpers.easingEffects
  12475. * @see http://www.robertpenner.com/easing/
  12476. */
  12477. var effects = {
  12478. linear: function(t) {
  12479. return t;
  12480. },
  12481. easeInQuad: function(t) {
  12482. return t * t;
  12483. },
  12484. easeOutQuad: function(t) {
  12485. return -t * (t - 2);
  12486. },
  12487. easeInOutQuad: function(t) {
  12488. if ((t /= 0.5) < 1) {
  12489. return 0.5 * t * t;
  12490. }
  12491. return -0.5 * ((--t) * (t - 2) - 1);
  12492. },
  12493. easeInCubic: function(t) {
  12494. return t * t * t;
  12495. },
  12496. easeOutCubic: function(t) {
  12497. return (t = t - 1) * t * t + 1;
  12498. },
  12499. easeInOutCubic: function(t) {
  12500. if ((t /= 0.5) < 1) {
  12501. return 0.5 * t * t * t;
  12502. }
  12503. return 0.5 * ((t -= 2) * t * t + 2);
  12504. },
  12505. easeInQuart: function(t) {
  12506. return t * t * t * t;
  12507. },
  12508. easeOutQuart: function(t) {
  12509. return -((t = t - 1) * t * t * t - 1);
  12510. },
  12511. easeInOutQuart: function(t) {
  12512. if ((t /= 0.5) < 1) {
  12513. return 0.5 * t * t * t * t;
  12514. }
  12515. return -0.5 * ((t -= 2) * t * t * t - 2);
  12516. },
  12517. easeInQuint: function(t) {
  12518. return t * t * t * t * t;
  12519. },
  12520. easeOutQuint: function(t) {
  12521. return (t = t - 1) * t * t * t * t + 1;
  12522. },
  12523. easeInOutQuint: function(t) {
  12524. if ((t /= 0.5) < 1) {
  12525. return 0.5 * t * t * t * t * t;
  12526. }
  12527. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  12528. },
  12529. easeInSine: function(t) {
  12530. return -Math.cos(t * (Math.PI / 2)) + 1;
  12531. },
  12532. easeOutSine: function(t) {
  12533. return Math.sin(t * (Math.PI / 2));
  12534. },
  12535. easeInOutSine: function(t) {
  12536. return -0.5 * (Math.cos(Math.PI * t) - 1);
  12537. },
  12538. easeInExpo: function(t) {
  12539. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  12540. },
  12541. easeOutExpo: function(t) {
  12542. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  12543. },
  12544. easeInOutExpo: function(t) {
  12545. if (t === 0) {
  12546. return 0;
  12547. }
  12548. if (t === 1) {
  12549. return 1;
  12550. }
  12551. if ((t /= 0.5) < 1) {
  12552. return 0.5 * Math.pow(2, 10 * (t - 1));
  12553. }
  12554. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  12555. },
  12556. easeInCirc: function(t) {
  12557. if (t >= 1) {
  12558. return t;
  12559. }
  12560. return -(Math.sqrt(1 - t * t) - 1);
  12561. },
  12562. easeOutCirc: function(t) {
  12563. return Math.sqrt(1 - (t = t - 1) * t);
  12564. },
  12565. easeInOutCirc: function(t) {
  12566. if ((t /= 0.5) < 1) {
  12567. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  12568. }
  12569. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  12570. },
  12571. easeInElastic: function(t) {
  12572. var s = 1.70158;
  12573. var p = 0;
  12574. var a = 1;
  12575. if (t === 0) {
  12576. return 0;
  12577. }
  12578. if (t === 1) {
  12579. return 1;
  12580. }
  12581. if (!p) {
  12582. p = 0.3;
  12583. }
  12584. if (a < 1) {
  12585. a = 1;
  12586. s = p / 4;
  12587. } else {
  12588. s = p / (2 * Math.PI) * Math.asin(1 / a);
  12589. }
  12590. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  12591. },
  12592. easeOutElastic: function(t) {
  12593. var s = 1.70158;
  12594. var p = 0;
  12595. var a = 1;
  12596. if (t === 0) {
  12597. return 0;
  12598. }
  12599. if (t === 1) {
  12600. return 1;
  12601. }
  12602. if (!p) {
  12603. p = 0.3;
  12604. }
  12605. if (a < 1) {
  12606. a = 1;
  12607. s = p / 4;
  12608. } else {
  12609. s = p / (2 * Math.PI) * Math.asin(1 / a);
  12610. }
  12611. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  12612. },
  12613. easeInOutElastic: function(t) {
  12614. var s = 1.70158;
  12615. var p = 0;
  12616. var a = 1;
  12617. if (t === 0) {
  12618. return 0;
  12619. }
  12620. if ((t /= 0.5) === 2) {
  12621. return 1;
  12622. }
  12623. if (!p) {
  12624. p = 0.45;
  12625. }
  12626. if (a < 1) {
  12627. a = 1;
  12628. s = p / 4;
  12629. } else {
  12630. s = p / (2 * Math.PI) * Math.asin(1 / a);
  12631. }
  12632. if (t < 1) {
  12633. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  12634. }
  12635. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  12636. },
  12637. easeInBack: function(t) {
  12638. var s = 1.70158;
  12639. return t * t * ((s + 1) * t - s);
  12640. },
  12641. easeOutBack: function(t) {
  12642. var s = 1.70158;
  12643. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  12644. },
  12645. easeInOutBack: function(t) {
  12646. var s = 1.70158;
  12647. if ((t /= 0.5) < 1) {
  12648. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  12649. }
  12650. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  12651. },
  12652. easeInBounce: function(t) {
  12653. return 1 - effects.easeOutBounce(1 - t);
  12654. },
  12655. easeOutBounce: function(t) {
  12656. if (t < (1 / 2.75)) {
  12657. return 7.5625 * t * t;
  12658. }
  12659. if (t < (2 / 2.75)) {
  12660. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  12661. }
  12662. if (t < (2.5 / 2.75)) {
  12663. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  12664. }
  12665. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  12666. },
  12667. easeInOutBounce: function(t) {
  12668. if (t < 0.5) {
  12669. return effects.easeInBounce(t * 2) * 0.5;
  12670. }
  12671. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  12672. }
  12673. };
  12674. module.exports = {
  12675. effects: effects
  12676. };
  12677. // DEPRECATIONS
  12678. /**
  12679. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  12680. * @function Chart.helpers.easingEffects
  12681. * @deprecated since version 2.7.0
  12682. * @todo remove at version 3
  12683. * @private
  12684. */
  12685. helpers.easingEffects = effects;
  12686. },{"43":43}],45:[function(require,module,exports){
  12687. 'use strict';
  12688. var helpers = require(43);
  12689. /**
  12690. * @alias Chart.helpers.options
  12691. * @namespace
  12692. */
  12693. module.exports = {
  12694. /**
  12695. * Converts the given line height `value` in pixels for a specific font `size`.
  12696. * @param {Number|String} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  12697. * @param {Number} size - The font size (in pixels) used to resolve relative `value`.
  12698. * @returns {Number} The effective line height in pixels (size * 1.2 if value is invalid).
  12699. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  12700. * @since 2.7.0
  12701. */
  12702. toLineHeight: function(value, size) {
  12703. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  12704. if (!matches || matches[1] === 'normal') {
  12705. return size * 1.2;
  12706. }
  12707. value = +matches[2];
  12708. switch (matches[3]) {
  12709. case 'px':
  12710. return value;
  12711. case '%':
  12712. value /= 100;
  12713. break;
  12714. default:
  12715. break;
  12716. }
  12717. return size * value;
  12718. },
  12719. /**
  12720. * Converts the given value into a padding object with pre-computed width/height.
  12721. * @param {Number|Object} value - If a number, set the value to all TRBL component,
  12722. * else, if and object, use defined properties and sets undefined ones to 0.
  12723. * @returns {Object} The padding values (top, right, bottom, left, width, height)
  12724. * @since 2.7.0
  12725. */
  12726. toPadding: function(value) {
  12727. var t, r, b, l;
  12728. if (helpers.isObject(value)) {
  12729. t = +value.top || 0;
  12730. r = +value.right || 0;
  12731. b = +value.bottom || 0;
  12732. l = +value.left || 0;
  12733. } else {
  12734. t = r = b = l = +value || 0;
  12735. }
  12736. return {
  12737. top: t,
  12738. right: r,
  12739. bottom: b,
  12740. left: l,
  12741. height: t + b,
  12742. width: l + r
  12743. };
  12744. },
  12745. /**
  12746. * Evaluates the given `inputs` sequentially and returns the first defined value.
  12747. * @param {Array[]} inputs - An array of values, falling back to the last value.
  12748. * @param {Object} [context] - If defined and the current value is a function, the value
  12749. * is called with `context` as first argument and the result becomes the new input.
  12750. * @param {Number} [index] - If defined and the current value is an array, the value
  12751. * at `index` become the new input.
  12752. * @since 2.7.0
  12753. */
  12754. resolve: function(inputs, context, index) {
  12755. var i, ilen, value;
  12756. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  12757. value = inputs[i];
  12758. if (value === undefined) {
  12759. continue;
  12760. }
  12761. if (context !== undefined && typeof value === 'function') {
  12762. value = value(context);
  12763. }
  12764. if (index !== undefined && helpers.isArray(value)) {
  12765. value = value[index];
  12766. }
  12767. if (value !== undefined) {
  12768. return value;
  12769. }
  12770. }
  12771. }
  12772. };
  12773. },{"43":43}],46:[function(require,module,exports){
  12774. 'use strict';
  12775. module.exports = require(43);
  12776. module.exports.easing = require(44);
  12777. module.exports.canvas = require(42);
  12778. module.exports.options = require(45);
  12779. },{"42":42,"43":43,"44":44,"45":45}],47:[function(require,module,exports){
  12780. /**
  12781. * Platform fallback implementation (minimal).
  12782. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  12783. */
  12784. module.exports = {
  12785. acquireContext: function(item) {
  12786. if (item && item.canvas) {
  12787. // Support for any object associated to a canvas (including a context2d)
  12788. item = item.canvas;
  12789. }
  12790. return item && item.getContext('2d') || null;
  12791. }
  12792. };
  12793. },{}],48:[function(require,module,exports){
  12794. /**
  12795. * Chart.Platform implementation for targeting a web browser
  12796. */
  12797. 'use strict';
  12798. var helpers = require(46);
  12799. var EXPANDO_KEY = '$chartjs';
  12800. var CSS_PREFIX = 'chartjs-';
  12801. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  12802. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  12803. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  12804. /**
  12805. * DOM event types -> Chart.js event types.
  12806. * Note: only events with different types are mapped.
  12807. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  12808. */
  12809. var EVENT_TYPES = {
  12810. touchstart: 'mousedown',
  12811. touchmove: 'mousemove',
  12812. touchend: 'mouseup',
  12813. pointerenter: 'mouseenter',
  12814. pointerdown: 'mousedown',
  12815. pointermove: 'mousemove',
  12816. pointerup: 'mouseup',
  12817. pointerleave: 'mouseout',
  12818. pointerout: 'mouseout'
  12819. };
  12820. /**
  12821. * The "used" size is the final value of a dimension property after all calculations have
  12822. * been performed. This method uses the computed style of `element` but returns undefined
  12823. * if the computed style is not expressed in pixels. That can happen in some cases where
  12824. * `element` has a size relative to its parent and this last one is not yet displayed,
  12825. * for example because of `display: none` on a parent node.
  12826. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  12827. * @returns {Number} Size in pixels or undefined if unknown.
  12828. */
  12829. function readUsedSize(element, property) {
  12830. var value = helpers.getStyle(element, property);
  12831. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  12832. return matches ? Number(matches[1]) : undefined;
  12833. }
  12834. /**
  12835. * Initializes the canvas style and render size without modifying the canvas display size,
  12836. * since responsiveness is handled by the controller.resize() method. The config is used
  12837. * to determine the aspect ratio to apply in case no explicit height has been specified.
  12838. */
  12839. function initCanvas(canvas, config) {
  12840. var style = canvas.style;
  12841. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  12842. // returns null or '' if no explicit value has been set to the canvas attribute.
  12843. var renderHeight = canvas.getAttribute('height');
  12844. var renderWidth = canvas.getAttribute('width');
  12845. // Chart.js modifies some canvas values that we want to restore on destroy
  12846. canvas[EXPANDO_KEY] = {
  12847. initial: {
  12848. height: renderHeight,
  12849. width: renderWidth,
  12850. style: {
  12851. display: style.display,
  12852. height: style.height,
  12853. width: style.width
  12854. }
  12855. }
  12856. };
  12857. // Force canvas to display as block to avoid extra space caused by inline
  12858. // elements, which would interfere with the responsive resize process.
  12859. // https://github.com/chartjs/Chart.js/issues/2538
  12860. style.display = style.display || 'block';
  12861. if (renderWidth === null || renderWidth === '') {
  12862. var displayWidth = readUsedSize(canvas, 'width');
  12863. if (displayWidth !== undefined) {
  12864. canvas.width = displayWidth;
  12865. }
  12866. }
  12867. if (renderHeight === null || renderHeight === '') {
  12868. if (canvas.style.height === '') {
  12869. // If no explicit render height and style height, let's apply the aspect ratio,
  12870. // which one can be specified by the user but also by charts as default option
  12871. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  12872. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  12873. } else {
  12874. var displayHeight = readUsedSize(canvas, 'height');
  12875. if (displayWidth !== undefined) {
  12876. canvas.height = displayHeight;
  12877. }
  12878. }
  12879. }
  12880. return canvas;
  12881. }
  12882. /**
  12883. * Detects support for options object argument in addEventListener.
  12884. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  12885. * @private
  12886. */
  12887. var supportsEventListenerOptions = (function() {
  12888. var supports = false;
  12889. try {
  12890. var options = Object.defineProperty({}, 'passive', {
  12891. get: function() {
  12892. supports = true;
  12893. }
  12894. });
  12895. window.addEventListener('e', null, options);
  12896. } catch (e) {
  12897. // continue regardless of error
  12898. }
  12899. return supports;
  12900. }());
  12901. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  12902. // https://github.com/chartjs/Chart.js/issues/4287
  12903. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  12904. function addEventListener(node, type, listener) {
  12905. node.addEventListener(type, listener, eventListenerOptions);
  12906. }
  12907. function removeEventListener(node, type, listener) {
  12908. node.removeEventListener(type, listener, eventListenerOptions);
  12909. }
  12910. function createEvent(type, chart, x, y, nativeEvent) {
  12911. return {
  12912. type: type,
  12913. chart: chart,
  12914. native: nativeEvent || null,
  12915. x: x !== undefined ? x : null,
  12916. y: y !== undefined ? y : null,
  12917. };
  12918. }
  12919. function fromNativeEvent(event, chart) {
  12920. var type = EVENT_TYPES[event.type] || event.type;
  12921. var pos = helpers.getRelativePosition(event, chart);
  12922. return createEvent(type, chart, pos.x, pos.y, event);
  12923. }
  12924. function throttled(fn, thisArg) {
  12925. var ticking = false;
  12926. var args = [];
  12927. return function() {
  12928. args = Array.prototype.slice.call(arguments);
  12929. thisArg = thisArg || this;
  12930. if (!ticking) {
  12931. ticking = true;
  12932. helpers.requestAnimFrame.call(window, function() {
  12933. ticking = false;
  12934. fn.apply(thisArg, args);
  12935. });
  12936. }
  12937. };
  12938. }
  12939. // Implementation based on https://github.com/marcj/css-element-queries
  12940. function createResizer(handler) {
  12941. var resizer = document.createElement('div');
  12942. var cls = CSS_PREFIX + 'size-monitor';
  12943. var maxSize = 1000000;
  12944. var style =
  12945. 'position:absolute;' +
  12946. 'left:0;' +
  12947. 'top:0;' +
  12948. 'right:0;' +
  12949. 'bottom:0;' +
  12950. 'overflow:hidden;' +
  12951. 'pointer-events:none;' +
  12952. 'visibility:hidden;' +
  12953. 'z-index:-1;';
  12954. resizer.style.cssText = style;
  12955. resizer.className = cls;
  12956. resizer.innerHTML =
  12957. '<div class="' + cls + '-expand" style="' + style + '">' +
  12958. '<div style="' +
  12959. 'position:absolute;' +
  12960. 'width:' + maxSize + 'px;' +
  12961. 'height:' + maxSize + 'px;' +
  12962. 'left:0;' +
  12963. 'top:0">' +
  12964. '</div>' +
  12965. '</div>' +
  12966. '<div class="' + cls + '-shrink" style="' + style + '">' +
  12967. '<div style="' +
  12968. 'position:absolute;' +
  12969. 'width:200%;' +
  12970. 'height:200%;' +
  12971. 'left:0; ' +
  12972. 'top:0">' +
  12973. '</div>' +
  12974. '</div>';
  12975. var expand = resizer.childNodes[0];
  12976. var shrink = resizer.childNodes[1];
  12977. resizer._reset = function() {
  12978. expand.scrollLeft = maxSize;
  12979. expand.scrollTop = maxSize;
  12980. shrink.scrollLeft = maxSize;
  12981. shrink.scrollTop = maxSize;
  12982. };
  12983. var onScroll = function() {
  12984. resizer._reset();
  12985. handler();
  12986. };
  12987. addEventListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  12988. addEventListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  12989. return resizer;
  12990. }
  12991. // https://davidwalsh.name/detect-node-insertion
  12992. function watchForRender(node, handler) {
  12993. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  12994. var proxy = expando.renderProxy = function(e) {
  12995. if (e.animationName === CSS_RENDER_ANIMATION) {
  12996. handler();
  12997. }
  12998. };
  12999. helpers.each(ANIMATION_START_EVENTS, function(type) {
  13000. addEventListener(node, type, proxy);
  13001. });
  13002. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  13003. // is removed then added back immediately (same animation frame?). Accessing the
  13004. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  13005. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  13006. // https://github.com/chartjs/Chart.js/issues/4737
  13007. expando.reflow = !!node.offsetParent;
  13008. node.classList.add(CSS_RENDER_MONITOR);
  13009. }
  13010. function unwatchForRender(node) {
  13011. var expando = node[EXPANDO_KEY] || {};
  13012. var proxy = expando.renderProxy;
  13013. if (proxy) {
  13014. helpers.each(ANIMATION_START_EVENTS, function(type) {
  13015. removeEventListener(node, type, proxy);
  13016. });
  13017. delete expando.renderProxy;
  13018. }
  13019. node.classList.remove(CSS_RENDER_MONITOR);
  13020. }
  13021. function addResizeListener(node, listener, chart) {
  13022. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  13023. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  13024. var resizer = expando.resizer = createResizer(throttled(function() {
  13025. if (expando.resizer) {
  13026. return listener(createEvent('resize', chart));
  13027. }
  13028. }));
  13029. // The resizer needs to be attached to the node parent, so we first need to be
  13030. // sure that `node` is attached to the DOM before injecting the resizer element.
  13031. watchForRender(node, function() {
  13032. if (expando.resizer) {
  13033. var container = node.parentNode;
  13034. if (container && container !== resizer.parentNode) {
  13035. container.insertBefore(resizer, container.firstChild);
  13036. }
  13037. // The container size might have changed, let's reset the resizer state.
  13038. resizer._reset();
  13039. }
  13040. });
  13041. }
  13042. function removeResizeListener(node) {
  13043. var expando = node[EXPANDO_KEY] || {};
  13044. var resizer = expando.resizer;
  13045. delete expando.resizer;
  13046. unwatchForRender(node);
  13047. if (resizer && resizer.parentNode) {
  13048. resizer.parentNode.removeChild(resizer);
  13049. }
  13050. }
  13051. function injectCSS(platform, css) {
  13052. // http://stackoverflow.com/q/3922139
  13053. var style = platform._style || document.createElement('style');
  13054. if (!platform._style) {
  13055. platform._style = style;
  13056. css = '/* Chart.js */\n' + css;
  13057. style.setAttribute('type', 'text/css');
  13058. document.getElementsByTagName('head')[0].appendChild(style);
  13059. }
  13060. style.appendChild(document.createTextNode(css));
  13061. }
  13062. module.exports = {
  13063. /**
  13064. * This property holds whether this platform is enabled for the current environment.
  13065. * Currently used by platform.js to select the proper implementation.
  13066. * @private
  13067. */
  13068. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  13069. initialize: function() {
  13070. var keyframes = 'from{opacity:0.99}to{opacity:1}';
  13071. injectCSS(this,
  13072. // DOM rendering detection
  13073. // https://davidwalsh.name/detect-node-insertion
  13074. '@-webkit-keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
  13075. '@keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' +
  13076. '.' + CSS_RENDER_MONITOR + '{' +
  13077. '-webkit-animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
  13078. 'animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' +
  13079. '}'
  13080. );
  13081. },
  13082. acquireContext: function(item, config) {
  13083. if (typeof item === 'string') {
  13084. item = document.getElementById(item);
  13085. } else if (item.length) {
  13086. // Support for array based queries (such as jQuery)
  13087. item = item[0];
  13088. }
  13089. if (item && item.canvas) {
  13090. // Support for any object associated to a canvas (including a context2d)
  13091. item = item.canvas;
  13092. }
  13093. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  13094. // method, for example: https://github.com/kkapsner/CanvasBlocker
  13095. // https://github.com/chartjs/Chart.js/issues/2807
  13096. var context = item && item.getContext && item.getContext('2d');
  13097. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  13098. // inside an iframe or when running in a protected environment. We could guess the
  13099. // types from their toString() value but let's keep things flexible and assume it's
  13100. // a sufficient condition if the item has a context2D which has item as `canvas`.
  13101. // https://github.com/chartjs/Chart.js/issues/3887
  13102. // https://github.com/chartjs/Chart.js/issues/4102
  13103. // https://github.com/chartjs/Chart.js/issues/4152
  13104. if (context && context.canvas === item) {
  13105. initCanvas(item, config);
  13106. return context;
  13107. }
  13108. return null;
  13109. },
  13110. releaseContext: function(context) {
  13111. var canvas = context.canvas;
  13112. if (!canvas[EXPANDO_KEY]) {
  13113. return;
  13114. }
  13115. var initial = canvas[EXPANDO_KEY].initial;
  13116. ['height', 'width'].forEach(function(prop) {
  13117. var value = initial[prop];
  13118. if (helpers.isNullOrUndef(value)) {
  13119. canvas.removeAttribute(prop);
  13120. } else {
  13121. canvas.setAttribute(prop, value);
  13122. }
  13123. });
  13124. helpers.each(initial.style || {}, function(value, key) {
  13125. canvas.style[key] = value;
  13126. });
  13127. // The canvas render size might have been changed (and thus the state stack discarded),
  13128. // we can't use save() and restore() to restore the initial state. So make sure that at
  13129. // least the canvas context is reset to the default state by setting the canvas width.
  13130. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  13131. canvas.width = canvas.width;
  13132. delete canvas[EXPANDO_KEY];
  13133. },
  13134. addEventListener: function(chart, type, listener) {
  13135. var canvas = chart.canvas;
  13136. if (type === 'resize') {
  13137. // Note: the resize event is not supported on all browsers.
  13138. addResizeListener(canvas, listener, chart);
  13139. return;
  13140. }
  13141. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  13142. var proxies = expando.proxies || (expando.proxies = {});
  13143. var proxy = proxies[chart.id + '_' + type] = function(event) {
  13144. listener(fromNativeEvent(event, chart));
  13145. };
  13146. addEventListener(canvas, type, proxy);
  13147. },
  13148. removeEventListener: function(chart, type, listener) {
  13149. var canvas = chart.canvas;
  13150. if (type === 'resize') {
  13151. // Note: the resize event is not supported on all browsers.
  13152. removeResizeListener(canvas, listener);
  13153. return;
  13154. }
  13155. var expando = listener[EXPANDO_KEY] || {};
  13156. var proxies = expando.proxies || {};
  13157. var proxy = proxies[chart.id + '_' + type];
  13158. if (!proxy) {
  13159. return;
  13160. }
  13161. removeEventListener(canvas, type, proxy);
  13162. }
  13163. };
  13164. // DEPRECATIONS
  13165. /**
  13166. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  13167. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  13168. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  13169. * @function Chart.helpers.addEvent
  13170. * @deprecated since version 2.7.0
  13171. * @todo remove at version 3
  13172. * @private
  13173. */
  13174. helpers.addEvent = addEventListener;
  13175. /**
  13176. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  13177. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  13178. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  13179. * @function Chart.helpers.removeEvent
  13180. * @deprecated since version 2.7.0
  13181. * @todo remove at version 3
  13182. * @private
  13183. */
  13184. helpers.removeEvent = removeEventListener;
  13185. },{"46":46}],49:[function(require,module,exports){
  13186. 'use strict';
  13187. var helpers = require(46);
  13188. var basic = require(47);
  13189. var dom = require(48);
  13190. // @TODO Make possible to select another platform at build time.
  13191. var implementation = dom._enabled ? dom : basic;
  13192. /**
  13193. * @namespace Chart.platform
  13194. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  13195. * @since 2.4.0
  13196. */
  13197. module.exports = helpers.extend({
  13198. /**
  13199. * @since 2.7.0
  13200. */
  13201. initialize: function() {},
  13202. /**
  13203. * Called at chart construction time, returns a context2d instance implementing
  13204. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  13205. * @param {*} item - The native item from which to acquire context (platform specific)
  13206. * @param {Object} options - The chart options
  13207. * @returns {CanvasRenderingContext2D} context2d instance
  13208. */
  13209. acquireContext: function() {},
  13210. /**
  13211. * Called at chart destruction time, releases any resources associated to the context
  13212. * previously returned by the acquireContext() method.
  13213. * @param {CanvasRenderingContext2D} context - The context2d instance
  13214. * @returns {Boolean} true if the method succeeded, else false
  13215. */
  13216. releaseContext: function() {},
  13217. /**
  13218. * Registers the specified listener on the given chart.
  13219. * @param {Chart} chart - Chart from which to listen for event
  13220. * @param {String} type - The ({@link IEvent}) type to listen for
  13221. * @param {Function} listener - Receives a notification (an object that implements
  13222. * the {@link IEvent} interface) when an event of the specified type occurs.
  13223. */
  13224. addEventListener: function() {},
  13225. /**
  13226. * Removes the specified listener previously registered with addEventListener.
  13227. * @param {Chart} chart -Chart from which to remove the listener
  13228. * @param {String} type - The ({@link IEvent}) type to remove
  13229. * @param {Function} listener - The listener function to remove from the event target.
  13230. */
  13231. removeEventListener: function() {}
  13232. }, implementation);
  13233. /**
  13234. * @interface IPlatform
  13235. * Allows abstracting platform dependencies away from the chart
  13236. * @borrows Chart.platform.acquireContext as acquireContext
  13237. * @borrows Chart.platform.releaseContext as releaseContext
  13238. * @borrows Chart.platform.addEventListener as addEventListener
  13239. * @borrows Chart.platform.removeEventListener as removeEventListener
  13240. */
  13241. /**
  13242. * @interface IEvent
  13243. * @prop {String} type - The event type name, possible values are:
  13244. * 'contextmenu', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseout',
  13245. * 'click', 'dblclick', 'keydown', 'keypress', 'keyup' and 'resize'
  13246. * @prop {*} native - The original native event (null for emulated events, e.g. 'resize')
  13247. * @prop {Number} x - The mouse x position, relative to the canvas (null for incompatible events)
  13248. * @prop {Number} y - The mouse y position, relative to the canvas (null for incompatible events)
  13249. */
  13250. },{"46":46,"47":47,"48":48}],50:[function(require,module,exports){
  13251. 'use strict';
  13252. module.exports = {};
  13253. module.exports.filler = require(51);
  13254. module.exports.legend = require(52);
  13255. module.exports.title = require(53);
  13256. },{"51":51,"52":52,"53":53}],51:[function(require,module,exports){
  13257. /**
  13258. * Plugin based on discussion from the following Chart.js issues:
  13259. * @see https://github.com/chartjs/Chart.js/issues/2380#issuecomment-279961569
  13260. * @see https://github.com/chartjs/Chart.js/issues/2440#issuecomment-256461897
  13261. */
  13262. 'use strict';
  13263. var defaults = require(26);
  13264. var elements = require(41);
  13265. var helpers = require(46);
  13266. defaults._set('global', {
  13267. plugins: {
  13268. filler: {
  13269. propagate: true
  13270. }
  13271. }
  13272. });
  13273. var mappers = {
  13274. dataset: function(source) {
  13275. var index = source.fill;
  13276. var chart = source.chart;
  13277. var meta = chart.getDatasetMeta(index);
  13278. var visible = meta && chart.isDatasetVisible(index);
  13279. var points = (visible && meta.dataset._children) || [];
  13280. var length = points.length || 0;
  13281. return !length ? null : function(point, i) {
  13282. return (i < length && points[i]._view) || null;
  13283. };
  13284. },
  13285. boundary: function(source) {
  13286. var boundary = source.boundary;
  13287. var x = boundary ? boundary.x : null;
  13288. var y = boundary ? boundary.y : null;
  13289. return function(point) {
  13290. return {
  13291. x: x === null ? point.x : x,
  13292. y: y === null ? point.y : y,
  13293. };
  13294. };
  13295. }
  13296. };
  13297. // @todo if (fill[0] === '#')
  13298. function decodeFill(el, index, count) {
  13299. var model = el._model || {};
  13300. var fill = model.fill;
  13301. var target;
  13302. if (fill === undefined) {
  13303. fill = !!model.backgroundColor;
  13304. }
  13305. if (fill === false || fill === null) {
  13306. return false;
  13307. }
  13308. if (fill === true) {
  13309. return 'origin';
  13310. }
  13311. target = parseFloat(fill, 10);
  13312. if (isFinite(target) && Math.floor(target) === target) {
  13313. if (fill[0] === '-' || fill[0] === '+') {
  13314. target = index + target;
  13315. }
  13316. if (target === index || target < 0 || target >= count) {
  13317. return false;
  13318. }
  13319. return target;
  13320. }
  13321. switch (fill) {
  13322. // compatibility
  13323. case 'bottom':
  13324. return 'start';
  13325. case 'top':
  13326. return 'end';
  13327. case 'zero':
  13328. return 'origin';
  13329. // supported boundaries
  13330. case 'origin':
  13331. case 'start':
  13332. case 'end':
  13333. return fill;
  13334. // invalid fill values
  13335. default:
  13336. return false;
  13337. }
  13338. }
  13339. function computeBoundary(source) {
  13340. var model = source.el._model || {};
  13341. var scale = source.el._scale || {};
  13342. var fill = source.fill;
  13343. var target = null;
  13344. var horizontal;
  13345. if (isFinite(fill)) {
  13346. return null;
  13347. }
  13348. // Backward compatibility: until v3, we still need to support boundary values set on
  13349. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  13350. // controllers might still use it (e.g. the Smith chart).
  13351. if (fill === 'start') {
  13352. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  13353. } else if (fill === 'end') {
  13354. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  13355. } else if (model.scaleZero !== undefined) {
  13356. target = model.scaleZero;
  13357. } else if (scale.getBasePosition) {
  13358. target = scale.getBasePosition();
  13359. } else if (scale.getBasePixel) {
  13360. target = scale.getBasePixel();
  13361. }
  13362. if (target !== undefined && target !== null) {
  13363. if (target.x !== undefined && target.y !== undefined) {
  13364. return target;
  13365. }
  13366. if (typeof target === 'number' && isFinite(target)) {
  13367. horizontal = scale.isHorizontal();
  13368. return {
  13369. x: horizontal ? target : null,
  13370. y: horizontal ? null : target
  13371. };
  13372. }
  13373. }
  13374. return null;
  13375. }
  13376. function resolveTarget(sources, index, propagate) {
  13377. var source = sources[index];
  13378. var fill = source.fill;
  13379. var visited = [index];
  13380. var target;
  13381. if (!propagate) {
  13382. return fill;
  13383. }
  13384. while (fill !== false && visited.indexOf(fill) === -1) {
  13385. if (!isFinite(fill)) {
  13386. return fill;
  13387. }
  13388. target = sources[fill];
  13389. if (!target) {
  13390. return false;
  13391. }
  13392. if (target.visible) {
  13393. return fill;
  13394. }
  13395. visited.push(fill);
  13396. fill = target.fill;
  13397. }
  13398. return false;
  13399. }
  13400. function createMapper(source) {
  13401. var fill = source.fill;
  13402. var type = 'dataset';
  13403. if (fill === false) {
  13404. return null;
  13405. }
  13406. if (!isFinite(fill)) {
  13407. type = 'boundary';
  13408. }
  13409. return mappers[type](source);
  13410. }
  13411. function isDrawable(point) {
  13412. return point && !point.skip;
  13413. }
  13414. function drawArea(ctx, curve0, curve1, len0, len1) {
  13415. var i;
  13416. if (!len0 || !len1) {
  13417. return;
  13418. }
  13419. // building first area curve (normal)
  13420. ctx.moveTo(curve0[0].x, curve0[0].y);
  13421. for (i = 1; i < len0; ++i) {
  13422. helpers.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  13423. }
  13424. // joining the two area curves
  13425. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  13426. // building opposite area curve (reverse)
  13427. for (i = len1 - 1; i > 0; --i) {
  13428. helpers.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  13429. }
  13430. }
  13431. function doFill(ctx, points, mapper, view, color, loop) {
  13432. var count = points.length;
  13433. var span = view.spanGaps;
  13434. var curve0 = [];
  13435. var curve1 = [];
  13436. var len0 = 0;
  13437. var len1 = 0;
  13438. var i, ilen, index, p0, p1, d0, d1;
  13439. ctx.beginPath();
  13440. for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {
  13441. index = i % count;
  13442. p0 = points[index]._view;
  13443. p1 = mapper(p0, index, view);
  13444. d0 = isDrawable(p0);
  13445. d1 = isDrawable(p1);
  13446. if (d0 && d1) {
  13447. len0 = curve0.push(p0);
  13448. len1 = curve1.push(p1);
  13449. } else if (len0 && len1) {
  13450. if (!span) {
  13451. drawArea(ctx, curve0, curve1, len0, len1);
  13452. len0 = len1 = 0;
  13453. curve0 = [];
  13454. curve1 = [];
  13455. } else {
  13456. if (d0) {
  13457. curve0.push(p0);
  13458. }
  13459. if (d1) {
  13460. curve1.push(p1);
  13461. }
  13462. }
  13463. }
  13464. }
  13465. drawArea(ctx, curve0, curve1, len0, len1);
  13466. ctx.closePath();
  13467. ctx.fillStyle = color;
  13468. ctx.fill();
  13469. }
  13470. module.exports = {
  13471. id: 'filler',
  13472. afterDatasetsUpdate: function(chart, options) {
  13473. var count = (chart.data.datasets || []).length;
  13474. var propagate = options.propagate;
  13475. var sources = [];
  13476. var meta, i, el, source;
  13477. for (i = 0; i < count; ++i) {
  13478. meta = chart.getDatasetMeta(i);
  13479. el = meta.dataset;
  13480. source = null;
  13481. if (el && el._model && el instanceof elements.Line) {
  13482. source = {
  13483. visible: chart.isDatasetVisible(i),
  13484. fill: decodeFill(el, i, count),
  13485. chart: chart,
  13486. el: el
  13487. };
  13488. }
  13489. meta.$filler = source;
  13490. sources.push(source);
  13491. }
  13492. for (i = 0; i < count; ++i) {
  13493. source = sources[i];
  13494. if (!source) {
  13495. continue;
  13496. }
  13497. source.fill = resolveTarget(sources, i, propagate);
  13498. source.boundary = computeBoundary(source);
  13499. source.mapper = createMapper(source);
  13500. }
  13501. },
  13502. beforeDatasetDraw: function(chart, args) {
  13503. var meta = args.meta.$filler;
  13504. if (!meta) {
  13505. return;
  13506. }
  13507. var ctx = chart.ctx;
  13508. var el = meta.el;
  13509. var view = el._view;
  13510. var points = el._children || [];
  13511. var mapper = meta.mapper;
  13512. var color = view.backgroundColor || defaults.global.defaultColor;
  13513. if (mapper && color && points.length) {
  13514. helpers.canvas.clipArea(ctx, chart.chartArea);
  13515. doFill(ctx, points, mapper, view, color, el._loop);
  13516. helpers.canvas.unclipArea(ctx);
  13517. }
  13518. }
  13519. };
  13520. },{"26":26,"41":41,"46":46}],52:[function(require,module,exports){
  13521. 'use strict';
  13522. var defaults = require(26);
  13523. var Element = require(27);
  13524. var helpers = require(46);
  13525. var layouts = require(31);
  13526. var noop = helpers.noop;
  13527. defaults._set('global', {
  13528. legend: {
  13529. display: true,
  13530. position: 'top',
  13531. fullWidth: true,
  13532. reverse: false,
  13533. weight: 1000,
  13534. // a callback that will handle
  13535. onClick: function(e, legendItem) {
  13536. var index = legendItem.datasetIndex;
  13537. var ci = this.chart;
  13538. var meta = ci.getDatasetMeta(index);
  13539. // See controller.isDatasetVisible comment
  13540. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  13541. // We hid a dataset ... rerender the chart
  13542. ci.update();
  13543. },
  13544. onHover: null,
  13545. labels: {
  13546. boxWidth: 40,
  13547. padding: 10,
  13548. // Generates labels shown in the legend
  13549. // Valid properties to return:
  13550. // text : text to display
  13551. // fillStyle : fill of coloured box
  13552. // strokeStyle: stroke of coloured box
  13553. // hidden : if this legend item refers to a hidden item
  13554. // lineCap : cap style for line
  13555. // lineDash
  13556. // lineDashOffset :
  13557. // lineJoin :
  13558. // lineWidth :
  13559. generateLabels: function(chart) {
  13560. var data = chart.data;
  13561. return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
  13562. return {
  13563. text: dataset.label,
  13564. fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
  13565. hidden: !chart.isDatasetVisible(i),
  13566. lineCap: dataset.borderCapStyle,
  13567. lineDash: dataset.borderDash,
  13568. lineDashOffset: dataset.borderDashOffset,
  13569. lineJoin: dataset.borderJoinStyle,
  13570. lineWidth: dataset.borderWidth,
  13571. strokeStyle: dataset.borderColor,
  13572. pointStyle: dataset.pointStyle,
  13573. // Below is extra data used for toggling the datasets
  13574. datasetIndex: i
  13575. };
  13576. }, this) : [];
  13577. }
  13578. }
  13579. },
  13580. legendCallback: function(chart) {
  13581. var text = [];
  13582. text.push('<ul class="' + chart.id + '-legend">');
  13583. for (var i = 0; i < chart.data.datasets.length; i++) {
  13584. text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
  13585. if (chart.data.datasets[i].label) {
  13586. text.push(chart.data.datasets[i].label);
  13587. }
  13588. text.push('</li>');
  13589. }
  13590. text.push('</ul>');
  13591. return text.join('');
  13592. }
  13593. });
  13594. /**
  13595. * Helper function to get the box width based on the usePointStyle option
  13596. * @param labelopts {Object} the label options on the legend
  13597. * @param fontSize {Number} the label font size
  13598. * @return {Number} width of the color box area
  13599. */
  13600. function getBoxWidth(labelOpts, fontSize) {
  13601. return labelOpts.usePointStyle ?
  13602. fontSize * Math.SQRT2 :
  13603. labelOpts.boxWidth;
  13604. }
  13605. /**
  13606. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  13607. */
  13608. var Legend = Element.extend({
  13609. initialize: function(config) {
  13610. helpers.extend(this, config);
  13611. // Contains hit boxes for each dataset (in dataset order)
  13612. this.legendHitBoxes = [];
  13613. // Are we in doughnut mode which has a different data type
  13614. this.doughnutMode = false;
  13615. },
  13616. // These methods are ordered by lifecycle. Utilities then follow.
  13617. // Any function defined here is inherited by all legend types.
  13618. // Any function can be extended by the legend type
  13619. beforeUpdate: noop,
  13620. update: function(maxWidth, maxHeight, margins) {
  13621. var me = this;
  13622. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  13623. me.beforeUpdate();
  13624. // Absorb the master measurements
  13625. me.maxWidth = maxWidth;
  13626. me.maxHeight = maxHeight;
  13627. me.margins = margins;
  13628. // Dimensions
  13629. me.beforeSetDimensions();
  13630. me.setDimensions();
  13631. me.afterSetDimensions();
  13632. // Labels
  13633. me.beforeBuildLabels();
  13634. me.buildLabels();
  13635. me.afterBuildLabels();
  13636. // Fit
  13637. me.beforeFit();
  13638. me.fit();
  13639. me.afterFit();
  13640. //
  13641. me.afterUpdate();
  13642. return me.minSize;
  13643. },
  13644. afterUpdate: noop,
  13645. //
  13646. beforeSetDimensions: noop,
  13647. setDimensions: function() {
  13648. var me = this;
  13649. // Set the unconstrained dimension before label rotation
  13650. if (me.isHorizontal()) {
  13651. // Reset position before calculating rotation
  13652. me.width = me.maxWidth;
  13653. me.left = 0;
  13654. me.right = me.width;
  13655. } else {
  13656. me.height = me.maxHeight;
  13657. // Reset position before calculating rotation
  13658. me.top = 0;
  13659. me.bottom = me.height;
  13660. }
  13661. // Reset padding
  13662. me.paddingLeft = 0;
  13663. me.paddingTop = 0;
  13664. me.paddingRight = 0;
  13665. me.paddingBottom = 0;
  13666. // Reset minSize
  13667. me.minSize = {
  13668. width: 0,
  13669. height: 0
  13670. };
  13671. },
  13672. afterSetDimensions: noop,
  13673. //
  13674. beforeBuildLabels: noop,
  13675. buildLabels: function() {
  13676. var me = this;
  13677. var labelOpts = me.options.labels || {};
  13678. var legendItems = helpers.callback(labelOpts.generateLabels, [me.chart], me) || [];
  13679. if (labelOpts.filter) {
  13680. legendItems = legendItems.filter(function(item) {
  13681. return labelOpts.filter(item, me.chart.data);
  13682. });
  13683. }
  13684. if (me.options.reverse) {
  13685. legendItems.reverse();
  13686. }
  13687. me.legendItems = legendItems;
  13688. },
  13689. afterBuildLabels: noop,
  13690. //
  13691. beforeFit: noop,
  13692. fit: function() {
  13693. var me = this;
  13694. var opts = me.options;
  13695. var labelOpts = opts.labels;
  13696. var display = opts.display;
  13697. var ctx = me.ctx;
  13698. var globalDefault = defaults.global;
  13699. var valueOrDefault = helpers.valueOrDefault;
  13700. var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);
  13701. var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);
  13702. var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);
  13703. var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
  13704. // Reset hit boxes
  13705. var hitboxes = me.legendHitBoxes = [];
  13706. var minSize = me.minSize;
  13707. var isHorizontal = me.isHorizontal();
  13708. if (isHorizontal) {
  13709. minSize.width = me.maxWidth; // fill all the width
  13710. minSize.height = display ? 10 : 0;
  13711. } else {
  13712. minSize.width = display ? 10 : 0;
  13713. minSize.height = me.maxHeight; // fill all the height
  13714. }
  13715. // Increase sizes here
  13716. if (display) {
  13717. ctx.font = labelFont;
  13718. if (isHorizontal) {
  13719. // Labels
  13720. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  13721. var lineWidths = me.lineWidths = [0];
  13722. var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0;
  13723. ctx.textAlign = 'left';
  13724. ctx.textBaseline = 'top';
  13725. helpers.each(me.legendItems, function(legendItem, i) {
  13726. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13727. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  13728. if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) {
  13729. totalHeight += fontSize + (labelOpts.padding);
  13730. lineWidths[lineWidths.length] = me.left;
  13731. }
  13732. // Store the hitbox width and height here. Final position will be updated in `draw`
  13733. hitboxes[i] = {
  13734. left: 0,
  13735. top: 0,
  13736. width: width,
  13737. height: fontSize
  13738. };
  13739. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  13740. });
  13741. minSize.height += totalHeight;
  13742. } else {
  13743. var vPadding = labelOpts.padding;
  13744. var columnWidths = me.columnWidths = [];
  13745. var totalWidth = labelOpts.padding;
  13746. var currentColWidth = 0;
  13747. var currentColHeight = 0;
  13748. var itemHeight = fontSize + vPadding;
  13749. helpers.each(me.legendItems, function(legendItem, i) {
  13750. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13751. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  13752. // If too tall, go to new column
  13753. if (currentColHeight + itemHeight > minSize.height) {
  13754. totalWidth += currentColWidth + labelOpts.padding;
  13755. columnWidths.push(currentColWidth); // previous column width
  13756. currentColWidth = 0;
  13757. currentColHeight = 0;
  13758. }
  13759. // Get max width
  13760. currentColWidth = Math.max(currentColWidth, itemWidth);
  13761. currentColHeight += itemHeight;
  13762. // Store the hitbox width and height here. Final position will be updated in `draw`
  13763. hitboxes[i] = {
  13764. left: 0,
  13765. top: 0,
  13766. width: itemWidth,
  13767. height: fontSize
  13768. };
  13769. });
  13770. totalWidth += currentColWidth;
  13771. columnWidths.push(currentColWidth);
  13772. minSize.width += totalWidth;
  13773. }
  13774. }
  13775. me.width = minSize.width;
  13776. me.height = minSize.height;
  13777. },
  13778. afterFit: noop,
  13779. // Shared Methods
  13780. isHorizontal: function() {
  13781. return this.options.position === 'top' || this.options.position === 'bottom';
  13782. },
  13783. // Actually draw the legend on the canvas
  13784. draw: function() {
  13785. var me = this;
  13786. var opts = me.options;
  13787. var labelOpts = opts.labels;
  13788. var globalDefault = defaults.global;
  13789. var lineDefault = globalDefault.elements.line;
  13790. var legendWidth = me.width;
  13791. var lineWidths = me.lineWidths;
  13792. if (opts.display) {
  13793. var ctx = me.ctx;
  13794. var valueOrDefault = helpers.valueOrDefault;
  13795. var fontColor = valueOrDefault(labelOpts.fontColor, globalDefault.defaultFontColor);
  13796. var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize);
  13797. var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle);
  13798. var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily);
  13799. var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
  13800. var cursor;
  13801. // Canvas setup
  13802. ctx.textAlign = 'left';
  13803. ctx.textBaseline = 'middle';
  13804. ctx.lineWidth = 0.5;
  13805. ctx.strokeStyle = fontColor; // for strikethrough effect
  13806. ctx.fillStyle = fontColor; // render in correct colour
  13807. ctx.font = labelFont;
  13808. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13809. var hitboxes = me.legendHitBoxes;
  13810. // current position
  13811. var drawLegendBox = function(x, y, legendItem) {
  13812. if (isNaN(boxWidth) || boxWidth <= 0) {
  13813. return;
  13814. }
  13815. // Set the ctx for the box
  13816. ctx.save();
  13817. ctx.fillStyle = valueOrDefault(legendItem.fillStyle, globalDefault.defaultColor);
  13818. ctx.lineCap = valueOrDefault(legendItem.lineCap, lineDefault.borderCapStyle);
  13819. ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  13820. ctx.lineJoin = valueOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle);
  13821. ctx.lineWidth = valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth);
  13822. ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, globalDefault.defaultColor);
  13823. var isLineWidthZero = (valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth) === 0);
  13824. if (ctx.setLineDash) {
  13825. // IE 9 and 10 do not support line dash
  13826. ctx.setLineDash(valueOrDefault(legendItem.lineDash, lineDefault.borderDash));
  13827. }
  13828. if (opts.labels && opts.labels.usePointStyle) {
  13829. // Recalculate x and y for drawPoint() because its expecting
  13830. // x and y to be center of figure (instead of top left)
  13831. var radius = fontSize * Math.SQRT2 / 2;
  13832. var offSet = radius / Math.SQRT2;
  13833. var centerX = x + offSet;
  13834. var centerY = y + offSet;
  13835. // Draw pointStyle as legend symbol
  13836. helpers.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
  13837. } else {
  13838. // Draw box as legend symbol
  13839. if (!isLineWidthZero) {
  13840. ctx.strokeRect(x, y, boxWidth, fontSize);
  13841. }
  13842. ctx.fillRect(x, y, boxWidth, fontSize);
  13843. }
  13844. ctx.restore();
  13845. };
  13846. var fillText = function(x, y, legendItem, textWidth) {
  13847. var halfFontSize = fontSize / 2;
  13848. var xLeft = boxWidth + halfFontSize + x;
  13849. var yMiddle = y + halfFontSize;
  13850. ctx.fillText(legendItem.text, xLeft, yMiddle);
  13851. if (legendItem.hidden) {
  13852. // Strikethrough the text if hidden
  13853. ctx.beginPath();
  13854. ctx.lineWidth = 2;
  13855. ctx.moveTo(xLeft, yMiddle);
  13856. ctx.lineTo(xLeft + textWidth, yMiddle);
  13857. ctx.stroke();
  13858. }
  13859. };
  13860. // Horizontal
  13861. var isHorizontal = me.isHorizontal();
  13862. if (isHorizontal) {
  13863. cursor = {
  13864. x: me.left + ((legendWidth - lineWidths[0]) / 2),
  13865. y: me.top + labelOpts.padding,
  13866. line: 0
  13867. };
  13868. } else {
  13869. cursor = {
  13870. x: me.left + labelOpts.padding,
  13871. y: me.top + labelOpts.padding,
  13872. line: 0
  13873. };
  13874. }
  13875. var itemHeight = fontSize + labelOpts.padding;
  13876. helpers.each(me.legendItems, function(legendItem, i) {
  13877. var textWidth = ctx.measureText(legendItem.text).width;
  13878. var width = boxWidth + (fontSize / 2) + textWidth;
  13879. var x = cursor.x;
  13880. var y = cursor.y;
  13881. if (isHorizontal) {
  13882. if (x + width >= legendWidth) {
  13883. y = cursor.y += itemHeight;
  13884. cursor.line++;
  13885. x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2);
  13886. }
  13887. } else if (y + itemHeight > me.bottom) {
  13888. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  13889. y = cursor.y = me.top + labelOpts.padding;
  13890. cursor.line++;
  13891. }
  13892. drawLegendBox(x, y, legendItem);
  13893. hitboxes[i].left = x;
  13894. hitboxes[i].top = y;
  13895. // Fill the actual label
  13896. fillText(x, y, legendItem, textWidth);
  13897. if (isHorizontal) {
  13898. cursor.x += width + (labelOpts.padding);
  13899. } else {
  13900. cursor.y += itemHeight;
  13901. }
  13902. });
  13903. }
  13904. },
  13905. /**
  13906. * Handle an event
  13907. * @private
  13908. * @param {IEvent} event - The event to handle
  13909. * @return {Boolean} true if a change occured
  13910. */
  13911. handleEvent: function(e) {
  13912. var me = this;
  13913. var opts = me.options;
  13914. var type = e.type === 'mouseup' ? 'click' : e.type;
  13915. var changed = false;
  13916. if (type === 'mousemove') {
  13917. if (!opts.onHover) {
  13918. return;
  13919. }
  13920. } else if (type === 'click') {
  13921. if (!opts.onClick) {
  13922. return;
  13923. }
  13924. } else {
  13925. return;
  13926. }
  13927. // Chart event already has relative position in it
  13928. var x = e.x;
  13929. var y = e.y;
  13930. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  13931. // See if we are touching one of the dataset boxes
  13932. var lh = me.legendHitBoxes;
  13933. for (var i = 0; i < lh.length; ++i) {
  13934. var hitBox = lh[i];
  13935. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  13936. // Touching an element
  13937. if (type === 'click') {
  13938. // use e.native for backwards compatibility
  13939. opts.onClick.call(me, e.native, me.legendItems[i]);
  13940. changed = true;
  13941. break;
  13942. } else if (type === 'mousemove') {
  13943. // use e.native for backwards compatibility
  13944. opts.onHover.call(me, e.native, me.legendItems[i]);
  13945. changed = true;
  13946. break;
  13947. }
  13948. }
  13949. }
  13950. }
  13951. return changed;
  13952. }
  13953. });
  13954. function createNewLegendAndAttach(chart, legendOpts) {
  13955. var legend = new Legend({
  13956. ctx: chart.ctx,
  13957. options: legendOpts,
  13958. chart: chart
  13959. });
  13960. layouts.configure(chart, legend, legendOpts);
  13961. layouts.addBox(chart, legend);
  13962. chart.legend = legend;
  13963. }
  13964. module.exports = {
  13965. id: 'legend',
  13966. /**
  13967. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  13968. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  13969. * the plugin, which one will be re-exposed in the chart.js file.
  13970. * https://github.com/chartjs/Chart.js/pull/2640
  13971. * @private
  13972. */
  13973. _element: Legend,
  13974. beforeInit: function(chart) {
  13975. var legendOpts = chart.options.legend;
  13976. if (legendOpts) {
  13977. createNewLegendAndAttach(chart, legendOpts);
  13978. }
  13979. },
  13980. beforeUpdate: function(chart) {
  13981. var legendOpts = chart.options.legend;
  13982. var legend = chart.legend;
  13983. if (legendOpts) {
  13984. helpers.mergeIf(legendOpts, defaults.global.legend);
  13985. if (legend) {
  13986. layouts.configure(chart, legend, legendOpts);
  13987. legend.options = legendOpts;
  13988. } else {
  13989. createNewLegendAndAttach(chart, legendOpts);
  13990. }
  13991. } else if (legend) {
  13992. layouts.removeBox(chart, legend);
  13993. delete chart.legend;
  13994. }
  13995. },
  13996. afterEvent: function(chart, e) {
  13997. var legend = chart.legend;
  13998. if (legend) {
  13999. legend.handleEvent(e);
  14000. }
  14001. }
  14002. };
  14003. },{"26":26,"27":27,"31":31,"46":46}],53:[function(require,module,exports){
  14004. 'use strict';
  14005. var defaults = require(26);
  14006. var Element = require(27);
  14007. var helpers = require(46);
  14008. var layouts = require(31);
  14009. var noop = helpers.noop;
  14010. defaults._set('global', {
  14011. title: {
  14012. display: false,
  14013. fontStyle: 'bold',
  14014. fullWidth: true,
  14015. lineHeight: 1.2,
  14016. padding: 10,
  14017. position: 'top',
  14018. text: '',
  14019. weight: 2000 // by default greater than legend (1000) to be above
  14020. }
  14021. });
  14022. /**
  14023. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  14024. */
  14025. var Title = Element.extend({
  14026. initialize: function(config) {
  14027. var me = this;
  14028. helpers.extend(me, config);
  14029. // Contains hit boxes for each dataset (in dataset order)
  14030. me.legendHitBoxes = [];
  14031. },
  14032. // These methods are ordered by lifecycle. Utilities then follow.
  14033. beforeUpdate: noop,
  14034. update: function(maxWidth, maxHeight, margins) {
  14035. var me = this;
  14036. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  14037. me.beforeUpdate();
  14038. // Absorb the master measurements
  14039. me.maxWidth = maxWidth;
  14040. me.maxHeight = maxHeight;
  14041. me.margins = margins;
  14042. // Dimensions
  14043. me.beforeSetDimensions();
  14044. me.setDimensions();
  14045. me.afterSetDimensions();
  14046. // Labels
  14047. me.beforeBuildLabels();
  14048. me.buildLabels();
  14049. me.afterBuildLabels();
  14050. // Fit
  14051. me.beforeFit();
  14052. me.fit();
  14053. me.afterFit();
  14054. //
  14055. me.afterUpdate();
  14056. return me.minSize;
  14057. },
  14058. afterUpdate: noop,
  14059. //
  14060. beforeSetDimensions: noop,
  14061. setDimensions: function() {
  14062. var me = this;
  14063. // Set the unconstrained dimension before label rotation
  14064. if (me.isHorizontal()) {
  14065. // Reset position before calculating rotation
  14066. me.width = me.maxWidth;
  14067. me.left = 0;
  14068. me.right = me.width;
  14069. } else {
  14070. me.height = me.maxHeight;
  14071. // Reset position before calculating rotation
  14072. me.top = 0;
  14073. me.bottom = me.height;
  14074. }
  14075. // Reset padding
  14076. me.paddingLeft = 0;
  14077. me.paddingTop = 0;
  14078. me.paddingRight = 0;
  14079. me.paddingBottom = 0;
  14080. // Reset minSize
  14081. me.minSize = {
  14082. width: 0,
  14083. height: 0
  14084. };
  14085. },
  14086. afterSetDimensions: noop,
  14087. //
  14088. beforeBuildLabels: noop,
  14089. buildLabels: noop,
  14090. afterBuildLabels: noop,
  14091. //
  14092. beforeFit: noop,
  14093. fit: function() {
  14094. var me = this;
  14095. var valueOrDefault = helpers.valueOrDefault;
  14096. var opts = me.options;
  14097. var display = opts.display;
  14098. var fontSize = valueOrDefault(opts.fontSize, defaults.global.defaultFontSize);
  14099. var minSize = me.minSize;
  14100. var lineCount = helpers.isArray(opts.text) ? opts.text.length : 1;
  14101. var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);
  14102. var textSize = display ? (lineCount * lineHeight) + (opts.padding * 2) : 0;
  14103. if (me.isHorizontal()) {
  14104. minSize.width = me.maxWidth; // fill all the width
  14105. minSize.height = textSize;
  14106. } else {
  14107. minSize.width = textSize;
  14108. minSize.height = me.maxHeight; // fill all the height
  14109. }
  14110. me.width = minSize.width;
  14111. me.height = minSize.height;
  14112. },
  14113. afterFit: noop,
  14114. // Shared Methods
  14115. isHorizontal: function() {
  14116. var pos = this.options.position;
  14117. return pos === 'top' || pos === 'bottom';
  14118. },
  14119. // Actually draw the title block on the canvas
  14120. draw: function() {
  14121. var me = this;
  14122. var ctx = me.ctx;
  14123. var valueOrDefault = helpers.valueOrDefault;
  14124. var opts = me.options;
  14125. var globalDefaults = defaults.global;
  14126. if (opts.display) {
  14127. var fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize);
  14128. var fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle);
  14129. var fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily);
  14130. var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily);
  14131. var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize);
  14132. var offset = lineHeight / 2 + opts.padding;
  14133. var rotation = 0;
  14134. var top = me.top;
  14135. var left = me.left;
  14136. var bottom = me.bottom;
  14137. var right = me.right;
  14138. var maxWidth, titleX, titleY;
  14139. ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour
  14140. ctx.font = titleFont;
  14141. // Horizontal
  14142. if (me.isHorizontal()) {
  14143. titleX = left + ((right - left) / 2); // midpoint of the width
  14144. titleY = top + offset;
  14145. maxWidth = right - left;
  14146. } else {
  14147. titleX = opts.position === 'left' ? left + offset : right - offset;
  14148. titleY = top + ((bottom - top) / 2);
  14149. maxWidth = bottom - top;
  14150. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  14151. }
  14152. ctx.save();
  14153. ctx.translate(titleX, titleY);
  14154. ctx.rotate(rotation);
  14155. ctx.textAlign = 'center';
  14156. ctx.textBaseline = 'middle';
  14157. var text = opts.text;
  14158. if (helpers.isArray(text)) {
  14159. var y = 0;
  14160. for (var i = 0; i < text.length; ++i) {
  14161. ctx.fillText(text[i], 0, y, maxWidth);
  14162. y += lineHeight;
  14163. }
  14164. } else {
  14165. ctx.fillText(text, 0, 0, maxWidth);
  14166. }
  14167. ctx.restore();
  14168. }
  14169. }
  14170. });
  14171. function createNewTitleBlockAndAttach(chart, titleOpts) {
  14172. var title = new Title({
  14173. ctx: chart.ctx,
  14174. options: titleOpts,
  14175. chart: chart
  14176. });
  14177. layouts.configure(chart, title, titleOpts);
  14178. layouts.addBox(chart, title);
  14179. chart.titleBlock = title;
  14180. }
  14181. module.exports = {
  14182. id: 'title',
  14183. /**
  14184. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  14185. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  14186. * the plugin, which one will be re-exposed in the chart.js file.
  14187. * https://github.com/chartjs/Chart.js/pull/2640
  14188. * @private
  14189. */
  14190. _element: Title,
  14191. beforeInit: function(chart) {
  14192. var titleOpts = chart.options.title;
  14193. if (titleOpts) {
  14194. createNewTitleBlockAndAttach(chart, titleOpts);
  14195. }
  14196. },
  14197. beforeUpdate: function(chart) {
  14198. var titleOpts = chart.options.title;
  14199. var titleBlock = chart.titleBlock;
  14200. if (titleOpts) {
  14201. helpers.mergeIf(titleOpts, defaults.global.title);
  14202. if (titleBlock) {
  14203. layouts.configure(chart, titleBlock, titleOpts);
  14204. titleBlock.options = titleOpts;
  14205. } else {
  14206. createNewTitleBlockAndAttach(chart, titleOpts);
  14207. }
  14208. } else if (titleBlock) {
  14209. layouts.removeBox(chart, titleBlock);
  14210. delete chart.titleBlock;
  14211. }
  14212. }
  14213. };
  14214. },{"26":26,"27":27,"31":31,"46":46}],54:[function(require,module,exports){
  14215. 'use strict';
  14216. var Scale = require(33);
  14217. var scaleService = require(34);
  14218. module.exports = function() {
  14219. // Default config for a category scale
  14220. var defaultConfig = {
  14221. position: 'bottom'
  14222. };
  14223. var DatasetScale = Scale.extend({
  14224. /**
  14225. * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those
  14226. * else fall back to data.labels
  14227. * @private
  14228. */
  14229. getLabels: function() {
  14230. var data = this.chart.data;
  14231. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;
  14232. },
  14233. determineDataLimits: function() {
  14234. var me = this;
  14235. var labels = me.getLabels();
  14236. me.minIndex = 0;
  14237. me.maxIndex = labels.length - 1;
  14238. var findIndex;
  14239. if (me.options.ticks.min !== undefined) {
  14240. // user specified min value
  14241. findIndex = labels.indexOf(me.options.ticks.min);
  14242. me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
  14243. }
  14244. if (me.options.ticks.max !== undefined) {
  14245. // user specified max value
  14246. findIndex = labels.indexOf(me.options.ticks.max);
  14247. me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
  14248. }
  14249. me.min = labels[me.minIndex];
  14250. me.max = labels[me.maxIndex];
  14251. },
  14252. buildTicks: function() {
  14253. var me = this;
  14254. var labels = me.getLabels();
  14255. // If we are viewing some subset of labels, slice the original array
  14256. me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);
  14257. },
  14258. getLabelForIndex: function(index, datasetIndex) {
  14259. var me = this;
  14260. var data = me.chart.data;
  14261. var isHorizontal = me.isHorizontal();
  14262. if (data.yLabels && !isHorizontal) {
  14263. return me.getRightValue(data.datasets[datasetIndex].data[index]);
  14264. }
  14265. return me.ticks[index - me.minIndex];
  14266. },
  14267. // Used to get data value locations. Value can either be an index or a numerical value
  14268. getPixelForValue: function(value, index) {
  14269. var me = this;
  14270. var offset = me.options.offset;
  14271. // 1 is added because we need the length but we have the indexes
  14272. var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1);
  14273. // If value is a data object, then index is the index in the data array,
  14274. // not the index of the scale. We need to change that.
  14275. var valueCategory;
  14276. if (value !== undefined && value !== null) {
  14277. valueCategory = me.isHorizontal() ? value.x : value.y;
  14278. }
  14279. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  14280. var labels = me.getLabels();
  14281. value = valueCategory || value;
  14282. var idx = labels.indexOf(value);
  14283. index = idx !== -1 ? idx : index;
  14284. }
  14285. if (me.isHorizontal()) {
  14286. var valueWidth = me.width / offsetAmt;
  14287. var widthOffset = (valueWidth * (index - me.minIndex));
  14288. if (offset) {
  14289. widthOffset += (valueWidth / 2);
  14290. }
  14291. return me.left + Math.round(widthOffset);
  14292. }
  14293. var valueHeight = me.height / offsetAmt;
  14294. var heightOffset = (valueHeight * (index - me.minIndex));
  14295. if (offset) {
  14296. heightOffset += (valueHeight / 2);
  14297. }
  14298. return me.top + Math.round(heightOffset);
  14299. },
  14300. getPixelForTick: function(index) {
  14301. return this.getPixelForValue(this.ticks[index], index + this.minIndex, null);
  14302. },
  14303. getValueForPixel: function(pixel) {
  14304. var me = this;
  14305. var offset = me.options.offset;
  14306. var value;
  14307. var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
  14308. var horz = me.isHorizontal();
  14309. var valueDimension = (horz ? me.width : me.height) / offsetAmt;
  14310. pixel -= horz ? me.left : me.top;
  14311. if (offset) {
  14312. pixel -= (valueDimension / 2);
  14313. }
  14314. if (pixel <= 0) {
  14315. value = 0;
  14316. } else {
  14317. value = Math.round(pixel / valueDimension);
  14318. }
  14319. return value + me.minIndex;
  14320. },
  14321. getBasePixel: function() {
  14322. return this.bottom;
  14323. }
  14324. });
  14325. scaleService.registerScaleType('category', DatasetScale, defaultConfig);
  14326. };
  14327. },{"33":33,"34":34}],55:[function(require,module,exports){
  14328. 'use strict';
  14329. var defaults = require(26);
  14330. var helpers = require(46);
  14331. var scaleService = require(34);
  14332. var Ticks = require(35);
  14333. module.exports = function(Chart) {
  14334. var defaultConfig = {
  14335. position: 'left',
  14336. ticks: {
  14337. callback: Ticks.formatters.linear
  14338. }
  14339. };
  14340. var LinearScale = Chart.LinearScaleBase.extend({
  14341. determineDataLimits: function() {
  14342. var me = this;
  14343. var opts = me.options;
  14344. var chart = me.chart;
  14345. var data = chart.data;
  14346. var datasets = data.datasets;
  14347. var isHorizontal = me.isHorizontal();
  14348. var DEFAULT_MIN = 0;
  14349. var DEFAULT_MAX = 1;
  14350. function IDMatches(meta) {
  14351. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  14352. }
  14353. // First Calculate the range
  14354. me.min = null;
  14355. me.max = null;
  14356. var hasStacks = opts.stacked;
  14357. if (hasStacks === undefined) {
  14358. helpers.each(datasets, function(dataset, datasetIndex) {
  14359. if (hasStacks) {
  14360. return;
  14361. }
  14362. var meta = chart.getDatasetMeta(datasetIndex);
  14363. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  14364. meta.stack !== undefined) {
  14365. hasStacks = true;
  14366. }
  14367. });
  14368. }
  14369. if (opts.stacked || hasStacks) {
  14370. var valuesPerStack = {};
  14371. helpers.each(datasets, function(dataset, datasetIndex) {
  14372. var meta = chart.getDatasetMeta(datasetIndex);
  14373. var key = [
  14374. meta.type,
  14375. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  14376. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  14377. meta.stack
  14378. ].join('.');
  14379. if (valuesPerStack[key] === undefined) {
  14380. valuesPerStack[key] = {
  14381. positiveValues: [],
  14382. negativeValues: []
  14383. };
  14384. }
  14385. // Store these per type
  14386. var positiveValues = valuesPerStack[key].positiveValues;
  14387. var negativeValues = valuesPerStack[key].negativeValues;
  14388. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  14389. helpers.each(dataset.data, function(rawValue, index) {
  14390. var value = +me.getRightValue(rawValue);
  14391. if (isNaN(value) || meta.data[index].hidden) {
  14392. return;
  14393. }
  14394. positiveValues[index] = positiveValues[index] || 0;
  14395. negativeValues[index] = negativeValues[index] || 0;
  14396. if (opts.relativePoints) {
  14397. positiveValues[index] = 100;
  14398. } else if (value < 0) {
  14399. negativeValues[index] += value;
  14400. } else {
  14401. positiveValues[index] += value;
  14402. }
  14403. });
  14404. }
  14405. });
  14406. helpers.each(valuesPerStack, function(valuesForType) {
  14407. var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
  14408. var minVal = helpers.min(values);
  14409. var maxVal = helpers.max(values);
  14410. me.min = me.min === null ? minVal : Math.min(me.min, minVal);
  14411. me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
  14412. });
  14413. } else {
  14414. helpers.each(datasets, function(dataset, datasetIndex) {
  14415. var meta = chart.getDatasetMeta(datasetIndex);
  14416. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  14417. helpers.each(dataset.data, function(rawValue, index) {
  14418. var value = +me.getRightValue(rawValue);
  14419. if (isNaN(value) || meta.data[index].hidden) {
  14420. return;
  14421. }
  14422. if (me.min === null) {
  14423. me.min = value;
  14424. } else if (value < me.min) {
  14425. me.min = value;
  14426. }
  14427. if (me.max === null) {
  14428. me.max = value;
  14429. } else if (value > me.max) {
  14430. me.max = value;
  14431. }
  14432. });
  14433. }
  14434. });
  14435. }
  14436. me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  14437. me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  14438. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  14439. this.handleTickRangeOptions();
  14440. },
  14441. getTickLimit: function() {
  14442. var maxTicks;
  14443. var me = this;
  14444. var tickOpts = me.options.ticks;
  14445. if (me.isHorizontal()) {
  14446. maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.width / 50));
  14447. } else {
  14448. // The factor of 2 used to scale the font size has been experimentally determined.
  14449. var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, defaults.global.defaultFontSize);
  14450. maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.height / (2 * tickFontSize)));
  14451. }
  14452. return maxTicks;
  14453. },
  14454. // Called after the ticks are built. We need
  14455. handleDirectionalChanges: function() {
  14456. if (!this.isHorizontal()) {
  14457. // We are in a vertical orientation. The top value is the highest. So reverse the array
  14458. this.ticks.reverse();
  14459. }
  14460. },
  14461. getLabelForIndex: function(index, datasetIndex) {
  14462. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  14463. },
  14464. // Utils
  14465. getPixelForValue: function(value) {
  14466. // This must be called after fit has been run so that
  14467. // this.left, this.top, this.right, and this.bottom have been defined
  14468. var me = this;
  14469. var start = me.start;
  14470. var rightValue = +me.getRightValue(value);
  14471. var pixel;
  14472. var range = me.end - start;
  14473. if (me.isHorizontal()) {
  14474. pixel = me.left + (me.width / range * (rightValue - start));
  14475. } else {
  14476. pixel = me.bottom - (me.height / range * (rightValue - start));
  14477. }
  14478. return pixel;
  14479. },
  14480. getValueForPixel: function(pixel) {
  14481. var me = this;
  14482. var isHorizontal = me.isHorizontal();
  14483. var innerDimension = isHorizontal ? me.width : me.height;
  14484. var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;
  14485. return me.start + ((me.end - me.start) * offset);
  14486. },
  14487. getPixelForTick: function(index) {
  14488. return this.getPixelForValue(this.ticksAsNumbers[index]);
  14489. }
  14490. });
  14491. scaleService.registerScaleType('linear', LinearScale, defaultConfig);
  14492. };
  14493. },{"26":26,"34":34,"35":35,"46":46}],56:[function(require,module,exports){
  14494. 'use strict';
  14495. var helpers = require(46);
  14496. var Scale = require(33);
  14497. /**
  14498. * Generate a set of linear ticks
  14499. * @param generationOptions the options used to generate the ticks
  14500. * @param dataRange the range of the data
  14501. * @returns {Array<Number>} array of tick values
  14502. */
  14503. function generateTicks(generationOptions, dataRange) {
  14504. var ticks = [];
  14505. // To get a "nice" value for the tick spacing, we will use the appropriately named
  14506. // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  14507. // for details.
  14508. var factor;
  14509. var precision;
  14510. var spacing;
  14511. if (generationOptions.stepSize && generationOptions.stepSize > 0) {
  14512. spacing = generationOptions.stepSize;
  14513. } else {
  14514. var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false);
  14515. spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true);
  14516. precision = generationOptions.precision;
  14517. if (precision !== undefined) {
  14518. // If the user specified a precision, round to that number of decimal places
  14519. factor = Math.pow(10, precision);
  14520. spacing = Math.ceil(spacing * factor) / factor;
  14521. }
  14522. }
  14523. var niceMin = Math.floor(dataRange.min / spacing) * spacing;
  14524. var niceMax = Math.ceil(dataRange.max / spacing) * spacing;
  14525. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  14526. if (!helpers.isNullOrUndef(generationOptions.min) && !helpers.isNullOrUndef(generationOptions.max) && generationOptions.stepSize) {
  14527. // If very close to our whole number, use it.
  14528. if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) {
  14529. niceMin = generationOptions.min;
  14530. niceMax = generationOptions.max;
  14531. }
  14532. }
  14533. var numSpaces = (niceMax - niceMin) / spacing;
  14534. // If very close to our rounded value, use it.
  14535. if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  14536. numSpaces = Math.round(numSpaces);
  14537. } else {
  14538. numSpaces = Math.ceil(numSpaces);
  14539. }
  14540. precision = 1;
  14541. if (spacing < 1) {
  14542. precision = Math.pow(10, 1 - Math.floor(helpers.log10(spacing)));
  14543. niceMin = Math.round(niceMin * precision) / precision;
  14544. niceMax = Math.round(niceMax * precision) / precision;
  14545. }
  14546. ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin);
  14547. for (var j = 1; j < numSpaces; ++j) {
  14548. ticks.push(Math.round((niceMin + j * spacing) * precision) / precision);
  14549. }
  14550. ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax);
  14551. return ticks;
  14552. }
  14553. module.exports = function(Chart) {
  14554. var noop = helpers.noop;
  14555. Chart.LinearScaleBase = Scale.extend({
  14556. getRightValue: function(value) {
  14557. if (typeof value === 'string') {
  14558. return +value;
  14559. }
  14560. return Scale.prototype.getRightValue.call(this, value);
  14561. },
  14562. handleTickRangeOptions: function() {
  14563. var me = this;
  14564. var opts = me.options;
  14565. var tickOpts = opts.ticks;
  14566. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  14567. // do nothing since that would make the chart weird. If the user really wants a weird chart
  14568. // axis, they can manually override it
  14569. if (tickOpts.beginAtZero) {
  14570. var minSign = helpers.sign(me.min);
  14571. var maxSign = helpers.sign(me.max);
  14572. if (minSign < 0 && maxSign < 0) {
  14573. // move the top up to 0
  14574. me.max = 0;
  14575. } else if (minSign > 0 && maxSign > 0) {
  14576. // move the bottom down to 0
  14577. me.min = 0;
  14578. }
  14579. }
  14580. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  14581. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  14582. if (tickOpts.min !== undefined) {
  14583. me.min = tickOpts.min;
  14584. } else if (tickOpts.suggestedMin !== undefined) {
  14585. if (me.min === null) {
  14586. me.min = tickOpts.suggestedMin;
  14587. } else {
  14588. me.min = Math.min(me.min, tickOpts.suggestedMin);
  14589. }
  14590. }
  14591. if (tickOpts.max !== undefined) {
  14592. me.max = tickOpts.max;
  14593. } else if (tickOpts.suggestedMax !== undefined) {
  14594. if (me.max === null) {
  14595. me.max = tickOpts.suggestedMax;
  14596. } else {
  14597. me.max = Math.max(me.max, tickOpts.suggestedMax);
  14598. }
  14599. }
  14600. if (setMin !== setMax) {
  14601. // We set the min or the max but not both.
  14602. // So ensure that our range is good
  14603. // Inverted or 0 length range can happen when
  14604. // ticks.min is set, and no datasets are visible
  14605. if (me.min >= me.max) {
  14606. if (setMin) {
  14607. me.max = me.min + 1;
  14608. } else {
  14609. me.min = me.max - 1;
  14610. }
  14611. }
  14612. }
  14613. if (me.min === me.max) {
  14614. me.max++;
  14615. if (!tickOpts.beginAtZero) {
  14616. me.min--;
  14617. }
  14618. }
  14619. },
  14620. getTickLimit: noop,
  14621. handleDirectionalChanges: noop,
  14622. buildTicks: function() {
  14623. var me = this;
  14624. var opts = me.options;
  14625. var tickOpts = opts.ticks;
  14626. // Figure out what the max number of ticks we can support it is based on the size of
  14627. // the axis area. For now, we say that the minimum tick spacing in pixels must be 50
  14628. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  14629. // the graph. Make sure we always have at least 2 ticks
  14630. var maxTicks = me.getTickLimit();
  14631. maxTicks = Math.max(2, maxTicks);
  14632. var numericGeneratorOptions = {
  14633. maxTicks: maxTicks,
  14634. min: tickOpts.min,
  14635. max: tickOpts.max,
  14636. precision: tickOpts.precision,
  14637. stepSize: helpers.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  14638. };
  14639. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  14640. me.handleDirectionalChanges();
  14641. // At this point, we need to update our max and min given the tick values since we have expanded the
  14642. // range of the scale
  14643. me.max = helpers.max(ticks);
  14644. me.min = helpers.min(ticks);
  14645. if (tickOpts.reverse) {
  14646. ticks.reverse();
  14647. me.start = me.max;
  14648. me.end = me.min;
  14649. } else {
  14650. me.start = me.min;
  14651. me.end = me.max;
  14652. }
  14653. },
  14654. convertTicksToLabels: function() {
  14655. var me = this;
  14656. me.ticksAsNumbers = me.ticks.slice();
  14657. me.zeroLineIndex = me.ticks.indexOf(0);
  14658. Scale.prototype.convertTicksToLabels.call(me);
  14659. }
  14660. });
  14661. };
  14662. },{"33":33,"46":46}],57:[function(require,module,exports){
  14663. 'use strict';
  14664. var helpers = require(46);
  14665. var Scale = require(33);
  14666. var scaleService = require(34);
  14667. var Ticks = require(35);
  14668. /**
  14669. * Generate a set of logarithmic ticks
  14670. * @param generationOptions the options used to generate the ticks
  14671. * @param dataRange the range of the data
  14672. * @returns {Array<Number>} array of tick values
  14673. */
  14674. function generateTicks(generationOptions, dataRange) {
  14675. var ticks = [];
  14676. var valueOrDefault = helpers.valueOrDefault;
  14677. // Figure out what the max number of ticks we can support it is based on the size of
  14678. // the axis area. For now, we say that the minimum tick spacing in pixels must be 50
  14679. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  14680. // the graph
  14681. var tickVal = valueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min))));
  14682. var endExp = Math.floor(helpers.log10(dataRange.max));
  14683. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  14684. var exp, significand;
  14685. if (tickVal === 0) {
  14686. exp = Math.floor(helpers.log10(dataRange.minNotZero));
  14687. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  14688. ticks.push(tickVal);
  14689. tickVal = significand * Math.pow(10, exp);
  14690. } else {
  14691. exp = Math.floor(helpers.log10(tickVal));
  14692. significand = Math.floor(tickVal / Math.pow(10, exp));
  14693. }
  14694. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  14695. do {
  14696. ticks.push(tickVal);
  14697. ++significand;
  14698. if (significand === 10) {
  14699. significand = 1;
  14700. ++exp;
  14701. precision = exp >= 0 ? 1 : precision;
  14702. }
  14703. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  14704. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  14705. var lastTick = valueOrDefault(generationOptions.max, tickVal);
  14706. ticks.push(lastTick);
  14707. return ticks;
  14708. }
  14709. module.exports = function(Chart) {
  14710. var defaultConfig = {
  14711. position: 'left',
  14712. // label settings
  14713. ticks: {
  14714. callback: Ticks.formatters.logarithmic
  14715. }
  14716. };
  14717. var LogarithmicScale = Scale.extend({
  14718. determineDataLimits: function() {
  14719. var me = this;
  14720. var opts = me.options;
  14721. var chart = me.chart;
  14722. var data = chart.data;
  14723. var datasets = data.datasets;
  14724. var isHorizontal = me.isHorizontal();
  14725. function IDMatches(meta) {
  14726. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  14727. }
  14728. // Calculate Range
  14729. me.min = null;
  14730. me.max = null;
  14731. me.minNotZero = null;
  14732. var hasStacks = opts.stacked;
  14733. if (hasStacks === undefined) {
  14734. helpers.each(datasets, function(dataset, datasetIndex) {
  14735. if (hasStacks) {
  14736. return;
  14737. }
  14738. var meta = chart.getDatasetMeta(datasetIndex);
  14739. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  14740. meta.stack !== undefined) {
  14741. hasStacks = true;
  14742. }
  14743. });
  14744. }
  14745. if (opts.stacked || hasStacks) {
  14746. var valuesPerStack = {};
  14747. helpers.each(datasets, function(dataset, datasetIndex) {
  14748. var meta = chart.getDatasetMeta(datasetIndex);
  14749. var key = [
  14750. meta.type,
  14751. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  14752. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  14753. meta.stack
  14754. ].join('.');
  14755. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  14756. if (valuesPerStack[key] === undefined) {
  14757. valuesPerStack[key] = [];
  14758. }
  14759. helpers.each(dataset.data, function(rawValue, index) {
  14760. var values = valuesPerStack[key];
  14761. var value = +me.getRightValue(rawValue);
  14762. // invalid, hidden and negative values are ignored
  14763. if (isNaN(value) || meta.data[index].hidden || value < 0) {
  14764. return;
  14765. }
  14766. values[index] = values[index] || 0;
  14767. values[index] += value;
  14768. });
  14769. }
  14770. });
  14771. helpers.each(valuesPerStack, function(valuesForType) {
  14772. if (valuesForType.length > 0) {
  14773. var minVal = helpers.min(valuesForType);
  14774. var maxVal = helpers.max(valuesForType);
  14775. me.min = me.min === null ? minVal : Math.min(me.min, minVal);
  14776. me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
  14777. }
  14778. });
  14779. } else {
  14780. helpers.each(datasets, function(dataset, datasetIndex) {
  14781. var meta = chart.getDatasetMeta(datasetIndex);
  14782. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  14783. helpers.each(dataset.data, function(rawValue, index) {
  14784. var value = +me.getRightValue(rawValue);
  14785. // invalid, hidden and negative values are ignored
  14786. if (isNaN(value) || meta.data[index].hidden || value < 0) {
  14787. return;
  14788. }
  14789. if (me.min === null) {
  14790. me.min = value;
  14791. } else if (value < me.min) {
  14792. me.min = value;
  14793. }
  14794. if (me.max === null) {
  14795. me.max = value;
  14796. } else if (value > me.max) {
  14797. me.max = value;
  14798. }
  14799. if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {
  14800. me.minNotZero = value;
  14801. }
  14802. });
  14803. }
  14804. });
  14805. }
  14806. // Common base implementation to handle ticks.min, ticks.max
  14807. this.handleTickRangeOptions();
  14808. },
  14809. handleTickRangeOptions: function() {
  14810. var me = this;
  14811. var opts = me.options;
  14812. var tickOpts = opts.ticks;
  14813. var valueOrDefault = helpers.valueOrDefault;
  14814. var DEFAULT_MIN = 1;
  14815. var DEFAULT_MAX = 10;
  14816. me.min = valueOrDefault(tickOpts.min, me.min);
  14817. me.max = valueOrDefault(tickOpts.max, me.max);
  14818. if (me.min === me.max) {
  14819. if (me.min !== 0 && me.min !== null) {
  14820. me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1);
  14821. me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1);
  14822. } else {
  14823. me.min = DEFAULT_MIN;
  14824. me.max = DEFAULT_MAX;
  14825. }
  14826. }
  14827. if (me.min === null) {
  14828. me.min = Math.pow(10, Math.floor(helpers.log10(me.max)) - 1);
  14829. }
  14830. if (me.max === null) {
  14831. me.max = me.min !== 0
  14832. ? Math.pow(10, Math.floor(helpers.log10(me.min)) + 1)
  14833. : DEFAULT_MAX;
  14834. }
  14835. if (me.minNotZero === null) {
  14836. if (me.min > 0) {
  14837. me.minNotZero = me.min;
  14838. } else if (me.max < 1) {
  14839. me.minNotZero = Math.pow(10, Math.floor(helpers.log10(me.max)));
  14840. } else {
  14841. me.minNotZero = DEFAULT_MIN;
  14842. }
  14843. }
  14844. },
  14845. buildTicks: function() {
  14846. var me = this;
  14847. var opts = me.options;
  14848. var tickOpts = opts.ticks;
  14849. var reverse = !me.isHorizontal();
  14850. var generationOptions = {
  14851. min: tickOpts.min,
  14852. max: tickOpts.max
  14853. };
  14854. var ticks = me.ticks = generateTicks(generationOptions, me);
  14855. // At this point, we need to update our max and min given the tick values since we have expanded the
  14856. // range of the scale
  14857. me.max = helpers.max(ticks);
  14858. me.min = helpers.min(ticks);
  14859. if (tickOpts.reverse) {
  14860. reverse = !reverse;
  14861. me.start = me.max;
  14862. me.end = me.min;
  14863. } else {
  14864. me.start = me.min;
  14865. me.end = me.max;
  14866. }
  14867. if (reverse) {
  14868. ticks.reverse();
  14869. }
  14870. },
  14871. convertTicksToLabels: function() {
  14872. this.tickValues = this.ticks.slice();
  14873. Scale.prototype.convertTicksToLabels.call(this);
  14874. },
  14875. // Get the correct tooltip label
  14876. getLabelForIndex: function(index, datasetIndex) {
  14877. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  14878. },
  14879. getPixelForTick: function(index) {
  14880. return this.getPixelForValue(this.tickValues[index]);
  14881. },
  14882. /**
  14883. * Returns the value of the first tick.
  14884. * @param {Number} value - The minimum not zero value.
  14885. * @return {Number} The first tick value.
  14886. * @private
  14887. */
  14888. _getFirstTickValue: function(value) {
  14889. var exp = Math.floor(helpers.log10(value));
  14890. var significand = Math.floor(value / Math.pow(10, exp));
  14891. return significand * Math.pow(10, exp);
  14892. },
  14893. getPixelForValue: function(value) {
  14894. var me = this;
  14895. var reverse = me.options.ticks.reverse;
  14896. var log10 = helpers.log10;
  14897. var firstTickValue = me._getFirstTickValue(me.minNotZero);
  14898. var offset = 0;
  14899. var innerDimension, pixel, start, end, sign;
  14900. value = +me.getRightValue(value);
  14901. if (reverse) {
  14902. start = me.end;
  14903. end = me.start;
  14904. sign = -1;
  14905. } else {
  14906. start = me.start;
  14907. end = me.end;
  14908. sign = 1;
  14909. }
  14910. if (me.isHorizontal()) {
  14911. innerDimension = me.width;
  14912. pixel = reverse ? me.right : me.left;
  14913. } else {
  14914. innerDimension = me.height;
  14915. sign *= -1; // invert, since the upper-left corner of the canvas is at pixel (0, 0)
  14916. pixel = reverse ? me.top : me.bottom;
  14917. }
  14918. if (value !== start) {
  14919. if (start === 0) { // include zero tick
  14920. offset = helpers.getValueOrDefault(
  14921. me.options.ticks.fontSize,
  14922. Chart.defaults.global.defaultFontSize
  14923. );
  14924. innerDimension -= offset;
  14925. start = firstTickValue;
  14926. }
  14927. if (value !== 0) {
  14928. offset += innerDimension / (log10(end) - log10(start)) * (log10(value) - log10(start));
  14929. }
  14930. pixel += sign * offset;
  14931. }
  14932. return pixel;
  14933. },
  14934. getValueForPixel: function(pixel) {
  14935. var me = this;
  14936. var reverse = me.options.ticks.reverse;
  14937. var log10 = helpers.log10;
  14938. var firstTickValue = me._getFirstTickValue(me.minNotZero);
  14939. var innerDimension, start, end, value;
  14940. if (reverse) {
  14941. start = me.end;
  14942. end = me.start;
  14943. } else {
  14944. start = me.start;
  14945. end = me.end;
  14946. }
  14947. if (me.isHorizontal()) {
  14948. innerDimension = me.width;
  14949. value = reverse ? me.right - pixel : pixel - me.left;
  14950. } else {
  14951. innerDimension = me.height;
  14952. value = reverse ? pixel - me.top : me.bottom - pixel;
  14953. }
  14954. if (value !== start) {
  14955. if (start === 0) { // include zero tick
  14956. var offset = helpers.getValueOrDefault(
  14957. me.options.ticks.fontSize,
  14958. Chart.defaults.global.defaultFontSize
  14959. );
  14960. value -= offset;
  14961. innerDimension -= offset;
  14962. start = firstTickValue;
  14963. }
  14964. value *= log10(end) - log10(start);
  14965. value /= innerDimension;
  14966. value = Math.pow(10, log10(start) + value);
  14967. }
  14968. return value;
  14969. }
  14970. });
  14971. scaleService.registerScaleType('logarithmic', LogarithmicScale, defaultConfig);
  14972. };
  14973. },{"33":33,"34":34,"35":35,"46":46}],58:[function(require,module,exports){
  14974. 'use strict';
  14975. var defaults = require(26);
  14976. var helpers = require(46);
  14977. var scaleService = require(34);
  14978. var Ticks = require(35);
  14979. module.exports = function(Chart) {
  14980. var globalDefaults = defaults.global;
  14981. var defaultConfig = {
  14982. display: true,
  14983. // Boolean - Whether to animate scaling the chart from the centre
  14984. animate: true,
  14985. position: 'chartArea',
  14986. angleLines: {
  14987. display: true,
  14988. color: 'rgba(0, 0, 0, 0.1)',
  14989. lineWidth: 1
  14990. },
  14991. gridLines: {
  14992. circular: false
  14993. },
  14994. // label settings
  14995. ticks: {
  14996. // Boolean - Show a backdrop to the scale label
  14997. showLabelBackdrop: true,
  14998. // String - The colour of the label backdrop
  14999. backdropColor: 'rgba(255,255,255,0.75)',
  15000. // Number - The backdrop padding above & below the label in pixels
  15001. backdropPaddingY: 2,
  15002. // Number - The backdrop padding to the side of the label in pixels
  15003. backdropPaddingX: 2,
  15004. callback: Ticks.formatters.linear
  15005. },
  15006. pointLabels: {
  15007. // Boolean - if true, show point labels
  15008. display: true,
  15009. // Number - Point label font size in pixels
  15010. fontSize: 10,
  15011. // Function - Used to convert point labels
  15012. callback: function(label) {
  15013. return label;
  15014. }
  15015. }
  15016. };
  15017. function getValueCount(scale) {
  15018. var opts = scale.options;
  15019. return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0;
  15020. }
  15021. function getPointLabelFontOptions(scale) {
  15022. var pointLabelOptions = scale.options.pointLabels;
  15023. var fontSize = helpers.valueOrDefault(pointLabelOptions.fontSize, globalDefaults.defaultFontSize);
  15024. var fontStyle = helpers.valueOrDefault(pointLabelOptions.fontStyle, globalDefaults.defaultFontStyle);
  15025. var fontFamily = helpers.valueOrDefault(pointLabelOptions.fontFamily, globalDefaults.defaultFontFamily);
  15026. var font = helpers.fontString(fontSize, fontStyle, fontFamily);
  15027. return {
  15028. size: fontSize,
  15029. style: fontStyle,
  15030. family: fontFamily,
  15031. font: font
  15032. };
  15033. }
  15034. function measureLabelSize(ctx, fontSize, label) {
  15035. if (helpers.isArray(label)) {
  15036. return {
  15037. w: helpers.longestText(ctx, ctx.font, label),
  15038. h: (label.length * fontSize) + ((label.length - 1) * 1.5 * fontSize)
  15039. };
  15040. }
  15041. return {
  15042. w: ctx.measureText(label).width,
  15043. h: fontSize
  15044. };
  15045. }
  15046. function determineLimits(angle, pos, size, min, max) {
  15047. if (angle === min || angle === max) {
  15048. return {
  15049. start: pos - (size / 2),
  15050. end: pos + (size / 2)
  15051. };
  15052. } else if (angle < min || angle > max) {
  15053. return {
  15054. start: pos - size - 5,
  15055. end: pos
  15056. };
  15057. }
  15058. return {
  15059. start: pos,
  15060. end: pos + size + 5
  15061. };
  15062. }
  15063. /**
  15064. * Helper function to fit a radial linear scale with point labels
  15065. */
  15066. function fitWithPointLabels(scale) {
  15067. /*
  15068. * Right, this is really confusing and there is a lot of maths going on here
  15069. * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  15070. *
  15071. * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  15072. *
  15073. * Solution:
  15074. *
  15075. * We assume the radius of the polygon is half the size of the canvas at first
  15076. * at each index we check if the text overlaps.
  15077. *
  15078. * Where it does, we store that angle and that index.
  15079. *
  15080. * After finding the largest index and angle we calculate how much we need to remove
  15081. * from the shape radius to move the point inwards by that x.
  15082. *
  15083. * We average the left and right distances to get the maximum shape radius that can fit in the box
  15084. * along with labels.
  15085. *
  15086. * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  15087. * on each side, removing that from the size, halving it and adding the left x protrusion width.
  15088. *
  15089. * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  15090. * and position it in the most space efficient manner
  15091. *
  15092. * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  15093. */
  15094. var plFont = getPointLabelFontOptions(scale);
  15095. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  15096. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  15097. var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
  15098. var furthestLimits = {
  15099. r: scale.width,
  15100. l: 0,
  15101. t: scale.height,
  15102. b: 0
  15103. };
  15104. var furthestAngles = {};
  15105. var i, textSize, pointPosition;
  15106. scale.ctx.font = plFont.font;
  15107. scale._pointLabelSizes = [];
  15108. var valueCount = getValueCount(scale);
  15109. for (i = 0; i < valueCount; i++) {
  15110. pointPosition = scale.getPointPosition(i, largestPossibleRadius);
  15111. textSize = measureLabelSize(scale.ctx, plFont.size, scale.pointLabels[i] || '');
  15112. scale._pointLabelSizes[i] = textSize;
  15113. // Add quarter circle to make degree 0 mean top of circle
  15114. var angleRadians = scale.getIndexAngle(i);
  15115. var angle = helpers.toDegrees(angleRadians) % 360;
  15116. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  15117. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  15118. if (hLimits.start < furthestLimits.l) {
  15119. furthestLimits.l = hLimits.start;
  15120. furthestAngles.l = angleRadians;
  15121. }
  15122. if (hLimits.end > furthestLimits.r) {
  15123. furthestLimits.r = hLimits.end;
  15124. furthestAngles.r = angleRadians;
  15125. }
  15126. if (vLimits.start < furthestLimits.t) {
  15127. furthestLimits.t = vLimits.start;
  15128. furthestAngles.t = angleRadians;
  15129. }
  15130. if (vLimits.end > furthestLimits.b) {
  15131. furthestLimits.b = vLimits.end;
  15132. furthestAngles.b = angleRadians;
  15133. }
  15134. }
  15135. scale.setReductions(largestPossibleRadius, furthestLimits, furthestAngles);
  15136. }
  15137. /**
  15138. * Helper function to fit a radial linear scale with no point labels
  15139. */
  15140. function fit(scale) {
  15141. var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
  15142. scale.drawingArea = Math.round(largestPossibleRadius);
  15143. scale.setCenterPoint(0, 0, 0, 0);
  15144. }
  15145. function getTextAlignForAngle(angle) {
  15146. if (angle === 0 || angle === 180) {
  15147. return 'center';
  15148. } else if (angle < 180) {
  15149. return 'left';
  15150. }
  15151. return 'right';
  15152. }
  15153. function fillText(ctx, text, position, fontSize) {
  15154. if (helpers.isArray(text)) {
  15155. var y = position.y;
  15156. var spacing = 1.5 * fontSize;
  15157. for (var i = 0; i < text.length; ++i) {
  15158. ctx.fillText(text[i], position.x, y);
  15159. y += spacing;
  15160. }
  15161. } else {
  15162. ctx.fillText(text, position.x, position.y);
  15163. }
  15164. }
  15165. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  15166. if (angle === 90 || angle === 270) {
  15167. position.y -= (textSize.h / 2);
  15168. } else if (angle > 270 || angle < 90) {
  15169. position.y -= textSize.h;
  15170. }
  15171. }
  15172. function drawPointLabels(scale) {
  15173. var ctx = scale.ctx;
  15174. var opts = scale.options;
  15175. var angleLineOpts = opts.angleLines;
  15176. var pointLabelOpts = opts.pointLabels;
  15177. ctx.lineWidth = angleLineOpts.lineWidth;
  15178. ctx.strokeStyle = angleLineOpts.color;
  15179. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  15180. // Point Label Font
  15181. var plFont = getPointLabelFontOptions(scale);
  15182. ctx.textBaseline = 'top';
  15183. for (var i = getValueCount(scale) - 1; i >= 0; i--) {
  15184. if (angleLineOpts.display) {
  15185. var outerPosition = scale.getPointPosition(i, outerDistance);
  15186. ctx.beginPath();
  15187. ctx.moveTo(scale.xCenter, scale.yCenter);
  15188. ctx.lineTo(outerPosition.x, outerPosition.y);
  15189. ctx.stroke();
  15190. ctx.closePath();
  15191. }
  15192. if (pointLabelOpts.display) {
  15193. // Extra 3px out for some label spacing
  15194. var pointLabelPosition = scale.getPointPosition(i, outerDistance + 5);
  15195. // Keep this in loop since we may support array properties here
  15196. var pointLabelFontColor = helpers.valueAtIndexOrDefault(pointLabelOpts.fontColor, i, globalDefaults.defaultFontColor);
  15197. ctx.font = plFont.font;
  15198. ctx.fillStyle = pointLabelFontColor;
  15199. var angleRadians = scale.getIndexAngle(i);
  15200. var angle = helpers.toDegrees(angleRadians);
  15201. ctx.textAlign = getTextAlignForAngle(angle);
  15202. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  15203. fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.size);
  15204. }
  15205. }
  15206. }
  15207. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  15208. var ctx = scale.ctx;
  15209. ctx.strokeStyle = helpers.valueAtIndexOrDefault(gridLineOpts.color, index - 1);
  15210. ctx.lineWidth = helpers.valueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1);
  15211. if (scale.options.gridLines.circular) {
  15212. // Draw circular arcs between the points
  15213. ctx.beginPath();
  15214. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  15215. ctx.closePath();
  15216. ctx.stroke();
  15217. } else {
  15218. // Draw straight lines connecting each index
  15219. var valueCount = getValueCount(scale);
  15220. if (valueCount === 0) {
  15221. return;
  15222. }
  15223. ctx.beginPath();
  15224. var pointPosition = scale.getPointPosition(0, radius);
  15225. ctx.moveTo(pointPosition.x, pointPosition.y);
  15226. for (var i = 1; i < valueCount; i++) {
  15227. pointPosition = scale.getPointPosition(i, radius);
  15228. ctx.lineTo(pointPosition.x, pointPosition.y);
  15229. }
  15230. ctx.closePath();
  15231. ctx.stroke();
  15232. }
  15233. }
  15234. function numberOrZero(param) {
  15235. return helpers.isNumber(param) ? param : 0;
  15236. }
  15237. var LinearRadialScale = Chart.LinearScaleBase.extend({
  15238. setDimensions: function() {
  15239. var me = this;
  15240. var opts = me.options;
  15241. var tickOpts = opts.ticks;
  15242. // Set the unconstrained dimension before label rotation
  15243. me.width = me.maxWidth;
  15244. me.height = me.maxHeight;
  15245. me.xCenter = Math.round(me.width / 2);
  15246. me.yCenter = Math.round(me.height / 2);
  15247. var minSize = helpers.min([me.height, me.width]);
  15248. var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
  15249. me.drawingArea = opts.display ? (minSize / 2) - (tickFontSize / 2 + tickOpts.backdropPaddingY) : (minSize / 2);
  15250. },
  15251. determineDataLimits: function() {
  15252. var me = this;
  15253. var chart = me.chart;
  15254. var min = Number.POSITIVE_INFINITY;
  15255. var max = Number.NEGATIVE_INFINITY;
  15256. helpers.each(chart.data.datasets, function(dataset, datasetIndex) {
  15257. if (chart.isDatasetVisible(datasetIndex)) {
  15258. var meta = chart.getDatasetMeta(datasetIndex);
  15259. helpers.each(dataset.data, function(rawValue, index) {
  15260. var value = +me.getRightValue(rawValue);
  15261. if (isNaN(value) || meta.data[index].hidden) {
  15262. return;
  15263. }
  15264. min = Math.min(value, min);
  15265. max = Math.max(value, max);
  15266. });
  15267. }
  15268. });
  15269. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  15270. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  15271. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  15272. me.handleTickRangeOptions();
  15273. },
  15274. getTickLimit: function() {
  15275. var tickOpts = this.options.ticks;
  15276. var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
  15277. return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize)));
  15278. },
  15279. convertTicksToLabels: function() {
  15280. var me = this;
  15281. Chart.LinearScaleBase.prototype.convertTicksToLabels.call(me);
  15282. // Point labels
  15283. me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
  15284. },
  15285. getLabelForIndex: function(index, datasetIndex) {
  15286. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  15287. },
  15288. fit: function() {
  15289. if (this.options.pointLabels.display) {
  15290. fitWithPointLabels(this);
  15291. } else {
  15292. fit(this);
  15293. }
  15294. },
  15295. /**
  15296. * Set radius reductions and determine new radius and center point
  15297. * @private
  15298. */
  15299. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  15300. var me = this;
  15301. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  15302. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  15303. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  15304. var radiusReductionBottom = -Math.max(furthestLimits.b - me.height, 0) / Math.cos(furthestAngles.b);
  15305. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  15306. radiusReductionRight = numberOrZero(radiusReductionRight);
  15307. radiusReductionTop = numberOrZero(radiusReductionTop);
  15308. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  15309. me.drawingArea = Math.min(
  15310. Math.round(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  15311. Math.round(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  15312. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  15313. },
  15314. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  15315. var me = this;
  15316. var maxRight = me.width - rightMovement - me.drawingArea;
  15317. var maxLeft = leftMovement + me.drawingArea;
  15318. var maxTop = topMovement + me.drawingArea;
  15319. var maxBottom = me.height - bottomMovement - me.drawingArea;
  15320. me.xCenter = Math.round(((maxLeft + maxRight) / 2) + me.left);
  15321. me.yCenter = Math.round(((maxTop + maxBottom) / 2) + me.top);
  15322. },
  15323. getIndexAngle: function(index) {
  15324. var angleMultiplier = (Math.PI * 2) / getValueCount(this);
  15325. var startAngle = this.chart.options && this.chart.options.startAngle ?
  15326. this.chart.options.startAngle :
  15327. 0;
  15328. var startAngleRadians = startAngle * Math.PI * 2 / 360;
  15329. // Start from the top instead of right, so remove a quarter of the circle
  15330. return index * angleMultiplier + startAngleRadians;
  15331. },
  15332. getDistanceFromCenterForValue: function(value) {
  15333. var me = this;
  15334. if (value === null) {
  15335. return 0; // null always in center
  15336. }
  15337. // Take into account half font size + the yPadding of the top value
  15338. var scalingFactor = me.drawingArea / (me.max - me.min);
  15339. if (me.options.ticks.reverse) {
  15340. return (me.max - value) * scalingFactor;
  15341. }
  15342. return (value - me.min) * scalingFactor;
  15343. },
  15344. getPointPosition: function(index, distanceFromCenter) {
  15345. var me = this;
  15346. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  15347. return {
  15348. x: Math.round(Math.cos(thisAngle) * distanceFromCenter) + me.xCenter,
  15349. y: Math.round(Math.sin(thisAngle) * distanceFromCenter) + me.yCenter
  15350. };
  15351. },
  15352. getPointPositionForValue: function(index, value) {
  15353. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  15354. },
  15355. getBasePosition: function() {
  15356. var me = this;
  15357. var min = me.min;
  15358. var max = me.max;
  15359. return me.getPointPositionForValue(0,
  15360. me.beginAtZero ? 0 :
  15361. min < 0 && max < 0 ? max :
  15362. min > 0 && max > 0 ? min :
  15363. 0);
  15364. },
  15365. draw: function() {
  15366. var me = this;
  15367. var opts = me.options;
  15368. var gridLineOpts = opts.gridLines;
  15369. var tickOpts = opts.ticks;
  15370. var valueOrDefault = helpers.valueOrDefault;
  15371. if (opts.display) {
  15372. var ctx = me.ctx;
  15373. var startAngle = this.getIndexAngle(0);
  15374. // Tick Font
  15375. var tickFontSize = valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
  15376. var tickFontStyle = valueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle);
  15377. var tickFontFamily = valueOrDefault(tickOpts.fontFamily, globalDefaults.defaultFontFamily);
  15378. var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
  15379. helpers.each(me.ticks, function(label, index) {
  15380. // Don't draw a centre value (if it is minimum)
  15381. if (index > 0 || tickOpts.reverse) {
  15382. var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  15383. // Draw circular lines around the scale
  15384. if (gridLineOpts.display && index !== 0) {
  15385. drawRadiusLine(me, gridLineOpts, yCenterOffset, index);
  15386. }
  15387. if (tickOpts.display) {
  15388. var tickFontColor = valueOrDefault(tickOpts.fontColor, globalDefaults.defaultFontColor);
  15389. ctx.font = tickLabelFont;
  15390. ctx.save();
  15391. ctx.translate(me.xCenter, me.yCenter);
  15392. ctx.rotate(startAngle);
  15393. if (tickOpts.showLabelBackdrop) {
  15394. var labelWidth = ctx.measureText(label).width;
  15395. ctx.fillStyle = tickOpts.backdropColor;
  15396. ctx.fillRect(
  15397. -labelWidth / 2 - tickOpts.backdropPaddingX,
  15398. -yCenterOffset - tickFontSize / 2 - tickOpts.backdropPaddingY,
  15399. labelWidth + tickOpts.backdropPaddingX * 2,
  15400. tickFontSize + tickOpts.backdropPaddingY * 2
  15401. );
  15402. }
  15403. ctx.textAlign = 'center';
  15404. ctx.textBaseline = 'middle';
  15405. ctx.fillStyle = tickFontColor;
  15406. ctx.fillText(label, 0, -yCenterOffset);
  15407. ctx.restore();
  15408. }
  15409. }
  15410. });
  15411. if (opts.angleLines.display || opts.pointLabels.display) {
  15412. drawPointLabels(me);
  15413. }
  15414. }
  15415. }
  15416. });
  15417. scaleService.registerScaleType('radialLinear', LinearRadialScale, defaultConfig);
  15418. };
  15419. },{"26":26,"34":34,"35":35,"46":46}],59:[function(require,module,exports){
  15420. /* global window: false */
  15421. 'use strict';
  15422. var moment = require(6);
  15423. moment = typeof moment === 'function' ? moment : window.moment;
  15424. var defaults = require(26);
  15425. var helpers = require(46);
  15426. var Scale = require(33);
  15427. var scaleService = require(34);
  15428. // Integer constants are from the ES6 spec.
  15429. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  15430. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  15431. var INTERVALS = {
  15432. millisecond: {
  15433. common: true,
  15434. size: 1,
  15435. steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
  15436. },
  15437. second: {
  15438. common: true,
  15439. size: 1000,
  15440. steps: [1, 2, 5, 10, 15, 30]
  15441. },
  15442. minute: {
  15443. common: true,
  15444. size: 60000,
  15445. steps: [1, 2, 5, 10, 15, 30]
  15446. },
  15447. hour: {
  15448. common: true,
  15449. size: 3600000,
  15450. steps: [1, 2, 3, 6, 12]
  15451. },
  15452. day: {
  15453. common: true,
  15454. size: 86400000,
  15455. steps: [1, 2, 5]
  15456. },
  15457. week: {
  15458. common: false,
  15459. size: 604800000,
  15460. steps: [1, 2, 3, 4]
  15461. },
  15462. month: {
  15463. common: true,
  15464. size: 2.628e9,
  15465. steps: [1, 2, 3]
  15466. },
  15467. quarter: {
  15468. common: false,
  15469. size: 7.884e9,
  15470. steps: [1, 2, 3, 4]
  15471. },
  15472. year: {
  15473. common: true,
  15474. size: 3.154e10
  15475. }
  15476. };
  15477. var UNITS = Object.keys(INTERVALS);
  15478. function sorter(a, b) {
  15479. return a - b;
  15480. }
  15481. function arrayUnique(items) {
  15482. var hash = {};
  15483. var out = [];
  15484. var i, ilen, item;
  15485. for (i = 0, ilen = items.length; i < ilen; ++i) {
  15486. item = items[i];
  15487. if (!hash[item]) {
  15488. hash[item] = true;
  15489. out.push(item);
  15490. }
  15491. }
  15492. return out;
  15493. }
  15494. /**
  15495. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  15496. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  15497. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  15498. * extremity (left + width or top + height). Note that it would be more optimized to directly
  15499. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  15500. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  15501. *
  15502. * @param {Number[]} timestamps - timestamps sorted from lowest to highest.
  15503. * @param {String} distribution - If 'linear', timestamps will be spread linearly along the min
  15504. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  15505. * If 'series', timestamps will be positioned at the same distance from each other. In this
  15506. * case, only timestamps that break the time linearity are registered, meaning that in the
  15507. * best case, all timestamps are linear, the table contains only min and max.
  15508. */
  15509. function buildLookupTable(timestamps, min, max, distribution) {
  15510. if (distribution === 'linear' || !timestamps.length) {
  15511. return [
  15512. {time: min, pos: 0},
  15513. {time: max, pos: 1}
  15514. ];
  15515. }
  15516. var table = [];
  15517. var items = [min];
  15518. var i, ilen, prev, curr, next;
  15519. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  15520. curr = timestamps[i];
  15521. if (curr > min && curr < max) {
  15522. items.push(curr);
  15523. }
  15524. }
  15525. items.push(max);
  15526. for (i = 0, ilen = items.length; i < ilen; ++i) {
  15527. next = items[i + 1];
  15528. prev = items[i - 1];
  15529. curr = items[i];
  15530. // only add points that breaks the scale linearity
  15531. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  15532. table.push({time: curr, pos: i / (ilen - 1)});
  15533. }
  15534. }
  15535. return table;
  15536. }
  15537. // @see adapted from http://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  15538. function lookup(table, key, value) {
  15539. var lo = 0;
  15540. var hi = table.length - 1;
  15541. var mid, i0, i1;
  15542. while (lo >= 0 && lo <= hi) {
  15543. mid = (lo + hi) >> 1;
  15544. i0 = table[mid - 1] || null;
  15545. i1 = table[mid];
  15546. if (!i0) {
  15547. // given value is outside table (before first item)
  15548. return {lo: null, hi: i1};
  15549. } else if (i1[key] < value) {
  15550. lo = mid + 1;
  15551. } else if (i0[key] > value) {
  15552. hi = mid - 1;
  15553. } else {
  15554. return {lo: i0, hi: i1};
  15555. }
  15556. }
  15557. // given value is outside table (after last item)
  15558. return {lo: i1, hi: null};
  15559. }
  15560. /**
  15561. * Linearly interpolates the given source `value` using the table items `skey` values and
  15562. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  15563. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  15564. * index [0, 1] or [n - 1, n] are used for the interpolation.
  15565. */
  15566. function interpolate(table, skey, sval, tkey) {
  15567. var range = lookup(table, skey, sval);
  15568. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  15569. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  15570. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  15571. var span = next[skey] - prev[skey];
  15572. var ratio = span ? (sval - prev[skey]) / span : 0;
  15573. var offset = (next[tkey] - prev[tkey]) * ratio;
  15574. return prev[tkey] + offset;
  15575. }
  15576. /**
  15577. * Convert the given value to a moment object using the given time options.
  15578. * @see http://momentjs.com/docs/#/parsing/
  15579. */
  15580. function momentify(value, options) {
  15581. var parser = options.parser;
  15582. var format = options.parser || options.format;
  15583. if (typeof parser === 'function') {
  15584. return parser(value);
  15585. }
  15586. if (typeof value === 'string' && typeof format === 'string') {
  15587. return moment(value, format);
  15588. }
  15589. if (!(value instanceof moment)) {
  15590. value = moment(value);
  15591. }
  15592. if (value.isValid()) {
  15593. return value;
  15594. }
  15595. // Labels are in an incompatible moment format and no `parser` has been provided.
  15596. // The user might still use the deprecated `format` option to convert his inputs.
  15597. if (typeof format === 'function') {
  15598. return format(value);
  15599. }
  15600. return value;
  15601. }
  15602. function parse(input, scale) {
  15603. if (helpers.isNullOrUndef(input)) {
  15604. return null;
  15605. }
  15606. var options = scale.options.time;
  15607. var value = momentify(scale.getRightValue(input), options);
  15608. if (!value.isValid()) {
  15609. return null;
  15610. }
  15611. if (options.round) {
  15612. value.startOf(options.round);
  15613. }
  15614. return value.valueOf();
  15615. }
  15616. /**
  15617. * Returns the number of unit to skip to be able to display up to `capacity` number of ticks
  15618. * in `unit` for the given `min` / `max` range and respecting the interval steps constraints.
  15619. */
  15620. function determineStepSize(min, max, unit, capacity) {
  15621. var range = max - min;
  15622. var interval = INTERVALS[unit];
  15623. var milliseconds = interval.size;
  15624. var steps = interval.steps;
  15625. var i, ilen, factor;
  15626. if (!steps) {
  15627. return Math.ceil(range / (capacity * milliseconds));
  15628. }
  15629. for (i = 0, ilen = steps.length; i < ilen; ++i) {
  15630. factor = steps[i];
  15631. if (Math.ceil(range / (milliseconds * factor)) <= capacity) {
  15632. break;
  15633. }
  15634. }
  15635. return factor;
  15636. }
  15637. /**
  15638. * Figures out what unit results in an appropriate number of auto-generated ticks
  15639. */
  15640. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  15641. var ilen = UNITS.length;
  15642. var i, interval, factor;
  15643. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  15644. interval = INTERVALS[UNITS[i]];
  15645. factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;
  15646. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  15647. return UNITS[i];
  15648. }
  15649. }
  15650. return UNITS[ilen - 1];
  15651. }
  15652. /**
  15653. * Figures out what unit to format a set of ticks with
  15654. */
  15655. function determineUnitForFormatting(ticks, minUnit, min, max) {
  15656. var duration = moment.duration(moment(max).diff(moment(min)));
  15657. var ilen = UNITS.length;
  15658. var i, unit;
  15659. for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) {
  15660. unit = UNITS[i];
  15661. if (INTERVALS[unit].common && duration.as(unit) >= ticks.length) {
  15662. return unit;
  15663. }
  15664. }
  15665. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  15666. }
  15667. function determineMajorUnit(unit) {
  15668. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  15669. if (INTERVALS[UNITS[i]].common) {
  15670. return UNITS[i];
  15671. }
  15672. }
  15673. }
  15674. /**
  15675. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  15676. * `minor` unit, aligned on the `major` unit and using the given scale time `options`.
  15677. * Important: this method can return ticks outside the min and max range, it's the
  15678. * responsibility of the calling code to clamp values if needed.
  15679. */
  15680. function generate(min, max, capacity, options) {
  15681. var timeOpts = options.time;
  15682. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  15683. var major = determineMajorUnit(minor);
  15684. var stepSize = helpers.valueOrDefault(timeOpts.stepSize, timeOpts.unitStepSize);
  15685. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  15686. var majorTicksEnabled = options.ticks.major.enabled;
  15687. var interval = INTERVALS[minor];
  15688. var first = moment(min);
  15689. var last = moment(max);
  15690. var ticks = [];
  15691. var time;
  15692. if (!stepSize) {
  15693. stepSize = determineStepSize(min, max, minor, capacity);
  15694. }
  15695. // For 'week' unit, handle the first day of week option
  15696. if (weekday) {
  15697. first = first.isoWeekday(weekday);
  15698. last = last.isoWeekday(weekday);
  15699. }
  15700. // Align first/last ticks on unit
  15701. first = first.startOf(weekday ? 'day' : minor);
  15702. last = last.startOf(weekday ? 'day' : minor);
  15703. // Make sure that the last tick include max
  15704. if (last < max) {
  15705. last.add(1, minor);
  15706. }
  15707. time = moment(first);
  15708. if (majorTicksEnabled && major && !weekday && !timeOpts.round) {
  15709. // Align the first tick on the previous `minor` unit aligned on the `major` unit:
  15710. // we first aligned time on the previous `major` unit then add the number of full
  15711. // stepSize there is between first and the previous major time.
  15712. time.startOf(major);
  15713. time.add(~~((first - time) / (interval.size * stepSize)) * stepSize, minor);
  15714. }
  15715. for (; time < last; time.add(stepSize, minor)) {
  15716. ticks.push(+time);
  15717. }
  15718. ticks.push(+time);
  15719. return ticks;
  15720. }
  15721. /**
  15722. * Returns the right and left offsets from edges in the form of {left, right}.
  15723. * Offsets are added when the `offset` option is true.
  15724. */
  15725. function computeOffsets(table, ticks, min, max, options) {
  15726. var left = 0;
  15727. var right = 0;
  15728. var upper, lower;
  15729. if (options.offset && ticks.length) {
  15730. if (!options.time.min) {
  15731. upper = ticks.length > 1 ? ticks[1] : max;
  15732. lower = ticks[0];
  15733. left = (
  15734. interpolate(table, 'time', upper, 'pos') -
  15735. interpolate(table, 'time', lower, 'pos')
  15736. ) / 2;
  15737. }
  15738. if (!options.time.max) {
  15739. upper = ticks[ticks.length - 1];
  15740. lower = ticks.length > 1 ? ticks[ticks.length - 2] : min;
  15741. right = (
  15742. interpolate(table, 'time', upper, 'pos') -
  15743. interpolate(table, 'time', lower, 'pos')
  15744. ) / 2;
  15745. }
  15746. }
  15747. return {left: left, right: right};
  15748. }
  15749. function ticksFromTimestamps(values, majorUnit) {
  15750. var ticks = [];
  15751. var i, ilen, value, major;
  15752. for (i = 0, ilen = values.length; i < ilen; ++i) {
  15753. value = values[i];
  15754. major = majorUnit ? value === +moment(value).startOf(majorUnit) : false;
  15755. ticks.push({
  15756. value: value,
  15757. major: major
  15758. });
  15759. }
  15760. return ticks;
  15761. }
  15762. function determineLabelFormat(data, timeOpts) {
  15763. var i, momentDate, hasTime;
  15764. var ilen = data.length;
  15765. // find the label with the most parts (milliseconds, minutes, etc.)
  15766. // format all labels with the same level of detail as the most specific label
  15767. for (i = 0; i < ilen; i++) {
  15768. momentDate = momentify(data[i], timeOpts);
  15769. if (momentDate.millisecond() !== 0) {
  15770. return 'MMM D, YYYY h:mm:ss.SSS a';
  15771. }
  15772. if (momentDate.second() !== 0 || momentDate.minute() !== 0 || momentDate.hour() !== 0) {
  15773. hasTime = true;
  15774. }
  15775. }
  15776. if (hasTime) {
  15777. return 'MMM D, YYYY h:mm:ss a';
  15778. }
  15779. return 'MMM D, YYYY';
  15780. }
  15781. module.exports = function() {
  15782. var defaultConfig = {
  15783. position: 'bottom',
  15784. /**
  15785. * Data distribution along the scale:
  15786. * - 'linear': data are spread according to their time (distances can vary),
  15787. * - 'series': data are spread at the same distance from each other.
  15788. * @see https://github.com/chartjs/Chart.js/pull/4507
  15789. * @since 2.7.0
  15790. */
  15791. distribution: 'linear',
  15792. /**
  15793. * Scale boundary strategy (bypassed by min/max time options)
  15794. * - `data`: make sure data are fully visible, ticks outside are removed
  15795. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  15796. * @see https://github.com/chartjs/Chart.js/pull/4556
  15797. * @since 2.7.0
  15798. */
  15799. bounds: 'data',
  15800. time: {
  15801. parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
  15802. format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
  15803. unit: false, // false == automatic or override with week, month, year, etc.
  15804. round: false, // none, or override with week, month, year, etc.
  15805. displayFormat: false, // DEPRECATED
  15806. isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/
  15807. minUnit: 'millisecond',
  15808. // defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/
  15809. displayFormats: {
  15810. millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM,
  15811. second: 'h:mm:ss a', // 11:20:01 AM
  15812. minute: 'h:mm a', // 11:20 AM
  15813. hour: 'hA', // 5PM
  15814. day: 'MMM D', // Sep 4
  15815. week: 'll', // Week 46, or maybe "[W]WW - YYYY" ?
  15816. month: 'MMM YYYY', // Sept 2015
  15817. quarter: '[Q]Q - YYYY', // Q3
  15818. year: 'YYYY' // 2015
  15819. },
  15820. },
  15821. ticks: {
  15822. autoSkip: false,
  15823. /**
  15824. * Ticks generation input values:
  15825. * - 'auto': generates "optimal" ticks based on scale size and time options.
  15826. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  15827. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  15828. * @see https://github.com/chartjs/Chart.js/pull/4507
  15829. * @since 2.7.0
  15830. */
  15831. source: 'auto',
  15832. major: {
  15833. enabled: false
  15834. }
  15835. }
  15836. };
  15837. var TimeScale = Scale.extend({
  15838. initialize: function() {
  15839. if (!moment) {
  15840. throw new Error('Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com');
  15841. }
  15842. this.mergeTicksOptions();
  15843. Scale.prototype.initialize.call(this);
  15844. },
  15845. update: function() {
  15846. var me = this;
  15847. var options = me.options;
  15848. // DEPRECATIONS: output a message only one time per update
  15849. if (options.time && options.time.format) {
  15850. console.warn('options.time.format is deprecated and replaced by options.time.parser.');
  15851. }
  15852. return Scale.prototype.update.apply(me, arguments);
  15853. },
  15854. /**
  15855. * Allows data to be referenced via 't' attribute
  15856. */
  15857. getRightValue: function(rawValue) {
  15858. if (rawValue && rawValue.t !== undefined) {
  15859. rawValue = rawValue.t;
  15860. }
  15861. return Scale.prototype.getRightValue.call(this, rawValue);
  15862. },
  15863. determineDataLimits: function() {
  15864. var me = this;
  15865. var chart = me.chart;
  15866. var timeOpts = me.options.time;
  15867. var unit = timeOpts.unit || 'day';
  15868. var min = MAX_INTEGER;
  15869. var max = MIN_INTEGER;
  15870. var timestamps = [];
  15871. var datasets = [];
  15872. var labels = [];
  15873. var i, j, ilen, jlen, data, timestamp;
  15874. // Convert labels to timestamps
  15875. for (i = 0, ilen = chart.data.labels.length; i < ilen; ++i) {
  15876. labels.push(parse(chart.data.labels[i], me));
  15877. }
  15878. // Convert data to timestamps
  15879. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  15880. if (chart.isDatasetVisible(i)) {
  15881. data = chart.data.datasets[i].data;
  15882. // Let's consider that all data have the same format.
  15883. if (helpers.isObject(data[0])) {
  15884. datasets[i] = [];
  15885. for (j = 0, jlen = data.length; j < jlen; ++j) {
  15886. timestamp = parse(data[j], me);
  15887. timestamps.push(timestamp);
  15888. datasets[i][j] = timestamp;
  15889. }
  15890. } else {
  15891. timestamps.push.apply(timestamps, labels);
  15892. datasets[i] = labels.slice(0);
  15893. }
  15894. } else {
  15895. datasets[i] = [];
  15896. }
  15897. }
  15898. if (labels.length) {
  15899. // Sort labels **after** data have been converted
  15900. labels = arrayUnique(labels).sort(sorter);
  15901. min = Math.min(min, labels[0]);
  15902. max = Math.max(max, labels[labels.length - 1]);
  15903. }
  15904. if (timestamps.length) {
  15905. timestamps = arrayUnique(timestamps).sort(sorter);
  15906. min = Math.min(min, timestamps[0]);
  15907. max = Math.max(max, timestamps[timestamps.length - 1]);
  15908. }
  15909. min = parse(timeOpts.min, me) || min;
  15910. max = parse(timeOpts.max, me) || max;
  15911. // In case there is no valid min/max, set limits based on unit time option
  15912. min = min === MAX_INTEGER ? +moment().startOf(unit) : min;
  15913. max = max === MIN_INTEGER ? +moment().endOf(unit) + 1 : max;
  15914. // Make sure that max is strictly higher than min (required by the lookup table)
  15915. me.min = Math.min(min, max);
  15916. me.max = Math.max(min + 1, max);
  15917. // PRIVATE
  15918. me._horizontal = me.isHorizontal();
  15919. me._table = [];
  15920. me._timestamps = {
  15921. data: timestamps,
  15922. datasets: datasets,
  15923. labels: labels
  15924. };
  15925. },
  15926. buildTicks: function() {
  15927. var me = this;
  15928. var min = me.min;
  15929. var max = me.max;
  15930. var options = me.options;
  15931. var timeOpts = options.time;
  15932. var timestamps = [];
  15933. var ticks = [];
  15934. var i, ilen, timestamp;
  15935. switch (options.ticks.source) {
  15936. case 'data':
  15937. timestamps = me._timestamps.data;
  15938. break;
  15939. case 'labels':
  15940. timestamps = me._timestamps.labels;
  15941. break;
  15942. case 'auto':
  15943. default:
  15944. timestamps = generate(min, max, me.getLabelCapacity(min), options);
  15945. }
  15946. if (options.bounds === 'ticks' && timestamps.length) {
  15947. min = timestamps[0];
  15948. max = timestamps[timestamps.length - 1];
  15949. }
  15950. // Enforce limits with user min/max options
  15951. min = parse(timeOpts.min, me) || min;
  15952. max = parse(timeOpts.max, me) || max;
  15953. // Remove ticks outside the min/max range
  15954. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  15955. timestamp = timestamps[i];
  15956. if (timestamp >= min && timestamp <= max) {
  15957. ticks.push(timestamp);
  15958. }
  15959. }
  15960. me.min = min;
  15961. me.max = max;
  15962. // PRIVATE
  15963. me._unit = timeOpts.unit || determineUnitForFormatting(ticks, timeOpts.minUnit, me.min, me.max);
  15964. me._majorUnit = determineMajorUnit(me._unit);
  15965. me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
  15966. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  15967. me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts);
  15968. return ticksFromTimestamps(ticks, me._majorUnit);
  15969. },
  15970. getLabelForIndex: function(index, datasetIndex) {
  15971. var me = this;
  15972. var data = me.chart.data;
  15973. var timeOpts = me.options.time;
  15974. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  15975. var value = data.datasets[datasetIndex].data[index];
  15976. if (helpers.isObject(value)) {
  15977. label = me.getRightValue(value);
  15978. }
  15979. if (timeOpts.tooltipFormat) {
  15980. return momentify(label, timeOpts).format(timeOpts.tooltipFormat);
  15981. }
  15982. if (typeof label === 'string') {
  15983. return label;
  15984. }
  15985. return momentify(label, timeOpts).format(me._labelFormat);
  15986. },
  15987. /**
  15988. * Function to format an individual tick mark
  15989. * @private
  15990. */
  15991. tickFormatFunction: function(tick, index, ticks, formatOverride) {
  15992. var me = this;
  15993. var options = me.options;
  15994. var time = tick.valueOf();
  15995. var formats = options.time.displayFormats;
  15996. var minorFormat = formats[me._unit];
  15997. var majorUnit = me._majorUnit;
  15998. var majorFormat = formats[majorUnit];
  15999. var majorTime = tick.clone().startOf(majorUnit).valueOf();
  16000. var majorTickOpts = options.ticks.major;
  16001. var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime;
  16002. var label = tick.format(formatOverride ? formatOverride : major ? majorFormat : minorFormat);
  16003. var tickOpts = major ? majorTickOpts : options.ticks.minor;
  16004. var formatter = helpers.valueOrDefault(tickOpts.callback, tickOpts.userCallback);
  16005. return formatter ? formatter(label, index, ticks) : label;
  16006. },
  16007. convertTicksToLabels: function(ticks) {
  16008. var labels = [];
  16009. var i, ilen;
  16010. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  16011. labels.push(this.tickFormatFunction(moment(ticks[i].value), i, ticks));
  16012. }
  16013. return labels;
  16014. },
  16015. /**
  16016. * @private
  16017. */
  16018. getPixelForOffset: function(time) {
  16019. var me = this;
  16020. var size = me._horizontal ? me.width : me.height;
  16021. var start = me._horizontal ? me.left : me.top;
  16022. var pos = interpolate(me._table, 'time', time, 'pos');
  16023. return start + size * (me._offsets.left + pos) / (me._offsets.left + 1 + me._offsets.right);
  16024. },
  16025. getPixelForValue: function(value, index, datasetIndex) {
  16026. var me = this;
  16027. var time = null;
  16028. if (index !== undefined && datasetIndex !== undefined) {
  16029. time = me._timestamps.datasets[datasetIndex][index];
  16030. }
  16031. if (time === null) {
  16032. time = parse(value, me);
  16033. }
  16034. if (time !== null) {
  16035. return me.getPixelForOffset(time);
  16036. }
  16037. },
  16038. getPixelForTick: function(index) {
  16039. var ticks = this.getTicks();
  16040. return index >= 0 && index < ticks.length ?
  16041. this.getPixelForOffset(ticks[index].value) :
  16042. null;
  16043. },
  16044. getValueForPixel: function(pixel) {
  16045. var me = this;
  16046. var size = me._horizontal ? me.width : me.height;
  16047. var start = me._horizontal ? me.left : me.top;
  16048. var pos = (size ? (pixel - start) / size : 0) * (me._offsets.left + 1 + me._offsets.left) - me._offsets.right;
  16049. var time = interpolate(me._table, 'pos', pos, 'time');
  16050. return moment(time);
  16051. },
  16052. /**
  16053. * Crude approximation of what the label width might be
  16054. * @private
  16055. */
  16056. getLabelWidth: function(label) {
  16057. var me = this;
  16058. var ticksOpts = me.options.ticks;
  16059. var tickLabelWidth = me.ctx.measureText(label).width;
  16060. var angle = helpers.toRadians(ticksOpts.maxRotation);
  16061. var cosRotation = Math.cos(angle);
  16062. var sinRotation = Math.sin(angle);
  16063. var tickFontSize = helpers.valueOrDefault(ticksOpts.fontSize, defaults.global.defaultFontSize);
  16064. return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
  16065. },
  16066. /**
  16067. * @private
  16068. */
  16069. getLabelCapacity: function(exampleTime) {
  16070. var me = this;
  16071. var formatOverride = me.options.time.displayFormats.millisecond; // Pick the longest format for guestimation
  16072. var exampleLabel = me.tickFormatFunction(moment(exampleTime), 0, [], formatOverride);
  16073. var tickLabelWidth = me.getLabelWidth(exampleLabel);
  16074. var innerWidth = me.isHorizontal() ? me.width : me.height;
  16075. var capacity = Math.floor(innerWidth / tickLabelWidth);
  16076. return capacity > 0 ? capacity : 1;
  16077. }
  16078. });
  16079. scaleService.registerScaleType('time', TimeScale, defaultConfig);
  16080. };
  16081. },{"26":26,"33":33,"34":34,"46":46,"6":6}]},{},[7])(7)
  16082. });