You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 2 година
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776
  1. /*!
  2. * Chart.js v2.9.4
  3. * https://www.chartjs.org
  4. * (c) 2020 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  9. typeof define === 'function' && define.amd ? define(factory) :
  10. (global = global || self, global.Chart = factory());
  11. }(this, (function () { 'use strict';
  12. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  13. function commonjsRequire () {
  14. throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
  15. }
  16. function createCommonjsModule(fn, module) {
  17. return module = { exports: {} }, fn(module, module.exports), module.exports;
  18. }
  19. function getCjsExportFromNamespace (n) {
  20. return n && n['default'] || n;
  21. }
  22. var colorName = {
  23. "aliceblue": [240, 248, 255],
  24. "antiquewhite": [250, 235, 215],
  25. "aqua": [0, 255, 255],
  26. "aquamarine": [127, 255, 212],
  27. "azure": [240, 255, 255],
  28. "beige": [245, 245, 220],
  29. "bisque": [255, 228, 196],
  30. "black": [0, 0, 0],
  31. "blanchedalmond": [255, 235, 205],
  32. "blue": [0, 0, 255],
  33. "blueviolet": [138, 43, 226],
  34. "brown": [165, 42, 42],
  35. "burlywood": [222, 184, 135],
  36. "cadetblue": [95, 158, 160],
  37. "chartreuse": [127, 255, 0],
  38. "chocolate": [210, 105, 30],
  39. "coral": [255, 127, 80],
  40. "cornflowerblue": [100, 149, 237],
  41. "cornsilk": [255, 248, 220],
  42. "crimson": [220, 20, 60],
  43. "cyan": [0, 255, 255],
  44. "darkblue": [0, 0, 139],
  45. "darkcyan": [0, 139, 139],
  46. "darkgoldenrod": [184, 134, 11],
  47. "darkgray": [169, 169, 169],
  48. "darkgreen": [0, 100, 0],
  49. "darkgrey": [169, 169, 169],
  50. "darkkhaki": [189, 183, 107],
  51. "darkmagenta": [139, 0, 139],
  52. "darkolivegreen": [85, 107, 47],
  53. "darkorange": [255, 140, 0],
  54. "darkorchid": [153, 50, 204],
  55. "darkred": [139, 0, 0],
  56. "darksalmon": [233, 150, 122],
  57. "darkseagreen": [143, 188, 143],
  58. "darkslateblue": [72, 61, 139],
  59. "darkslategray": [47, 79, 79],
  60. "darkslategrey": [47, 79, 79],
  61. "darkturquoise": [0, 206, 209],
  62. "darkviolet": [148, 0, 211],
  63. "deeppink": [255, 20, 147],
  64. "deepskyblue": [0, 191, 255],
  65. "dimgray": [105, 105, 105],
  66. "dimgrey": [105, 105, 105],
  67. "dodgerblue": [30, 144, 255],
  68. "firebrick": [178, 34, 34],
  69. "floralwhite": [255, 250, 240],
  70. "forestgreen": [34, 139, 34],
  71. "fuchsia": [255, 0, 255],
  72. "gainsboro": [220, 220, 220],
  73. "ghostwhite": [248, 248, 255],
  74. "gold": [255, 215, 0],
  75. "goldenrod": [218, 165, 32],
  76. "gray": [128, 128, 128],
  77. "green": [0, 128, 0],
  78. "greenyellow": [173, 255, 47],
  79. "grey": [128, 128, 128],
  80. "honeydew": [240, 255, 240],
  81. "hotpink": [255, 105, 180],
  82. "indianred": [205, 92, 92],
  83. "indigo": [75, 0, 130],
  84. "ivory": [255, 255, 240],
  85. "khaki": [240, 230, 140],
  86. "lavender": [230, 230, 250],
  87. "lavenderblush": [255, 240, 245],
  88. "lawngreen": [124, 252, 0],
  89. "lemonchiffon": [255, 250, 205],
  90. "lightblue": [173, 216, 230],
  91. "lightcoral": [240, 128, 128],
  92. "lightcyan": [224, 255, 255],
  93. "lightgoldenrodyellow": [250, 250, 210],
  94. "lightgray": [211, 211, 211],
  95. "lightgreen": [144, 238, 144],
  96. "lightgrey": [211, 211, 211],
  97. "lightpink": [255, 182, 193],
  98. "lightsalmon": [255, 160, 122],
  99. "lightseagreen": [32, 178, 170],
  100. "lightskyblue": [135, 206, 250],
  101. "lightslategray": [119, 136, 153],
  102. "lightslategrey": [119, 136, 153],
  103. "lightsteelblue": [176, 196, 222],
  104. "lightyellow": [255, 255, 224],
  105. "lime": [0, 255, 0],
  106. "limegreen": [50, 205, 50],
  107. "linen": [250, 240, 230],
  108. "magenta": [255, 0, 255],
  109. "maroon": [128, 0, 0],
  110. "mediumaquamarine": [102, 205, 170],
  111. "mediumblue": [0, 0, 205],
  112. "mediumorchid": [186, 85, 211],
  113. "mediumpurple": [147, 112, 219],
  114. "mediumseagreen": [60, 179, 113],
  115. "mediumslateblue": [123, 104, 238],
  116. "mediumspringgreen": [0, 250, 154],
  117. "mediumturquoise": [72, 209, 204],
  118. "mediumvioletred": [199, 21, 133],
  119. "midnightblue": [25, 25, 112],
  120. "mintcream": [245, 255, 250],
  121. "mistyrose": [255, 228, 225],
  122. "moccasin": [255, 228, 181],
  123. "navajowhite": [255, 222, 173],
  124. "navy": [0, 0, 128],
  125. "oldlace": [253, 245, 230],
  126. "olive": [128, 128, 0],
  127. "olivedrab": [107, 142, 35],
  128. "orange": [255, 165, 0],
  129. "orangered": [255, 69, 0],
  130. "orchid": [218, 112, 214],
  131. "palegoldenrod": [238, 232, 170],
  132. "palegreen": [152, 251, 152],
  133. "paleturquoise": [175, 238, 238],
  134. "palevioletred": [219, 112, 147],
  135. "papayawhip": [255, 239, 213],
  136. "peachpuff": [255, 218, 185],
  137. "peru": [205, 133, 63],
  138. "pink": [255, 192, 203],
  139. "plum": [221, 160, 221],
  140. "powderblue": [176, 224, 230],
  141. "purple": [128, 0, 128],
  142. "rebeccapurple": [102, 51, 153],
  143. "red": [255, 0, 0],
  144. "rosybrown": [188, 143, 143],
  145. "royalblue": [65, 105, 225],
  146. "saddlebrown": [139, 69, 19],
  147. "salmon": [250, 128, 114],
  148. "sandybrown": [244, 164, 96],
  149. "seagreen": [46, 139, 87],
  150. "seashell": [255, 245, 238],
  151. "sienna": [160, 82, 45],
  152. "silver": [192, 192, 192],
  153. "skyblue": [135, 206, 235],
  154. "slateblue": [106, 90, 205],
  155. "slategray": [112, 128, 144],
  156. "slategrey": [112, 128, 144],
  157. "snow": [255, 250, 250],
  158. "springgreen": [0, 255, 127],
  159. "steelblue": [70, 130, 180],
  160. "tan": [210, 180, 140],
  161. "teal": [0, 128, 128],
  162. "thistle": [216, 191, 216],
  163. "tomato": [255, 99, 71],
  164. "turquoise": [64, 224, 208],
  165. "violet": [238, 130, 238],
  166. "wheat": [245, 222, 179],
  167. "white": [255, 255, 255],
  168. "whitesmoke": [245, 245, 245],
  169. "yellow": [255, 255, 0],
  170. "yellowgreen": [154, 205, 50]
  171. };
  172. var conversions = createCommonjsModule(function (module) {
  173. /* MIT license */
  174. // NOTE: conversions should only return primitive values (i.e. arrays, or
  175. // values that give correct `typeof` results).
  176. // do not use box values types (i.e. Number(), String(), etc.)
  177. var reverseKeywords = {};
  178. for (var key in colorName) {
  179. if (colorName.hasOwnProperty(key)) {
  180. reverseKeywords[colorName[key]] = key;
  181. }
  182. }
  183. var convert = module.exports = {
  184. rgb: {channels: 3, labels: 'rgb'},
  185. hsl: {channels: 3, labels: 'hsl'},
  186. hsv: {channels: 3, labels: 'hsv'},
  187. hwb: {channels: 3, labels: 'hwb'},
  188. cmyk: {channels: 4, labels: 'cmyk'},
  189. xyz: {channels: 3, labels: 'xyz'},
  190. lab: {channels: 3, labels: 'lab'},
  191. lch: {channels: 3, labels: 'lch'},
  192. hex: {channels: 1, labels: ['hex']},
  193. keyword: {channels: 1, labels: ['keyword']},
  194. ansi16: {channels: 1, labels: ['ansi16']},
  195. ansi256: {channels: 1, labels: ['ansi256']},
  196. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  197. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  198. gray: {channels: 1, labels: ['gray']}
  199. };
  200. // hide .channels and .labels properties
  201. for (var model in convert) {
  202. if (convert.hasOwnProperty(model)) {
  203. if (!('channels' in convert[model])) {
  204. throw new Error('missing channels property: ' + model);
  205. }
  206. if (!('labels' in convert[model])) {
  207. throw new Error('missing channel labels property: ' + model);
  208. }
  209. if (convert[model].labels.length !== convert[model].channels) {
  210. throw new Error('channel and label counts mismatch: ' + model);
  211. }
  212. var channels = convert[model].channels;
  213. var labels = convert[model].labels;
  214. delete convert[model].channels;
  215. delete convert[model].labels;
  216. Object.defineProperty(convert[model], 'channels', {value: channels});
  217. Object.defineProperty(convert[model], 'labels', {value: labels});
  218. }
  219. }
  220. convert.rgb.hsl = function (rgb) {
  221. var r = rgb[0] / 255;
  222. var g = rgb[1] / 255;
  223. var b = rgb[2] / 255;
  224. var min = Math.min(r, g, b);
  225. var max = Math.max(r, g, b);
  226. var delta = max - min;
  227. var h;
  228. var s;
  229. var l;
  230. if (max === min) {
  231. h = 0;
  232. } else if (r === max) {
  233. h = (g - b) / delta;
  234. } else if (g === max) {
  235. h = 2 + (b - r) / delta;
  236. } else if (b === max) {
  237. h = 4 + (r - g) / delta;
  238. }
  239. h = Math.min(h * 60, 360);
  240. if (h < 0) {
  241. h += 360;
  242. }
  243. l = (min + max) / 2;
  244. if (max === min) {
  245. s = 0;
  246. } else if (l <= 0.5) {
  247. s = delta / (max + min);
  248. } else {
  249. s = delta / (2 - max - min);
  250. }
  251. return [h, s * 100, l * 100];
  252. };
  253. convert.rgb.hsv = function (rgb) {
  254. var rdif;
  255. var gdif;
  256. var bdif;
  257. var h;
  258. var s;
  259. var r = rgb[0] / 255;
  260. var g = rgb[1] / 255;
  261. var b = rgb[2] / 255;
  262. var v = Math.max(r, g, b);
  263. var diff = v - Math.min(r, g, b);
  264. var diffc = function (c) {
  265. return (v - c) / 6 / diff + 1 / 2;
  266. };
  267. if (diff === 0) {
  268. h = s = 0;
  269. } else {
  270. s = diff / v;
  271. rdif = diffc(r);
  272. gdif = diffc(g);
  273. bdif = diffc(b);
  274. if (r === v) {
  275. h = bdif - gdif;
  276. } else if (g === v) {
  277. h = (1 / 3) + rdif - bdif;
  278. } else if (b === v) {
  279. h = (2 / 3) + gdif - rdif;
  280. }
  281. if (h < 0) {
  282. h += 1;
  283. } else if (h > 1) {
  284. h -= 1;
  285. }
  286. }
  287. return [
  288. h * 360,
  289. s * 100,
  290. v * 100
  291. ];
  292. };
  293. convert.rgb.hwb = function (rgb) {
  294. var r = rgb[0];
  295. var g = rgb[1];
  296. var b = rgb[2];
  297. var h = convert.rgb.hsl(rgb)[0];
  298. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  299. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  300. return [h, w * 100, b * 100];
  301. };
  302. convert.rgb.cmyk = function (rgb) {
  303. var r = rgb[0] / 255;
  304. var g = rgb[1] / 255;
  305. var b = rgb[2] / 255;
  306. var c;
  307. var m;
  308. var y;
  309. var k;
  310. k = Math.min(1 - r, 1 - g, 1 - b);
  311. c = (1 - r - k) / (1 - k) || 0;
  312. m = (1 - g - k) / (1 - k) || 0;
  313. y = (1 - b - k) / (1 - k) || 0;
  314. return [c * 100, m * 100, y * 100, k * 100];
  315. };
  316. /**
  317. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  318. * */
  319. function comparativeDistance(x, y) {
  320. return (
  321. Math.pow(x[0] - y[0], 2) +
  322. Math.pow(x[1] - y[1], 2) +
  323. Math.pow(x[2] - y[2], 2)
  324. );
  325. }
  326. convert.rgb.keyword = function (rgb) {
  327. var reversed = reverseKeywords[rgb];
  328. if (reversed) {
  329. return reversed;
  330. }
  331. var currentClosestDistance = Infinity;
  332. var currentClosestKeyword;
  333. for (var keyword in colorName) {
  334. if (colorName.hasOwnProperty(keyword)) {
  335. var value = colorName[keyword];
  336. // Compute comparative distance
  337. var distance = comparativeDistance(rgb, value);
  338. // Check if its less, if so set as closest
  339. if (distance < currentClosestDistance) {
  340. currentClosestDistance = distance;
  341. currentClosestKeyword = keyword;
  342. }
  343. }
  344. }
  345. return currentClosestKeyword;
  346. };
  347. convert.keyword.rgb = function (keyword) {
  348. return colorName[keyword];
  349. };
  350. convert.rgb.xyz = function (rgb) {
  351. var r = rgb[0] / 255;
  352. var g = rgb[1] / 255;
  353. var b = rgb[2] / 255;
  354. // assume sRGB
  355. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  356. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  357. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  358. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  359. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  360. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  361. return [x * 100, y * 100, z * 100];
  362. };
  363. convert.rgb.lab = function (rgb) {
  364. var xyz = convert.rgb.xyz(rgb);
  365. var x = xyz[0];
  366. var y = xyz[1];
  367. var z = xyz[2];
  368. var l;
  369. var a;
  370. var b;
  371. x /= 95.047;
  372. y /= 100;
  373. z /= 108.883;
  374. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  375. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  376. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  377. l = (116 * y) - 16;
  378. a = 500 * (x - y);
  379. b = 200 * (y - z);
  380. return [l, a, b];
  381. };
  382. convert.hsl.rgb = function (hsl) {
  383. var h = hsl[0] / 360;
  384. var s = hsl[1] / 100;
  385. var l = hsl[2] / 100;
  386. var t1;
  387. var t2;
  388. var t3;
  389. var rgb;
  390. var val;
  391. if (s === 0) {
  392. val = l * 255;
  393. return [val, val, val];
  394. }
  395. if (l < 0.5) {
  396. t2 = l * (1 + s);
  397. } else {
  398. t2 = l + s - l * s;
  399. }
  400. t1 = 2 * l - t2;
  401. rgb = [0, 0, 0];
  402. for (var i = 0; i < 3; i++) {
  403. t3 = h + 1 / 3 * -(i - 1);
  404. if (t3 < 0) {
  405. t3++;
  406. }
  407. if (t3 > 1) {
  408. t3--;
  409. }
  410. if (6 * t3 < 1) {
  411. val = t1 + (t2 - t1) * 6 * t3;
  412. } else if (2 * t3 < 1) {
  413. val = t2;
  414. } else if (3 * t3 < 2) {
  415. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  416. } else {
  417. val = t1;
  418. }
  419. rgb[i] = val * 255;
  420. }
  421. return rgb;
  422. };
  423. convert.hsl.hsv = function (hsl) {
  424. var h = hsl[0];
  425. var s = hsl[1] / 100;
  426. var l = hsl[2] / 100;
  427. var smin = s;
  428. var lmin = Math.max(l, 0.01);
  429. var sv;
  430. var v;
  431. l *= 2;
  432. s *= (l <= 1) ? l : 2 - l;
  433. smin *= lmin <= 1 ? lmin : 2 - lmin;
  434. v = (l + s) / 2;
  435. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  436. return [h, sv * 100, v * 100];
  437. };
  438. convert.hsv.rgb = function (hsv) {
  439. var h = hsv[0] / 60;
  440. var s = hsv[1] / 100;
  441. var v = hsv[2] / 100;
  442. var hi = Math.floor(h) % 6;
  443. var f = h - Math.floor(h);
  444. var p = 255 * v * (1 - s);
  445. var q = 255 * v * (1 - (s * f));
  446. var t = 255 * v * (1 - (s * (1 - f)));
  447. v *= 255;
  448. switch (hi) {
  449. case 0:
  450. return [v, t, p];
  451. case 1:
  452. return [q, v, p];
  453. case 2:
  454. return [p, v, t];
  455. case 3:
  456. return [p, q, v];
  457. case 4:
  458. return [t, p, v];
  459. case 5:
  460. return [v, p, q];
  461. }
  462. };
  463. convert.hsv.hsl = function (hsv) {
  464. var h = hsv[0];
  465. var s = hsv[1] / 100;
  466. var v = hsv[2] / 100;
  467. var vmin = Math.max(v, 0.01);
  468. var lmin;
  469. var sl;
  470. var l;
  471. l = (2 - s) * v;
  472. lmin = (2 - s) * vmin;
  473. sl = s * vmin;
  474. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  475. sl = sl || 0;
  476. l /= 2;
  477. return [h, sl * 100, l * 100];
  478. };
  479. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  480. convert.hwb.rgb = function (hwb) {
  481. var h = hwb[0] / 360;
  482. var wh = hwb[1] / 100;
  483. var bl = hwb[2] / 100;
  484. var ratio = wh + bl;
  485. var i;
  486. var v;
  487. var f;
  488. var n;
  489. // wh + bl cant be > 1
  490. if (ratio > 1) {
  491. wh /= ratio;
  492. bl /= ratio;
  493. }
  494. i = Math.floor(6 * h);
  495. v = 1 - bl;
  496. f = 6 * h - i;
  497. if ((i & 0x01) !== 0) {
  498. f = 1 - f;
  499. }
  500. n = wh + f * (v - wh); // linear interpolation
  501. var r;
  502. var g;
  503. var b;
  504. switch (i) {
  505. default:
  506. case 6:
  507. case 0: r = v; g = n; b = wh; break;
  508. case 1: r = n; g = v; b = wh; break;
  509. case 2: r = wh; g = v; b = n; break;
  510. case 3: r = wh; g = n; b = v; break;
  511. case 4: r = n; g = wh; b = v; break;
  512. case 5: r = v; g = wh; b = n; break;
  513. }
  514. return [r * 255, g * 255, b * 255];
  515. };
  516. convert.cmyk.rgb = function (cmyk) {
  517. var c = cmyk[0] / 100;
  518. var m = cmyk[1] / 100;
  519. var y = cmyk[2] / 100;
  520. var k = cmyk[3] / 100;
  521. var r;
  522. var g;
  523. var b;
  524. r = 1 - Math.min(1, c * (1 - k) + k);
  525. g = 1 - Math.min(1, m * (1 - k) + k);
  526. b = 1 - Math.min(1, y * (1 - k) + k);
  527. return [r * 255, g * 255, b * 255];
  528. };
  529. convert.xyz.rgb = function (xyz) {
  530. var x = xyz[0] / 100;
  531. var y = xyz[1] / 100;
  532. var z = xyz[2] / 100;
  533. var r;
  534. var g;
  535. var b;
  536. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  537. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  538. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  539. // assume sRGB
  540. r = r > 0.0031308
  541. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  542. : r * 12.92;
  543. g = g > 0.0031308
  544. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  545. : g * 12.92;
  546. b = b > 0.0031308
  547. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  548. : b * 12.92;
  549. r = Math.min(Math.max(0, r), 1);
  550. g = Math.min(Math.max(0, g), 1);
  551. b = Math.min(Math.max(0, b), 1);
  552. return [r * 255, g * 255, b * 255];
  553. };
  554. convert.xyz.lab = function (xyz) {
  555. var x = xyz[0];
  556. var y = xyz[1];
  557. var z = xyz[2];
  558. var l;
  559. var a;
  560. var b;
  561. x /= 95.047;
  562. y /= 100;
  563. z /= 108.883;
  564. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  565. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  566. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  567. l = (116 * y) - 16;
  568. a = 500 * (x - y);
  569. b = 200 * (y - z);
  570. return [l, a, b];
  571. };
  572. convert.lab.xyz = function (lab) {
  573. var l = lab[0];
  574. var a = lab[1];
  575. var b = lab[2];
  576. var x;
  577. var y;
  578. var z;
  579. y = (l + 16) / 116;
  580. x = a / 500 + y;
  581. z = y - b / 200;
  582. var y2 = Math.pow(y, 3);
  583. var x2 = Math.pow(x, 3);
  584. var z2 = Math.pow(z, 3);
  585. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  586. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  587. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  588. x *= 95.047;
  589. y *= 100;
  590. z *= 108.883;
  591. return [x, y, z];
  592. };
  593. convert.lab.lch = function (lab) {
  594. var l = lab[0];
  595. var a = lab[1];
  596. var b = lab[2];
  597. var hr;
  598. var h;
  599. var c;
  600. hr = Math.atan2(b, a);
  601. h = hr * 360 / 2 / Math.PI;
  602. if (h < 0) {
  603. h += 360;
  604. }
  605. c = Math.sqrt(a * a + b * b);
  606. return [l, c, h];
  607. };
  608. convert.lch.lab = function (lch) {
  609. var l = lch[0];
  610. var c = lch[1];
  611. var h = lch[2];
  612. var a;
  613. var b;
  614. var hr;
  615. hr = h / 360 * 2 * Math.PI;
  616. a = c * Math.cos(hr);
  617. b = c * Math.sin(hr);
  618. return [l, a, b];
  619. };
  620. convert.rgb.ansi16 = function (args) {
  621. var r = args[0];
  622. var g = args[1];
  623. var b = args[2];
  624. var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  625. value = Math.round(value / 50);
  626. if (value === 0) {
  627. return 30;
  628. }
  629. var ansi = 30
  630. + ((Math.round(b / 255) << 2)
  631. | (Math.round(g / 255) << 1)
  632. | Math.round(r / 255));
  633. if (value === 2) {
  634. ansi += 60;
  635. }
  636. return ansi;
  637. };
  638. convert.hsv.ansi16 = function (args) {
  639. // optimization here; we already know the value and don't need to get
  640. // it converted for us.
  641. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  642. };
  643. convert.rgb.ansi256 = function (args) {
  644. var r = args[0];
  645. var g = args[1];
  646. var b = args[2];
  647. // we use the extended greyscale palette here, with the exception of
  648. // black and white. normal palette only has 4 greyscale shades.
  649. if (r === g && g === b) {
  650. if (r < 8) {
  651. return 16;
  652. }
  653. if (r > 248) {
  654. return 231;
  655. }
  656. return Math.round(((r - 8) / 247) * 24) + 232;
  657. }
  658. var ansi = 16
  659. + (36 * Math.round(r / 255 * 5))
  660. + (6 * Math.round(g / 255 * 5))
  661. + Math.round(b / 255 * 5);
  662. return ansi;
  663. };
  664. convert.ansi16.rgb = function (args) {
  665. var color = args % 10;
  666. // handle greyscale
  667. if (color === 0 || color === 7) {
  668. if (args > 50) {
  669. color += 3.5;
  670. }
  671. color = color / 10.5 * 255;
  672. return [color, color, color];
  673. }
  674. var mult = (~~(args > 50) + 1) * 0.5;
  675. var r = ((color & 1) * mult) * 255;
  676. var g = (((color >> 1) & 1) * mult) * 255;
  677. var b = (((color >> 2) & 1) * mult) * 255;
  678. return [r, g, b];
  679. };
  680. convert.ansi256.rgb = function (args) {
  681. // handle greyscale
  682. if (args >= 232) {
  683. var c = (args - 232) * 10 + 8;
  684. return [c, c, c];
  685. }
  686. args -= 16;
  687. var rem;
  688. var r = Math.floor(args / 36) / 5 * 255;
  689. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  690. var b = (rem % 6) / 5 * 255;
  691. return [r, g, b];
  692. };
  693. convert.rgb.hex = function (args) {
  694. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  695. + ((Math.round(args[1]) & 0xFF) << 8)
  696. + (Math.round(args[2]) & 0xFF);
  697. var string = integer.toString(16).toUpperCase();
  698. return '000000'.substring(string.length) + string;
  699. };
  700. convert.hex.rgb = function (args) {
  701. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  702. if (!match) {
  703. return [0, 0, 0];
  704. }
  705. var colorString = match[0];
  706. if (match[0].length === 3) {
  707. colorString = colorString.split('').map(function (char) {
  708. return char + char;
  709. }).join('');
  710. }
  711. var integer = parseInt(colorString, 16);
  712. var r = (integer >> 16) & 0xFF;
  713. var g = (integer >> 8) & 0xFF;
  714. var b = integer & 0xFF;
  715. return [r, g, b];
  716. };
  717. convert.rgb.hcg = function (rgb) {
  718. var r = rgb[0] / 255;
  719. var g = rgb[1] / 255;
  720. var b = rgb[2] / 255;
  721. var max = Math.max(Math.max(r, g), b);
  722. var min = Math.min(Math.min(r, g), b);
  723. var chroma = (max - min);
  724. var grayscale;
  725. var hue;
  726. if (chroma < 1) {
  727. grayscale = min / (1 - chroma);
  728. } else {
  729. grayscale = 0;
  730. }
  731. if (chroma <= 0) {
  732. hue = 0;
  733. } else
  734. if (max === r) {
  735. hue = ((g - b) / chroma) % 6;
  736. } else
  737. if (max === g) {
  738. hue = 2 + (b - r) / chroma;
  739. } else {
  740. hue = 4 + (r - g) / chroma + 4;
  741. }
  742. hue /= 6;
  743. hue %= 1;
  744. return [hue * 360, chroma * 100, grayscale * 100];
  745. };
  746. convert.hsl.hcg = function (hsl) {
  747. var s = hsl[1] / 100;
  748. var l = hsl[2] / 100;
  749. var c = 1;
  750. var f = 0;
  751. if (l < 0.5) {
  752. c = 2.0 * s * l;
  753. } else {
  754. c = 2.0 * s * (1.0 - l);
  755. }
  756. if (c < 1.0) {
  757. f = (l - 0.5 * c) / (1.0 - c);
  758. }
  759. return [hsl[0], c * 100, f * 100];
  760. };
  761. convert.hsv.hcg = function (hsv) {
  762. var s = hsv[1] / 100;
  763. var v = hsv[2] / 100;
  764. var c = s * v;
  765. var f = 0;
  766. if (c < 1.0) {
  767. f = (v - c) / (1 - c);
  768. }
  769. return [hsv[0], c * 100, f * 100];
  770. };
  771. convert.hcg.rgb = function (hcg) {
  772. var h = hcg[0] / 360;
  773. var c = hcg[1] / 100;
  774. var g = hcg[2] / 100;
  775. if (c === 0.0) {
  776. return [g * 255, g * 255, g * 255];
  777. }
  778. var pure = [0, 0, 0];
  779. var hi = (h % 1) * 6;
  780. var v = hi % 1;
  781. var w = 1 - v;
  782. var mg = 0;
  783. switch (Math.floor(hi)) {
  784. case 0:
  785. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  786. case 1:
  787. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  788. case 2:
  789. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  790. case 3:
  791. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  792. case 4:
  793. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  794. default:
  795. pure[0] = 1; pure[1] = 0; pure[2] = w;
  796. }
  797. mg = (1.0 - c) * g;
  798. return [
  799. (c * pure[0] + mg) * 255,
  800. (c * pure[1] + mg) * 255,
  801. (c * pure[2] + mg) * 255
  802. ];
  803. };
  804. convert.hcg.hsv = function (hcg) {
  805. var c = hcg[1] / 100;
  806. var g = hcg[2] / 100;
  807. var v = c + g * (1.0 - c);
  808. var f = 0;
  809. if (v > 0.0) {
  810. f = c / v;
  811. }
  812. return [hcg[0], f * 100, v * 100];
  813. };
  814. convert.hcg.hsl = function (hcg) {
  815. var c = hcg[1] / 100;
  816. var g = hcg[2] / 100;
  817. var l = g * (1.0 - c) + 0.5 * c;
  818. var s = 0;
  819. if (l > 0.0 && l < 0.5) {
  820. s = c / (2 * l);
  821. } else
  822. if (l >= 0.5 && l < 1.0) {
  823. s = c / (2 * (1 - l));
  824. }
  825. return [hcg[0], s * 100, l * 100];
  826. };
  827. convert.hcg.hwb = function (hcg) {
  828. var c = hcg[1] / 100;
  829. var g = hcg[2] / 100;
  830. var v = c + g * (1.0 - c);
  831. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  832. };
  833. convert.hwb.hcg = function (hwb) {
  834. var w = hwb[1] / 100;
  835. var b = hwb[2] / 100;
  836. var v = 1 - b;
  837. var c = v - w;
  838. var g = 0;
  839. if (c < 1) {
  840. g = (v - c) / (1 - c);
  841. }
  842. return [hwb[0], c * 100, g * 100];
  843. };
  844. convert.apple.rgb = function (apple) {
  845. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  846. };
  847. convert.rgb.apple = function (rgb) {
  848. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  849. };
  850. convert.gray.rgb = function (args) {
  851. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  852. };
  853. convert.gray.hsl = convert.gray.hsv = function (args) {
  854. return [0, 0, args[0]];
  855. };
  856. convert.gray.hwb = function (gray) {
  857. return [0, 100, gray[0]];
  858. };
  859. convert.gray.cmyk = function (gray) {
  860. return [0, 0, 0, gray[0]];
  861. };
  862. convert.gray.lab = function (gray) {
  863. return [gray[0], 0, 0];
  864. };
  865. convert.gray.hex = function (gray) {
  866. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  867. var integer = (val << 16) + (val << 8) + val;
  868. var string = integer.toString(16).toUpperCase();
  869. return '000000'.substring(string.length) + string;
  870. };
  871. convert.rgb.gray = function (rgb) {
  872. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  873. return [val / 255 * 100];
  874. };
  875. });
  876. var conversions_1 = conversions.rgb;
  877. var conversions_2 = conversions.hsl;
  878. var conversions_3 = conversions.hsv;
  879. var conversions_4 = conversions.hwb;
  880. var conversions_5 = conversions.cmyk;
  881. var conversions_6 = conversions.xyz;
  882. var conversions_7 = conversions.lab;
  883. var conversions_8 = conversions.lch;
  884. var conversions_9 = conversions.hex;
  885. var conversions_10 = conversions.keyword;
  886. var conversions_11 = conversions.ansi16;
  887. var conversions_12 = conversions.ansi256;
  888. var conversions_13 = conversions.hcg;
  889. var conversions_14 = conversions.apple;
  890. var conversions_15 = conversions.gray;
  891. /*
  892. this function routes a model to all other models.
  893. all functions that are routed have a property `.conversion` attached
  894. to the returned synthetic function. This property is an array
  895. of strings, each with the steps in between the 'from' and 'to'
  896. color models (inclusive).
  897. conversions that are not possible simply are not included.
  898. */
  899. function buildGraph() {
  900. var graph = {};
  901. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  902. var models = Object.keys(conversions);
  903. for (var len = models.length, i = 0; i < len; i++) {
  904. graph[models[i]] = {
  905. // http://jsperf.com/1-vs-infinity
  906. // micro-opt, but this is simple.
  907. distance: -1,
  908. parent: null
  909. };
  910. }
  911. return graph;
  912. }
  913. // https://en.wikipedia.org/wiki/Breadth-first_search
  914. function deriveBFS(fromModel) {
  915. var graph = buildGraph();
  916. var queue = [fromModel]; // unshift -> queue -> pop
  917. graph[fromModel].distance = 0;
  918. while (queue.length) {
  919. var current = queue.pop();
  920. var adjacents = Object.keys(conversions[current]);
  921. for (var len = adjacents.length, i = 0; i < len; i++) {
  922. var adjacent = adjacents[i];
  923. var node = graph[adjacent];
  924. if (node.distance === -1) {
  925. node.distance = graph[current].distance + 1;
  926. node.parent = current;
  927. queue.unshift(adjacent);
  928. }
  929. }
  930. }
  931. return graph;
  932. }
  933. function link(from, to) {
  934. return function (args) {
  935. return to(from(args));
  936. };
  937. }
  938. function wrapConversion(toModel, graph) {
  939. var path = [graph[toModel].parent, toModel];
  940. var fn = conversions[graph[toModel].parent][toModel];
  941. var cur = graph[toModel].parent;
  942. while (graph[cur].parent) {
  943. path.unshift(graph[cur].parent);
  944. fn = link(conversions[graph[cur].parent][cur], fn);
  945. cur = graph[cur].parent;
  946. }
  947. fn.conversion = path;
  948. return fn;
  949. }
  950. var route = function (fromModel) {
  951. var graph = deriveBFS(fromModel);
  952. var conversion = {};
  953. var models = Object.keys(graph);
  954. for (var len = models.length, i = 0; i < len; i++) {
  955. var toModel = models[i];
  956. var node = graph[toModel];
  957. if (node.parent === null) {
  958. // no possible conversion, or this node is the source model.
  959. continue;
  960. }
  961. conversion[toModel] = wrapConversion(toModel, graph);
  962. }
  963. return conversion;
  964. };
  965. var convert = {};
  966. var models = Object.keys(conversions);
  967. function wrapRaw(fn) {
  968. var wrappedFn = function (args) {
  969. if (args === undefined || args === null) {
  970. return args;
  971. }
  972. if (arguments.length > 1) {
  973. args = Array.prototype.slice.call(arguments);
  974. }
  975. return fn(args);
  976. };
  977. // preserve .conversion property if there is one
  978. if ('conversion' in fn) {
  979. wrappedFn.conversion = fn.conversion;
  980. }
  981. return wrappedFn;
  982. }
  983. function wrapRounded(fn) {
  984. var wrappedFn = function (args) {
  985. if (args === undefined || args === null) {
  986. return args;
  987. }
  988. if (arguments.length > 1) {
  989. args = Array.prototype.slice.call(arguments);
  990. }
  991. var result = fn(args);
  992. // we're assuming the result is an array here.
  993. // see notice in conversions.js; don't use box types
  994. // in conversion functions.
  995. if (typeof result === 'object') {
  996. for (var len = result.length, i = 0; i < len; i++) {
  997. result[i] = Math.round(result[i]);
  998. }
  999. }
  1000. return result;
  1001. };
  1002. // preserve .conversion property if there is one
  1003. if ('conversion' in fn) {
  1004. wrappedFn.conversion = fn.conversion;
  1005. }
  1006. return wrappedFn;
  1007. }
  1008. models.forEach(function (fromModel) {
  1009. convert[fromModel] = {};
  1010. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  1011. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  1012. var routes = route(fromModel);
  1013. var routeModels = Object.keys(routes);
  1014. routeModels.forEach(function (toModel) {
  1015. var fn = routes[toModel];
  1016. convert[fromModel][toModel] = wrapRounded(fn);
  1017. convert[fromModel][toModel].raw = wrapRaw(fn);
  1018. });
  1019. });
  1020. var colorConvert = convert;
  1021. var colorName$1 = {
  1022. "aliceblue": [240, 248, 255],
  1023. "antiquewhite": [250, 235, 215],
  1024. "aqua": [0, 255, 255],
  1025. "aquamarine": [127, 255, 212],
  1026. "azure": [240, 255, 255],
  1027. "beige": [245, 245, 220],
  1028. "bisque": [255, 228, 196],
  1029. "black": [0, 0, 0],
  1030. "blanchedalmond": [255, 235, 205],
  1031. "blue": [0, 0, 255],
  1032. "blueviolet": [138, 43, 226],
  1033. "brown": [165, 42, 42],
  1034. "burlywood": [222, 184, 135],
  1035. "cadetblue": [95, 158, 160],
  1036. "chartreuse": [127, 255, 0],
  1037. "chocolate": [210, 105, 30],
  1038. "coral": [255, 127, 80],
  1039. "cornflowerblue": [100, 149, 237],
  1040. "cornsilk": [255, 248, 220],
  1041. "crimson": [220, 20, 60],
  1042. "cyan": [0, 255, 255],
  1043. "darkblue": [0, 0, 139],
  1044. "darkcyan": [0, 139, 139],
  1045. "darkgoldenrod": [184, 134, 11],
  1046. "darkgray": [169, 169, 169],
  1047. "darkgreen": [0, 100, 0],
  1048. "darkgrey": [169, 169, 169],
  1049. "darkkhaki": [189, 183, 107],
  1050. "darkmagenta": [139, 0, 139],
  1051. "darkolivegreen": [85, 107, 47],
  1052. "darkorange": [255, 140, 0],
  1053. "darkorchid": [153, 50, 204],
  1054. "darkred": [139, 0, 0],
  1055. "darksalmon": [233, 150, 122],
  1056. "darkseagreen": [143, 188, 143],
  1057. "darkslateblue": [72, 61, 139],
  1058. "darkslategray": [47, 79, 79],
  1059. "darkslategrey": [47, 79, 79],
  1060. "darkturquoise": [0, 206, 209],
  1061. "darkviolet": [148, 0, 211],
  1062. "deeppink": [255, 20, 147],
  1063. "deepskyblue": [0, 191, 255],
  1064. "dimgray": [105, 105, 105],
  1065. "dimgrey": [105, 105, 105],
  1066. "dodgerblue": [30, 144, 255],
  1067. "firebrick": [178, 34, 34],
  1068. "floralwhite": [255, 250, 240],
  1069. "forestgreen": [34, 139, 34],
  1070. "fuchsia": [255, 0, 255],
  1071. "gainsboro": [220, 220, 220],
  1072. "ghostwhite": [248, 248, 255],
  1073. "gold": [255, 215, 0],
  1074. "goldenrod": [218, 165, 32],
  1075. "gray": [128, 128, 128],
  1076. "green": [0, 128, 0],
  1077. "greenyellow": [173, 255, 47],
  1078. "grey": [128, 128, 128],
  1079. "honeydew": [240, 255, 240],
  1080. "hotpink": [255, 105, 180],
  1081. "indianred": [205, 92, 92],
  1082. "indigo": [75, 0, 130],
  1083. "ivory": [255, 255, 240],
  1084. "khaki": [240, 230, 140],
  1085. "lavender": [230, 230, 250],
  1086. "lavenderblush": [255, 240, 245],
  1087. "lawngreen": [124, 252, 0],
  1088. "lemonchiffon": [255, 250, 205],
  1089. "lightblue": [173, 216, 230],
  1090. "lightcoral": [240, 128, 128],
  1091. "lightcyan": [224, 255, 255],
  1092. "lightgoldenrodyellow": [250, 250, 210],
  1093. "lightgray": [211, 211, 211],
  1094. "lightgreen": [144, 238, 144],
  1095. "lightgrey": [211, 211, 211],
  1096. "lightpink": [255, 182, 193],
  1097. "lightsalmon": [255, 160, 122],
  1098. "lightseagreen": [32, 178, 170],
  1099. "lightskyblue": [135, 206, 250],
  1100. "lightslategray": [119, 136, 153],
  1101. "lightslategrey": [119, 136, 153],
  1102. "lightsteelblue": [176, 196, 222],
  1103. "lightyellow": [255, 255, 224],
  1104. "lime": [0, 255, 0],
  1105. "limegreen": [50, 205, 50],
  1106. "linen": [250, 240, 230],
  1107. "magenta": [255, 0, 255],
  1108. "maroon": [128, 0, 0],
  1109. "mediumaquamarine": [102, 205, 170],
  1110. "mediumblue": [0, 0, 205],
  1111. "mediumorchid": [186, 85, 211],
  1112. "mediumpurple": [147, 112, 219],
  1113. "mediumseagreen": [60, 179, 113],
  1114. "mediumslateblue": [123, 104, 238],
  1115. "mediumspringgreen": [0, 250, 154],
  1116. "mediumturquoise": [72, 209, 204],
  1117. "mediumvioletred": [199, 21, 133],
  1118. "midnightblue": [25, 25, 112],
  1119. "mintcream": [245, 255, 250],
  1120. "mistyrose": [255, 228, 225],
  1121. "moccasin": [255, 228, 181],
  1122. "navajowhite": [255, 222, 173],
  1123. "navy": [0, 0, 128],
  1124. "oldlace": [253, 245, 230],
  1125. "olive": [128, 128, 0],
  1126. "olivedrab": [107, 142, 35],
  1127. "orange": [255, 165, 0],
  1128. "orangered": [255, 69, 0],
  1129. "orchid": [218, 112, 214],
  1130. "palegoldenrod": [238, 232, 170],
  1131. "palegreen": [152, 251, 152],
  1132. "paleturquoise": [175, 238, 238],
  1133. "palevioletred": [219, 112, 147],
  1134. "papayawhip": [255, 239, 213],
  1135. "peachpuff": [255, 218, 185],
  1136. "peru": [205, 133, 63],
  1137. "pink": [255, 192, 203],
  1138. "plum": [221, 160, 221],
  1139. "powderblue": [176, 224, 230],
  1140. "purple": [128, 0, 128],
  1141. "rebeccapurple": [102, 51, 153],
  1142. "red": [255, 0, 0],
  1143. "rosybrown": [188, 143, 143],
  1144. "royalblue": [65, 105, 225],
  1145. "saddlebrown": [139, 69, 19],
  1146. "salmon": [250, 128, 114],
  1147. "sandybrown": [244, 164, 96],
  1148. "seagreen": [46, 139, 87],
  1149. "seashell": [255, 245, 238],
  1150. "sienna": [160, 82, 45],
  1151. "silver": [192, 192, 192],
  1152. "skyblue": [135, 206, 235],
  1153. "slateblue": [106, 90, 205],
  1154. "slategray": [112, 128, 144],
  1155. "slategrey": [112, 128, 144],
  1156. "snow": [255, 250, 250],
  1157. "springgreen": [0, 255, 127],
  1158. "steelblue": [70, 130, 180],
  1159. "tan": [210, 180, 140],
  1160. "teal": [0, 128, 128],
  1161. "thistle": [216, 191, 216],
  1162. "tomato": [255, 99, 71],
  1163. "turquoise": [64, 224, 208],
  1164. "violet": [238, 130, 238],
  1165. "wheat": [245, 222, 179],
  1166. "white": [255, 255, 255],
  1167. "whitesmoke": [245, 245, 245],
  1168. "yellow": [255, 255, 0],
  1169. "yellowgreen": [154, 205, 50]
  1170. };
  1171. /* MIT license */
  1172. var colorString = {
  1173. getRgba: getRgba,
  1174. getHsla: getHsla,
  1175. getRgb: getRgb,
  1176. getHsl: getHsl,
  1177. getHwb: getHwb,
  1178. getAlpha: getAlpha,
  1179. hexString: hexString,
  1180. rgbString: rgbString,
  1181. rgbaString: rgbaString,
  1182. percentString: percentString,
  1183. percentaString: percentaString,
  1184. hslString: hslString,
  1185. hslaString: hslaString,
  1186. hwbString: hwbString,
  1187. keyword: keyword
  1188. };
  1189. function getRgba(string) {
  1190. if (!string) {
  1191. return;
  1192. }
  1193. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  1194. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  1195. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1196. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1197. keyword = /(\w+)/;
  1198. var rgb = [0, 0, 0],
  1199. a = 1,
  1200. match = string.match(abbr),
  1201. hexAlpha = "";
  1202. if (match) {
  1203. match = match[1];
  1204. hexAlpha = match[3];
  1205. for (var i = 0; i < rgb.length; i++) {
  1206. rgb[i] = parseInt(match[i] + match[i], 16);
  1207. }
  1208. if (hexAlpha) {
  1209. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  1210. }
  1211. }
  1212. else if (match = string.match(hex)) {
  1213. hexAlpha = match[2];
  1214. match = match[1];
  1215. for (var i = 0; i < rgb.length; i++) {
  1216. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  1217. }
  1218. if (hexAlpha) {
  1219. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  1220. }
  1221. }
  1222. else if (match = string.match(rgba)) {
  1223. for (var i = 0; i < rgb.length; i++) {
  1224. rgb[i] = parseInt(match[i + 1]);
  1225. }
  1226. a = parseFloat(match[4]);
  1227. }
  1228. else if (match = string.match(per)) {
  1229. for (var i = 0; i < rgb.length; i++) {
  1230. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  1231. }
  1232. a = parseFloat(match[4]);
  1233. }
  1234. else if (match = string.match(keyword)) {
  1235. if (match[1] == "transparent") {
  1236. return [0, 0, 0, 0];
  1237. }
  1238. rgb = colorName$1[match[1]];
  1239. if (!rgb) {
  1240. return;
  1241. }
  1242. }
  1243. for (var i = 0; i < rgb.length; i++) {
  1244. rgb[i] = scale(rgb[i], 0, 255);
  1245. }
  1246. if (!a && a != 0) {
  1247. a = 1;
  1248. }
  1249. else {
  1250. a = scale(a, 0, 1);
  1251. }
  1252. rgb[3] = a;
  1253. return rgb;
  1254. }
  1255. function getHsla(string) {
  1256. if (!string) {
  1257. return;
  1258. }
  1259. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1260. var match = string.match(hsl);
  1261. if (match) {
  1262. var alpha = parseFloat(match[4]);
  1263. var h = scale(parseInt(match[1]), 0, 360),
  1264. s = scale(parseFloat(match[2]), 0, 100),
  1265. l = scale(parseFloat(match[3]), 0, 100),
  1266. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1267. return [h, s, l, a];
  1268. }
  1269. }
  1270. function getHwb(string) {
  1271. if (!string) {
  1272. return;
  1273. }
  1274. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1275. var match = string.match(hwb);
  1276. if (match) {
  1277. var alpha = parseFloat(match[4]);
  1278. var h = scale(parseInt(match[1]), 0, 360),
  1279. w = scale(parseFloat(match[2]), 0, 100),
  1280. b = scale(parseFloat(match[3]), 0, 100),
  1281. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1282. return [h, w, b, a];
  1283. }
  1284. }
  1285. function getRgb(string) {
  1286. var rgba = getRgba(string);
  1287. return rgba && rgba.slice(0, 3);
  1288. }
  1289. function getHsl(string) {
  1290. var hsla = getHsla(string);
  1291. return hsla && hsla.slice(0, 3);
  1292. }
  1293. function getAlpha(string) {
  1294. var vals = getRgba(string);
  1295. if (vals) {
  1296. return vals[3];
  1297. }
  1298. else if (vals = getHsla(string)) {
  1299. return vals[3];
  1300. }
  1301. else if (vals = getHwb(string)) {
  1302. return vals[3];
  1303. }
  1304. }
  1305. // generators
  1306. function hexString(rgba, a) {
  1307. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  1308. return "#" + hexDouble(rgba[0])
  1309. + hexDouble(rgba[1])
  1310. + hexDouble(rgba[2])
  1311. + (
  1312. (a >= 0 && a < 1)
  1313. ? hexDouble(Math.round(a * 255))
  1314. : ""
  1315. );
  1316. }
  1317. function rgbString(rgba, alpha) {
  1318. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1319. return rgbaString(rgba, alpha);
  1320. }
  1321. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  1322. }
  1323. function rgbaString(rgba, alpha) {
  1324. if (alpha === undefined) {
  1325. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  1326. }
  1327. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  1328. + ", " + alpha + ")";
  1329. }
  1330. function percentString(rgba, alpha) {
  1331. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1332. return percentaString(rgba, alpha);
  1333. }
  1334. var r = Math.round(rgba[0]/255 * 100),
  1335. g = Math.round(rgba[1]/255 * 100),
  1336. b = Math.round(rgba[2]/255 * 100);
  1337. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  1338. }
  1339. function percentaString(rgba, alpha) {
  1340. var r = Math.round(rgba[0]/255 * 100),
  1341. g = Math.round(rgba[1]/255 * 100),
  1342. b = Math.round(rgba[2]/255 * 100);
  1343. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  1344. }
  1345. function hslString(hsla, alpha) {
  1346. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1347. return hslaString(hsla, alpha);
  1348. }
  1349. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1350. }
  1351. function hslaString(hsla, alpha) {
  1352. if (alpha === undefined) {
  1353. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1354. }
  1355. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1356. + alpha + ")";
  1357. }
  1358. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1359. // (hwb have alpha optional & 1 is default value)
  1360. function hwbString(hwb, alpha) {
  1361. if (alpha === undefined) {
  1362. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1363. }
  1364. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1365. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1366. }
  1367. function keyword(rgb) {
  1368. return reverseNames[rgb.slice(0, 3)];
  1369. }
  1370. // helpers
  1371. function scale(num, min, max) {
  1372. return Math.min(Math.max(min, num), max);
  1373. }
  1374. function hexDouble(num) {
  1375. var str = num.toString(16).toUpperCase();
  1376. return (str.length < 2) ? "0" + str : str;
  1377. }
  1378. //create a list of reverse color names
  1379. var reverseNames = {};
  1380. for (var name in colorName$1) {
  1381. reverseNames[colorName$1[name]] = name;
  1382. }
  1383. /* MIT license */
  1384. var Color = function (obj) {
  1385. if (obj instanceof Color) {
  1386. return obj;
  1387. }
  1388. if (!(this instanceof Color)) {
  1389. return new Color(obj);
  1390. }
  1391. this.valid = false;
  1392. this.values = {
  1393. rgb: [0, 0, 0],
  1394. hsl: [0, 0, 0],
  1395. hsv: [0, 0, 0],
  1396. hwb: [0, 0, 0],
  1397. cmyk: [0, 0, 0, 0],
  1398. alpha: 1
  1399. };
  1400. // parse Color() argument
  1401. var vals;
  1402. if (typeof obj === 'string') {
  1403. vals = colorString.getRgba(obj);
  1404. if (vals) {
  1405. this.setValues('rgb', vals);
  1406. } else if (vals = colorString.getHsla(obj)) {
  1407. this.setValues('hsl', vals);
  1408. } else if (vals = colorString.getHwb(obj)) {
  1409. this.setValues('hwb', vals);
  1410. }
  1411. } else if (typeof obj === 'object') {
  1412. vals = obj;
  1413. if (vals.r !== undefined || vals.red !== undefined) {
  1414. this.setValues('rgb', vals);
  1415. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1416. this.setValues('hsl', vals);
  1417. } else if (vals.v !== undefined || vals.value !== undefined) {
  1418. this.setValues('hsv', vals);
  1419. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1420. this.setValues('hwb', vals);
  1421. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1422. this.setValues('cmyk', vals);
  1423. }
  1424. }
  1425. };
  1426. Color.prototype = {
  1427. isValid: function () {
  1428. return this.valid;
  1429. },
  1430. rgb: function () {
  1431. return this.setSpace('rgb', arguments);
  1432. },
  1433. hsl: function () {
  1434. return this.setSpace('hsl', arguments);
  1435. },
  1436. hsv: function () {
  1437. return this.setSpace('hsv', arguments);
  1438. },
  1439. hwb: function () {
  1440. return this.setSpace('hwb', arguments);
  1441. },
  1442. cmyk: function () {
  1443. return this.setSpace('cmyk', arguments);
  1444. },
  1445. rgbArray: function () {
  1446. return this.values.rgb;
  1447. },
  1448. hslArray: function () {
  1449. return this.values.hsl;
  1450. },
  1451. hsvArray: function () {
  1452. return this.values.hsv;
  1453. },
  1454. hwbArray: function () {
  1455. var values = this.values;
  1456. if (values.alpha !== 1) {
  1457. return values.hwb.concat([values.alpha]);
  1458. }
  1459. return values.hwb;
  1460. },
  1461. cmykArray: function () {
  1462. return this.values.cmyk;
  1463. },
  1464. rgbaArray: function () {
  1465. var values = this.values;
  1466. return values.rgb.concat([values.alpha]);
  1467. },
  1468. hslaArray: function () {
  1469. var values = this.values;
  1470. return values.hsl.concat([values.alpha]);
  1471. },
  1472. alpha: function (val) {
  1473. if (val === undefined) {
  1474. return this.values.alpha;
  1475. }
  1476. this.setValues('alpha', val);
  1477. return this;
  1478. },
  1479. red: function (val) {
  1480. return this.setChannel('rgb', 0, val);
  1481. },
  1482. green: function (val) {
  1483. return this.setChannel('rgb', 1, val);
  1484. },
  1485. blue: function (val) {
  1486. return this.setChannel('rgb', 2, val);
  1487. },
  1488. hue: function (val) {
  1489. if (val) {
  1490. val %= 360;
  1491. val = val < 0 ? 360 + val : val;
  1492. }
  1493. return this.setChannel('hsl', 0, val);
  1494. },
  1495. saturation: function (val) {
  1496. return this.setChannel('hsl', 1, val);
  1497. },
  1498. lightness: function (val) {
  1499. return this.setChannel('hsl', 2, val);
  1500. },
  1501. saturationv: function (val) {
  1502. return this.setChannel('hsv', 1, val);
  1503. },
  1504. whiteness: function (val) {
  1505. return this.setChannel('hwb', 1, val);
  1506. },
  1507. blackness: function (val) {
  1508. return this.setChannel('hwb', 2, val);
  1509. },
  1510. value: function (val) {
  1511. return this.setChannel('hsv', 2, val);
  1512. },
  1513. cyan: function (val) {
  1514. return this.setChannel('cmyk', 0, val);
  1515. },
  1516. magenta: function (val) {
  1517. return this.setChannel('cmyk', 1, val);
  1518. },
  1519. yellow: function (val) {
  1520. return this.setChannel('cmyk', 2, val);
  1521. },
  1522. black: function (val) {
  1523. return this.setChannel('cmyk', 3, val);
  1524. },
  1525. hexString: function () {
  1526. return colorString.hexString(this.values.rgb);
  1527. },
  1528. rgbString: function () {
  1529. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1530. },
  1531. rgbaString: function () {
  1532. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1533. },
  1534. percentString: function () {
  1535. return colorString.percentString(this.values.rgb, this.values.alpha);
  1536. },
  1537. hslString: function () {
  1538. return colorString.hslString(this.values.hsl, this.values.alpha);
  1539. },
  1540. hslaString: function () {
  1541. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1542. },
  1543. hwbString: function () {
  1544. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1545. },
  1546. keyword: function () {
  1547. return colorString.keyword(this.values.rgb, this.values.alpha);
  1548. },
  1549. rgbNumber: function () {
  1550. var rgb = this.values.rgb;
  1551. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1552. },
  1553. luminosity: function () {
  1554. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1555. var rgb = this.values.rgb;
  1556. var lum = [];
  1557. for (var i = 0; i < rgb.length; i++) {
  1558. var chan = rgb[i] / 255;
  1559. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1560. }
  1561. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1562. },
  1563. contrast: function (color2) {
  1564. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1565. var lum1 = this.luminosity();
  1566. var lum2 = color2.luminosity();
  1567. if (lum1 > lum2) {
  1568. return (lum1 + 0.05) / (lum2 + 0.05);
  1569. }
  1570. return (lum2 + 0.05) / (lum1 + 0.05);
  1571. },
  1572. level: function (color2) {
  1573. var contrastRatio = this.contrast(color2);
  1574. if (contrastRatio >= 7.1) {
  1575. return 'AAA';
  1576. }
  1577. return (contrastRatio >= 4.5) ? 'AA' : '';
  1578. },
  1579. dark: function () {
  1580. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1581. var rgb = this.values.rgb;
  1582. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1583. return yiq < 128;
  1584. },
  1585. light: function () {
  1586. return !this.dark();
  1587. },
  1588. negate: function () {
  1589. var rgb = [];
  1590. for (var i = 0; i < 3; i++) {
  1591. rgb[i] = 255 - this.values.rgb[i];
  1592. }
  1593. this.setValues('rgb', rgb);
  1594. return this;
  1595. },
  1596. lighten: function (ratio) {
  1597. var hsl = this.values.hsl;
  1598. hsl[2] += hsl[2] * ratio;
  1599. this.setValues('hsl', hsl);
  1600. return this;
  1601. },
  1602. darken: function (ratio) {
  1603. var hsl = this.values.hsl;
  1604. hsl[2] -= hsl[2] * ratio;
  1605. this.setValues('hsl', hsl);
  1606. return this;
  1607. },
  1608. saturate: function (ratio) {
  1609. var hsl = this.values.hsl;
  1610. hsl[1] += hsl[1] * ratio;
  1611. this.setValues('hsl', hsl);
  1612. return this;
  1613. },
  1614. desaturate: function (ratio) {
  1615. var hsl = this.values.hsl;
  1616. hsl[1] -= hsl[1] * ratio;
  1617. this.setValues('hsl', hsl);
  1618. return this;
  1619. },
  1620. whiten: function (ratio) {
  1621. var hwb = this.values.hwb;
  1622. hwb[1] += hwb[1] * ratio;
  1623. this.setValues('hwb', hwb);
  1624. return this;
  1625. },
  1626. blacken: function (ratio) {
  1627. var hwb = this.values.hwb;
  1628. hwb[2] += hwb[2] * ratio;
  1629. this.setValues('hwb', hwb);
  1630. return this;
  1631. },
  1632. greyscale: function () {
  1633. var rgb = this.values.rgb;
  1634. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1635. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1636. this.setValues('rgb', [val, val, val]);
  1637. return this;
  1638. },
  1639. clearer: function (ratio) {
  1640. var alpha = this.values.alpha;
  1641. this.setValues('alpha', alpha - (alpha * ratio));
  1642. return this;
  1643. },
  1644. opaquer: function (ratio) {
  1645. var alpha = this.values.alpha;
  1646. this.setValues('alpha', alpha + (alpha * ratio));
  1647. return this;
  1648. },
  1649. rotate: function (degrees) {
  1650. var hsl = this.values.hsl;
  1651. var hue = (hsl[0] + degrees) % 360;
  1652. hsl[0] = hue < 0 ? 360 + hue : hue;
  1653. this.setValues('hsl', hsl);
  1654. return this;
  1655. },
  1656. /**
  1657. * Ported from sass implementation in C
  1658. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1659. */
  1660. mix: function (mixinColor, weight) {
  1661. var color1 = this;
  1662. var color2 = mixinColor;
  1663. var p = weight === undefined ? 0.5 : weight;
  1664. var w = 2 * p - 1;
  1665. var a = color1.alpha() - color2.alpha();
  1666. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1667. var w2 = 1 - w1;
  1668. return this
  1669. .rgb(
  1670. w1 * color1.red() + w2 * color2.red(),
  1671. w1 * color1.green() + w2 * color2.green(),
  1672. w1 * color1.blue() + w2 * color2.blue()
  1673. )
  1674. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1675. },
  1676. toJSON: function () {
  1677. return this.rgb();
  1678. },
  1679. clone: function () {
  1680. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1681. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1682. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1683. // except 'alpha' which is a number.
  1684. var result = new Color();
  1685. var source = this.values;
  1686. var target = result.values;
  1687. var value, type;
  1688. for (var prop in source) {
  1689. if (source.hasOwnProperty(prop)) {
  1690. value = source[prop];
  1691. type = ({}).toString.call(value);
  1692. if (type === '[object Array]') {
  1693. target[prop] = value.slice(0);
  1694. } else if (type === '[object Number]') {
  1695. target[prop] = value;
  1696. } else {
  1697. console.error('unexpected color value:', value);
  1698. }
  1699. }
  1700. }
  1701. return result;
  1702. }
  1703. };
  1704. Color.prototype.spaces = {
  1705. rgb: ['red', 'green', 'blue'],
  1706. hsl: ['hue', 'saturation', 'lightness'],
  1707. hsv: ['hue', 'saturation', 'value'],
  1708. hwb: ['hue', 'whiteness', 'blackness'],
  1709. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1710. };
  1711. Color.prototype.maxes = {
  1712. rgb: [255, 255, 255],
  1713. hsl: [360, 100, 100],
  1714. hsv: [360, 100, 100],
  1715. hwb: [360, 100, 100],
  1716. cmyk: [100, 100, 100, 100]
  1717. };
  1718. Color.prototype.getValues = function (space) {
  1719. var values = this.values;
  1720. var vals = {};
  1721. for (var i = 0; i < space.length; i++) {
  1722. vals[space.charAt(i)] = values[space][i];
  1723. }
  1724. if (values.alpha !== 1) {
  1725. vals.a = values.alpha;
  1726. }
  1727. // {r: 255, g: 255, b: 255, a: 0.4}
  1728. return vals;
  1729. };
  1730. Color.prototype.setValues = function (space, vals) {
  1731. var values = this.values;
  1732. var spaces = this.spaces;
  1733. var maxes = this.maxes;
  1734. var alpha = 1;
  1735. var i;
  1736. this.valid = true;
  1737. if (space === 'alpha') {
  1738. alpha = vals;
  1739. } else if (vals.length) {
  1740. // [10, 10, 10]
  1741. values[space] = vals.slice(0, space.length);
  1742. alpha = vals[space.length];
  1743. } else if (vals[space.charAt(0)] !== undefined) {
  1744. // {r: 10, g: 10, b: 10}
  1745. for (i = 0; i < space.length; i++) {
  1746. values[space][i] = vals[space.charAt(i)];
  1747. }
  1748. alpha = vals.a;
  1749. } else if (vals[spaces[space][0]] !== undefined) {
  1750. // {red: 10, green: 10, blue: 10}
  1751. var chans = spaces[space];
  1752. for (i = 0; i < space.length; i++) {
  1753. values[space][i] = vals[chans[i]];
  1754. }
  1755. alpha = vals.alpha;
  1756. }
  1757. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1758. if (space === 'alpha') {
  1759. return false;
  1760. }
  1761. var capped;
  1762. // cap values of the space prior converting all values
  1763. for (i = 0; i < space.length; i++) {
  1764. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1765. values[space][i] = Math.round(capped);
  1766. }
  1767. // convert to all the other color spaces
  1768. for (var sname in spaces) {
  1769. if (sname !== space) {
  1770. values[sname] = colorConvert[space][sname](values[space]);
  1771. }
  1772. }
  1773. return true;
  1774. };
  1775. Color.prototype.setSpace = function (space, args) {
  1776. var vals = args[0];
  1777. if (vals === undefined) {
  1778. // color.rgb()
  1779. return this.getValues(space);
  1780. }
  1781. // color.rgb(10, 10, 10)
  1782. if (typeof vals === 'number') {
  1783. vals = Array.prototype.slice.call(args);
  1784. }
  1785. this.setValues(space, vals);
  1786. return this;
  1787. };
  1788. Color.prototype.setChannel = function (space, index, val) {
  1789. var svalues = this.values[space];
  1790. if (val === undefined) {
  1791. // color.red()
  1792. return svalues[index];
  1793. } else if (val === svalues[index]) {
  1794. // color.red(color.red())
  1795. return this;
  1796. }
  1797. // color.red(100)
  1798. svalues[index] = val;
  1799. this.setValues(space, svalues);
  1800. return this;
  1801. };
  1802. if (typeof window !== 'undefined') {
  1803. window.Color = Color;
  1804. }
  1805. var chartjsColor = Color;
  1806. function isValidKey(key) {
  1807. return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;
  1808. }
  1809. /**
  1810. * @namespace Chart.helpers
  1811. */
  1812. var helpers = {
  1813. /**
  1814. * An empty function that can be used, for example, for optional callback.
  1815. */
  1816. noop: function() {},
  1817. /**
  1818. * Returns a unique id, sequentially generated from a global variable.
  1819. * @returns {number}
  1820. * @function
  1821. */
  1822. uid: (function() {
  1823. var id = 0;
  1824. return function() {
  1825. return id++;
  1826. };
  1827. }()),
  1828. /**
  1829. * Returns true if `value` is neither null nor undefined, else returns false.
  1830. * @param {*} value - The value to test.
  1831. * @returns {boolean}
  1832. * @since 2.7.0
  1833. */
  1834. isNullOrUndef: function(value) {
  1835. return value === null || typeof value === 'undefined';
  1836. },
  1837. /**
  1838. * Returns true if `value` is an array (including typed arrays), else returns false.
  1839. * @param {*} value - The value to test.
  1840. * @returns {boolean}
  1841. * @function
  1842. */
  1843. isArray: function(value) {
  1844. if (Array.isArray && Array.isArray(value)) {
  1845. return true;
  1846. }
  1847. var type = Object.prototype.toString.call(value);
  1848. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1849. return true;
  1850. }
  1851. return false;
  1852. },
  1853. /**
  1854. * Returns true if `value` is an object (excluding null), else returns false.
  1855. * @param {*} value - The value to test.
  1856. * @returns {boolean}
  1857. * @since 2.7.0
  1858. */
  1859. isObject: function(value) {
  1860. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1861. },
  1862. /**
  1863. * Returns true if `value` is a finite number, else returns false
  1864. * @param {*} value - The value to test.
  1865. * @returns {boolean}
  1866. */
  1867. isFinite: function(value) {
  1868. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1869. },
  1870. /**
  1871. * Returns `value` if defined, else returns `defaultValue`.
  1872. * @param {*} value - The value to return if defined.
  1873. * @param {*} defaultValue - The value to return if `value` is undefined.
  1874. * @returns {*}
  1875. */
  1876. valueOrDefault: function(value, defaultValue) {
  1877. return typeof value === 'undefined' ? defaultValue : value;
  1878. },
  1879. /**
  1880. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1881. * @param {Array} value - The array to lookup for value at `index`.
  1882. * @param {number} index - The index in `value` to lookup for value.
  1883. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1884. * @returns {*}
  1885. */
  1886. valueAtIndexOrDefault: function(value, index, defaultValue) {
  1887. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1888. },
  1889. /**
  1890. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1891. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1892. * @param {function} fn - The function to call.
  1893. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1894. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1895. * @returns {*}
  1896. */
  1897. callback: function(fn, args, thisArg) {
  1898. if (fn && typeof fn.call === 'function') {
  1899. return fn.apply(thisArg, args);
  1900. }
  1901. },
  1902. /**
  1903. * Note(SB) for performance sake, this method should only be used when loopable type
  1904. * is unknown or in none intensive code (not called often and small loopable). Else
  1905. * it's preferable to use a regular for() loop and save extra function calls.
  1906. * @param {object|Array} loopable - The object or array to be iterated.
  1907. * @param {function} fn - The function to call for each item.
  1908. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1909. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1910. */
  1911. each: function(loopable, fn, thisArg, reverse) {
  1912. var i, len, keys;
  1913. if (helpers.isArray(loopable)) {
  1914. len = loopable.length;
  1915. if (reverse) {
  1916. for (i = len - 1; i >= 0; i--) {
  1917. fn.call(thisArg, loopable[i], i);
  1918. }
  1919. } else {
  1920. for (i = 0; i < len; i++) {
  1921. fn.call(thisArg, loopable[i], i);
  1922. }
  1923. }
  1924. } else if (helpers.isObject(loopable)) {
  1925. keys = Object.keys(loopable);
  1926. len = keys.length;
  1927. for (i = 0; i < len; i++) {
  1928. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1929. }
  1930. }
  1931. },
  1932. /**
  1933. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1934. * @see https://stackoverflow.com/a/14853974
  1935. * @param {Array} a0 - The array to compare
  1936. * @param {Array} a1 - The array to compare
  1937. * @returns {boolean}
  1938. */
  1939. arrayEquals: function(a0, a1) {
  1940. var i, ilen, v0, v1;
  1941. if (!a0 || !a1 || a0.length !== a1.length) {
  1942. return false;
  1943. }
  1944. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1945. v0 = a0[i];
  1946. v1 = a1[i];
  1947. if (v0 instanceof Array && v1 instanceof Array) {
  1948. if (!helpers.arrayEquals(v0, v1)) {
  1949. return false;
  1950. }
  1951. } else if (v0 !== v1) {
  1952. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1953. return false;
  1954. }
  1955. }
  1956. return true;
  1957. },
  1958. /**
  1959. * Returns a deep copy of `source` without keeping references on objects and arrays.
  1960. * @param {*} source - The value to clone.
  1961. * @returns {*}
  1962. */
  1963. clone: function(source) {
  1964. if (helpers.isArray(source)) {
  1965. return source.map(helpers.clone);
  1966. }
  1967. if (helpers.isObject(source)) {
  1968. var target = Object.create(source);
  1969. var keys = Object.keys(source);
  1970. var klen = keys.length;
  1971. var k = 0;
  1972. for (; k < klen; ++k) {
  1973. target[keys[k]] = helpers.clone(source[keys[k]]);
  1974. }
  1975. return target;
  1976. }
  1977. return source;
  1978. },
  1979. /**
  1980. * The default merger when Chart.helpers.merge is called without merger option.
  1981. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  1982. * @private
  1983. */
  1984. _merger: function(key, target, source, options) {
  1985. if (!isValidKey(key)) {
  1986. // We want to ensure we do not copy prototypes over
  1987. // as this can pollute global namespaces
  1988. return;
  1989. }
  1990. var tval = target[key];
  1991. var sval = source[key];
  1992. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1993. helpers.merge(tval, sval, options);
  1994. } else {
  1995. target[key] = helpers.clone(sval);
  1996. }
  1997. },
  1998. /**
  1999. * Merges source[key] in target[key] only if target[key] is undefined.
  2000. * @private
  2001. */
  2002. _mergerIf: function(key, target, source) {
  2003. if (!isValidKey(key)) {
  2004. // We want to ensure we do not copy prototypes over
  2005. // as this can pollute global namespaces
  2006. return;
  2007. }
  2008. var tval = target[key];
  2009. var sval = source[key];
  2010. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  2011. helpers.mergeIf(tval, sval);
  2012. } else if (!target.hasOwnProperty(key)) {
  2013. target[key] = helpers.clone(sval);
  2014. }
  2015. },
  2016. /**
  2017. * Recursively deep copies `source` properties into `target` with the given `options`.
  2018. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2019. * @param {object} target - The target object in which all sources are merged into.
  2020. * @param {object|object[]} source - Object(s) to merge into `target`.
  2021. * @param {object} [options] - Merging options:
  2022. * @param {function} [options.merger] - The merge method (key, target, source, options)
  2023. * @returns {object} The `target` object.
  2024. */
  2025. merge: function(target, source, options) {
  2026. var sources = helpers.isArray(source) ? source : [source];
  2027. var ilen = sources.length;
  2028. var merge, i, keys, klen, k;
  2029. if (!helpers.isObject(target)) {
  2030. return target;
  2031. }
  2032. options = options || {};
  2033. merge = options.merger || helpers._merger;
  2034. for (i = 0; i < ilen; ++i) {
  2035. source = sources[i];
  2036. if (!helpers.isObject(source)) {
  2037. continue;
  2038. }
  2039. keys = Object.keys(source);
  2040. for (k = 0, klen = keys.length; k < klen; ++k) {
  2041. merge(keys[k], target, source, options);
  2042. }
  2043. }
  2044. return target;
  2045. },
  2046. /**
  2047. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  2048. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2049. * @param {object} target - The target object in which all sources are merged into.
  2050. * @param {object|object[]} source - Object(s) to merge into `target`.
  2051. * @returns {object} The `target` object.
  2052. */
  2053. mergeIf: function(target, source) {
  2054. return helpers.merge(target, source, {merger: helpers._mergerIf});
  2055. },
  2056. /**
  2057. * Applies the contents of two or more objects together into the first object.
  2058. * @param {object} target - The target object in which all objects are merged into.
  2059. * @param {object} arg1 - Object containing additional properties to merge in target.
  2060. * @param {object} argN - Additional objects containing properties to merge in target.
  2061. * @returns {object} The `target` object.
  2062. */
  2063. extend: Object.assign || function(target) {
  2064. return helpers.merge(target, [].slice.call(arguments, 1), {
  2065. merger: function(key, dst, src) {
  2066. dst[key] = src[key];
  2067. }
  2068. });
  2069. },
  2070. /**
  2071. * Basic javascript inheritance based on the model created in Backbone.js
  2072. */
  2073. inherits: function(extensions) {
  2074. var me = this;
  2075. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  2076. return me.apply(this, arguments);
  2077. };
  2078. var Surrogate = function() {
  2079. this.constructor = ChartElement;
  2080. };
  2081. Surrogate.prototype = me.prototype;
  2082. ChartElement.prototype = new Surrogate();
  2083. ChartElement.extend = helpers.inherits;
  2084. if (extensions) {
  2085. helpers.extend(ChartElement.prototype, extensions);
  2086. }
  2087. ChartElement.__super__ = me.prototype;
  2088. return ChartElement;
  2089. },
  2090. _deprecated: function(scope, value, previous, current) {
  2091. if (value !== undefined) {
  2092. console.warn(scope + ': "' + previous +
  2093. '" is deprecated. Please use "' + current + '" instead');
  2094. }
  2095. }
  2096. };
  2097. var helpers_core = helpers;
  2098. // DEPRECATIONS
  2099. /**
  2100. * Provided for backward compatibility, use Chart.helpers.callback instead.
  2101. * @function Chart.helpers.callCallback
  2102. * @deprecated since version 2.6.0
  2103. * @todo remove at version 3
  2104. * @private
  2105. */
  2106. helpers.callCallback = helpers.callback;
  2107. /**
  2108. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  2109. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  2110. * @function Chart.helpers.indexOf
  2111. * @deprecated since version 2.7.0
  2112. * @todo remove at version 3
  2113. * @private
  2114. */
  2115. helpers.indexOf = function(array, item, fromIndex) {
  2116. return Array.prototype.indexOf.call(array, item, fromIndex);
  2117. };
  2118. /**
  2119. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  2120. * @function Chart.helpers.getValueOrDefault
  2121. * @deprecated since version 2.7.0
  2122. * @todo remove at version 3
  2123. * @private
  2124. */
  2125. helpers.getValueOrDefault = helpers.valueOrDefault;
  2126. /**
  2127. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  2128. * @function Chart.helpers.getValueAtIndexOrDefault
  2129. * @deprecated since version 2.7.0
  2130. * @todo remove at version 3
  2131. * @private
  2132. */
  2133. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  2134. /**
  2135. * Easing functions adapted from Robert Penner's easing equations.
  2136. * @namespace Chart.helpers.easingEffects
  2137. * @see http://www.robertpenner.com/easing/
  2138. */
  2139. var effects = {
  2140. linear: function(t) {
  2141. return t;
  2142. },
  2143. easeInQuad: function(t) {
  2144. return t * t;
  2145. },
  2146. easeOutQuad: function(t) {
  2147. return -t * (t - 2);
  2148. },
  2149. easeInOutQuad: function(t) {
  2150. if ((t /= 0.5) < 1) {
  2151. return 0.5 * t * t;
  2152. }
  2153. return -0.5 * ((--t) * (t - 2) - 1);
  2154. },
  2155. easeInCubic: function(t) {
  2156. return t * t * t;
  2157. },
  2158. easeOutCubic: function(t) {
  2159. return (t = t - 1) * t * t + 1;
  2160. },
  2161. easeInOutCubic: function(t) {
  2162. if ((t /= 0.5) < 1) {
  2163. return 0.5 * t * t * t;
  2164. }
  2165. return 0.5 * ((t -= 2) * t * t + 2);
  2166. },
  2167. easeInQuart: function(t) {
  2168. return t * t * t * t;
  2169. },
  2170. easeOutQuart: function(t) {
  2171. return -((t = t - 1) * t * t * t - 1);
  2172. },
  2173. easeInOutQuart: function(t) {
  2174. if ((t /= 0.5) < 1) {
  2175. return 0.5 * t * t * t * t;
  2176. }
  2177. return -0.5 * ((t -= 2) * t * t * t - 2);
  2178. },
  2179. easeInQuint: function(t) {
  2180. return t * t * t * t * t;
  2181. },
  2182. easeOutQuint: function(t) {
  2183. return (t = t - 1) * t * t * t * t + 1;
  2184. },
  2185. easeInOutQuint: function(t) {
  2186. if ((t /= 0.5) < 1) {
  2187. return 0.5 * t * t * t * t * t;
  2188. }
  2189. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  2190. },
  2191. easeInSine: function(t) {
  2192. return -Math.cos(t * (Math.PI / 2)) + 1;
  2193. },
  2194. easeOutSine: function(t) {
  2195. return Math.sin(t * (Math.PI / 2));
  2196. },
  2197. easeInOutSine: function(t) {
  2198. return -0.5 * (Math.cos(Math.PI * t) - 1);
  2199. },
  2200. easeInExpo: function(t) {
  2201. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  2202. },
  2203. easeOutExpo: function(t) {
  2204. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  2205. },
  2206. easeInOutExpo: function(t) {
  2207. if (t === 0) {
  2208. return 0;
  2209. }
  2210. if (t === 1) {
  2211. return 1;
  2212. }
  2213. if ((t /= 0.5) < 1) {
  2214. return 0.5 * Math.pow(2, 10 * (t - 1));
  2215. }
  2216. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  2217. },
  2218. easeInCirc: function(t) {
  2219. if (t >= 1) {
  2220. return t;
  2221. }
  2222. return -(Math.sqrt(1 - t * t) - 1);
  2223. },
  2224. easeOutCirc: function(t) {
  2225. return Math.sqrt(1 - (t = t - 1) * t);
  2226. },
  2227. easeInOutCirc: function(t) {
  2228. if ((t /= 0.5) < 1) {
  2229. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  2230. }
  2231. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  2232. },
  2233. easeInElastic: function(t) {
  2234. var s = 1.70158;
  2235. var p = 0;
  2236. var a = 1;
  2237. if (t === 0) {
  2238. return 0;
  2239. }
  2240. if (t === 1) {
  2241. return 1;
  2242. }
  2243. if (!p) {
  2244. p = 0.3;
  2245. }
  2246. if (a < 1) {
  2247. a = 1;
  2248. s = p / 4;
  2249. } else {
  2250. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2251. }
  2252. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2253. },
  2254. easeOutElastic: function(t) {
  2255. var s = 1.70158;
  2256. var p = 0;
  2257. var a = 1;
  2258. if (t === 0) {
  2259. return 0;
  2260. }
  2261. if (t === 1) {
  2262. return 1;
  2263. }
  2264. if (!p) {
  2265. p = 0.3;
  2266. }
  2267. if (a < 1) {
  2268. a = 1;
  2269. s = p / 4;
  2270. } else {
  2271. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2272. }
  2273. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  2274. },
  2275. easeInOutElastic: function(t) {
  2276. var s = 1.70158;
  2277. var p = 0;
  2278. var a = 1;
  2279. if (t === 0) {
  2280. return 0;
  2281. }
  2282. if ((t /= 0.5) === 2) {
  2283. return 1;
  2284. }
  2285. if (!p) {
  2286. p = 0.45;
  2287. }
  2288. if (a < 1) {
  2289. a = 1;
  2290. s = p / 4;
  2291. } else {
  2292. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2293. }
  2294. if (t < 1) {
  2295. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2296. }
  2297. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2298. },
  2299. easeInBack: function(t) {
  2300. var s = 1.70158;
  2301. return t * t * ((s + 1) * t - s);
  2302. },
  2303. easeOutBack: function(t) {
  2304. var s = 1.70158;
  2305. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  2306. },
  2307. easeInOutBack: function(t) {
  2308. var s = 1.70158;
  2309. if ((t /= 0.5) < 1) {
  2310. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  2311. }
  2312. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  2313. },
  2314. easeInBounce: function(t) {
  2315. return 1 - effects.easeOutBounce(1 - t);
  2316. },
  2317. easeOutBounce: function(t) {
  2318. if (t < (1 / 2.75)) {
  2319. return 7.5625 * t * t;
  2320. }
  2321. if (t < (2 / 2.75)) {
  2322. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  2323. }
  2324. if (t < (2.5 / 2.75)) {
  2325. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  2326. }
  2327. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  2328. },
  2329. easeInOutBounce: function(t) {
  2330. if (t < 0.5) {
  2331. return effects.easeInBounce(t * 2) * 0.5;
  2332. }
  2333. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  2334. }
  2335. };
  2336. var helpers_easing = {
  2337. effects: effects
  2338. };
  2339. // DEPRECATIONS
  2340. /**
  2341. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  2342. * @function Chart.helpers.easingEffects
  2343. * @deprecated since version 2.7.0
  2344. * @todo remove at version 3
  2345. * @private
  2346. */
  2347. helpers_core.easingEffects = effects;
  2348. var PI = Math.PI;
  2349. var RAD_PER_DEG = PI / 180;
  2350. var DOUBLE_PI = PI * 2;
  2351. var HALF_PI = PI / 2;
  2352. var QUARTER_PI = PI / 4;
  2353. var TWO_THIRDS_PI = PI * 2 / 3;
  2354. /**
  2355. * @namespace Chart.helpers.canvas
  2356. */
  2357. var exports$1 = {
  2358. /**
  2359. * Clears the entire canvas associated to the given `chart`.
  2360. * @param {Chart} chart - The chart for which to clear the canvas.
  2361. */
  2362. clear: function(chart) {
  2363. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2364. },
  2365. /**
  2366. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2367. * given size (width, height) and the same `radius` for all corners.
  2368. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2369. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2370. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2371. * @param {number} width - The rectangle's width.
  2372. * @param {number} height - The rectangle's height.
  2373. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2374. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2375. */
  2376. roundedRect: function(ctx, x, y, width, height, radius) {
  2377. if (radius) {
  2378. var r = Math.min(radius, height / 2, width / 2);
  2379. var left = x + r;
  2380. var top = y + r;
  2381. var right = x + width - r;
  2382. var bottom = y + height - r;
  2383. ctx.moveTo(x, top);
  2384. if (left < right && top < bottom) {
  2385. ctx.arc(left, top, r, -PI, -HALF_PI);
  2386. ctx.arc(right, top, r, -HALF_PI, 0);
  2387. ctx.arc(right, bottom, r, 0, HALF_PI);
  2388. ctx.arc(left, bottom, r, HALF_PI, PI);
  2389. } else if (left < right) {
  2390. ctx.moveTo(left, y);
  2391. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2392. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2393. } else if (top < bottom) {
  2394. ctx.arc(left, top, r, -PI, 0);
  2395. ctx.arc(left, bottom, r, 0, PI);
  2396. } else {
  2397. ctx.arc(left, top, r, -PI, PI);
  2398. }
  2399. ctx.closePath();
  2400. ctx.moveTo(x, y);
  2401. } else {
  2402. ctx.rect(x, y, width, height);
  2403. }
  2404. },
  2405. drawPoint: function(ctx, style, radius, x, y, rotation) {
  2406. var type, xOffset, yOffset, size, cornerRadius;
  2407. var rad = (rotation || 0) * RAD_PER_DEG;
  2408. if (style && typeof style === 'object') {
  2409. type = style.toString();
  2410. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2411. ctx.save();
  2412. ctx.translate(x, y);
  2413. ctx.rotate(rad);
  2414. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  2415. ctx.restore();
  2416. return;
  2417. }
  2418. }
  2419. if (isNaN(radius) || radius <= 0) {
  2420. return;
  2421. }
  2422. ctx.beginPath();
  2423. switch (style) {
  2424. // Default includes circle
  2425. default:
  2426. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2427. ctx.closePath();
  2428. break;
  2429. case 'triangle':
  2430. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2431. rad += TWO_THIRDS_PI;
  2432. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2433. rad += TWO_THIRDS_PI;
  2434. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2435. ctx.closePath();
  2436. break;
  2437. case 'rectRounded':
  2438. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2439. // `quadraticCurveTo` since it generates better results when rect is
  2440. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2441. // closer proportion to the previous impl and it is inscribed in the
  2442. // circle with `radius`. For more details, see the following PRs:
  2443. // https://github.com/chartjs/Chart.js/issues/5597
  2444. // https://github.com/chartjs/Chart.js/issues/5858
  2445. cornerRadius = radius * 0.516;
  2446. size = radius - cornerRadius;
  2447. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2448. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2449. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2450. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2451. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2452. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2453. ctx.closePath();
  2454. break;
  2455. case 'rect':
  2456. if (!rotation) {
  2457. size = Math.SQRT1_2 * radius;
  2458. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2459. break;
  2460. }
  2461. rad += QUARTER_PI;
  2462. /* falls through */
  2463. case 'rectRot':
  2464. xOffset = Math.cos(rad) * radius;
  2465. yOffset = Math.sin(rad) * radius;
  2466. ctx.moveTo(x - xOffset, y - yOffset);
  2467. ctx.lineTo(x + yOffset, y - xOffset);
  2468. ctx.lineTo(x + xOffset, y + yOffset);
  2469. ctx.lineTo(x - yOffset, y + xOffset);
  2470. ctx.closePath();
  2471. break;
  2472. case 'crossRot':
  2473. rad += QUARTER_PI;
  2474. /* falls through */
  2475. case 'cross':
  2476. xOffset = Math.cos(rad) * radius;
  2477. yOffset = Math.sin(rad) * radius;
  2478. ctx.moveTo(x - xOffset, y - yOffset);
  2479. ctx.lineTo(x + xOffset, y + yOffset);
  2480. ctx.moveTo(x + yOffset, y - xOffset);
  2481. ctx.lineTo(x - yOffset, y + xOffset);
  2482. break;
  2483. case 'star':
  2484. xOffset = Math.cos(rad) * radius;
  2485. yOffset = Math.sin(rad) * radius;
  2486. ctx.moveTo(x - xOffset, y - yOffset);
  2487. ctx.lineTo(x + xOffset, y + yOffset);
  2488. ctx.moveTo(x + yOffset, y - xOffset);
  2489. ctx.lineTo(x - yOffset, y + xOffset);
  2490. rad += QUARTER_PI;
  2491. xOffset = Math.cos(rad) * radius;
  2492. yOffset = Math.sin(rad) * radius;
  2493. ctx.moveTo(x - xOffset, y - yOffset);
  2494. ctx.lineTo(x + xOffset, y + yOffset);
  2495. ctx.moveTo(x + yOffset, y - xOffset);
  2496. ctx.lineTo(x - yOffset, y + xOffset);
  2497. break;
  2498. case 'line':
  2499. xOffset = Math.cos(rad) * radius;
  2500. yOffset = Math.sin(rad) * radius;
  2501. ctx.moveTo(x - xOffset, y - yOffset);
  2502. ctx.lineTo(x + xOffset, y + yOffset);
  2503. break;
  2504. case 'dash':
  2505. ctx.moveTo(x, y);
  2506. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2507. break;
  2508. }
  2509. ctx.fill();
  2510. ctx.stroke();
  2511. },
  2512. /**
  2513. * Returns true if the point is inside the rectangle
  2514. * @param {object} point - The point to test
  2515. * @param {object} area - The rectangle
  2516. * @returns {boolean}
  2517. * @private
  2518. */
  2519. _isPointInArea: function(point, area) {
  2520. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2521. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2522. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2523. },
  2524. clipArea: function(ctx, area) {
  2525. ctx.save();
  2526. ctx.beginPath();
  2527. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2528. ctx.clip();
  2529. },
  2530. unclipArea: function(ctx) {
  2531. ctx.restore();
  2532. },
  2533. lineTo: function(ctx, previous, target, flip) {
  2534. var stepped = target.steppedLine;
  2535. if (stepped) {
  2536. if (stepped === 'middle') {
  2537. var midpoint = (previous.x + target.x) / 2.0;
  2538. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2539. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2540. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2541. ctx.lineTo(previous.x, target.y);
  2542. } else {
  2543. ctx.lineTo(target.x, previous.y);
  2544. }
  2545. ctx.lineTo(target.x, target.y);
  2546. return;
  2547. }
  2548. if (!target.tension) {
  2549. ctx.lineTo(target.x, target.y);
  2550. return;
  2551. }
  2552. ctx.bezierCurveTo(
  2553. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2554. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2555. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2556. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2557. target.x,
  2558. target.y);
  2559. }
  2560. };
  2561. var helpers_canvas = exports$1;
  2562. // DEPRECATIONS
  2563. /**
  2564. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2565. * @namespace Chart.helpers.clear
  2566. * @deprecated since version 2.7.0
  2567. * @todo remove at version 3
  2568. * @private
  2569. */
  2570. helpers_core.clear = exports$1.clear;
  2571. /**
  2572. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2573. * @namespace Chart.helpers.drawRoundedRectangle
  2574. * @deprecated since version 2.7.0
  2575. * @todo remove at version 3
  2576. * @private
  2577. */
  2578. helpers_core.drawRoundedRectangle = function(ctx) {
  2579. ctx.beginPath();
  2580. exports$1.roundedRect.apply(exports$1, arguments);
  2581. };
  2582. var defaults = {
  2583. /**
  2584. * @private
  2585. */
  2586. _set: function(scope, values) {
  2587. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2588. }
  2589. };
  2590. // TODO(v3): remove 'global' from namespace. all default are global and
  2591. // there's inconsistency around which options are under 'global'
  2592. defaults._set('global', {
  2593. defaultColor: 'rgba(0,0,0,0.1)',
  2594. defaultFontColor: '#666',
  2595. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2596. defaultFontSize: 12,
  2597. defaultFontStyle: 'normal',
  2598. defaultLineHeight: 1.2,
  2599. showLines: true
  2600. });
  2601. var core_defaults = defaults;
  2602. var valueOrDefault = helpers_core.valueOrDefault;
  2603. /**
  2604. * Converts the given font object into a CSS font string.
  2605. * @param {object} font - A font object.
  2606. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2607. * @private
  2608. */
  2609. function toFontString(font) {
  2610. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2611. return null;
  2612. }
  2613. return (font.style ? font.style + ' ' : '')
  2614. + (font.weight ? font.weight + ' ' : '')
  2615. + font.size + 'px '
  2616. + font.family;
  2617. }
  2618. /**
  2619. * @alias Chart.helpers.options
  2620. * @namespace
  2621. */
  2622. var helpers_options = {
  2623. /**
  2624. * Converts the given line height `value` in pixels for a specific font `size`.
  2625. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2626. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2627. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2628. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2629. * @since 2.7.0
  2630. */
  2631. toLineHeight: function(value, size) {
  2632. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2633. if (!matches || matches[1] === 'normal') {
  2634. return size * 1.2;
  2635. }
  2636. value = +matches[2];
  2637. switch (matches[3]) {
  2638. case 'px':
  2639. return value;
  2640. case '%':
  2641. value /= 100;
  2642. break;
  2643. }
  2644. return size * value;
  2645. },
  2646. /**
  2647. * Converts the given value into a padding object with pre-computed width/height.
  2648. * @param {number|object} value - If a number, set the value to all TRBL component,
  2649. * else, if and object, use defined properties and sets undefined ones to 0.
  2650. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2651. * @since 2.7.0
  2652. */
  2653. toPadding: function(value) {
  2654. var t, r, b, l;
  2655. if (helpers_core.isObject(value)) {
  2656. t = +value.top || 0;
  2657. r = +value.right || 0;
  2658. b = +value.bottom || 0;
  2659. l = +value.left || 0;
  2660. } else {
  2661. t = r = b = l = +value || 0;
  2662. }
  2663. return {
  2664. top: t,
  2665. right: r,
  2666. bottom: b,
  2667. left: l,
  2668. height: t + b,
  2669. width: l + r
  2670. };
  2671. },
  2672. /**
  2673. * Parses font options and returns the font object.
  2674. * @param {object} options - A object that contains font options to be parsed.
  2675. * @return {object} The font object.
  2676. * @todo Support font.* options and renamed to toFont().
  2677. * @private
  2678. */
  2679. _parseFont: function(options) {
  2680. var globalDefaults = core_defaults.global;
  2681. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2682. var font = {
  2683. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2684. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2685. size: size,
  2686. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2687. weight: null,
  2688. string: ''
  2689. };
  2690. font.string = toFontString(font);
  2691. return font;
  2692. },
  2693. /**
  2694. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2695. * @param {Array} inputs - An array of values, falling back to the last value.
  2696. * @param {object} [context] - If defined and the current value is a function, the value
  2697. * is called with `context` as first argument and the result becomes the new input.
  2698. * @param {number} [index] - If defined and the current value is an array, the value
  2699. * at `index` become the new input.
  2700. * @param {object} [info] - object to return information about resolution in
  2701. * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.
  2702. * @since 2.7.0
  2703. */
  2704. resolve: function(inputs, context, index, info) {
  2705. var cacheable = true;
  2706. var i, ilen, value;
  2707. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2708. value = inputs[i];
  2709. if (value === undefined) {
  2710. continue;
  2711. }
  2712. if (context !== undefined && typeof value === 'function') {
  2713. value = value(context);
  2714. cacheable = false;
  2715. }
  2716. if (index !== undefined && helpers_core.isArray(value)) {
  2717. value = value[index];
  2718. cacheable = false;
  2719. }
  2720. if (value !== undefined) {
  2721. if (info && !cacheable) {
  2722. info.cacheable = false;
  2723. }
  2724. return value;
  2725. }
  2726. }
  2727. }
  2728. };
  2729. /**
  2730. * @alias Chart.helpers.math
  2731. * @namespace
  2732. */
  2733. var exports$2 = {
  2734. /**
  2735. * Returns an array of factors sorted from 1 to sqrt(value)
  2736. * @private
  2737. */
  2738. _factorize: function(value) {
  2739. var result = [];
  2740. var sqrt = Math.sqrt(value);
  2741. var i;
  2742. for (i = 1; i < sqrt; i++) {
  2743. if (value % i === 0) {
  2744. result.push(i);
  2745. result.push(value / i);
  2746. }
  2747. }
  2748. if (sqrt === (sqrt | 0)) { // if value is a square number
  2749. result.push(sqrt);
  2750. }
  2751. result.sort(function(a, b) {
  2752. return a - b;
  2753. }).pop();
  2754. return result;
  2755. },
  2756. log10: Math.log10 || function(x) {
  2757. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  2758. // Check for whole powers of 10,
  2759. // which due to floating point rounding error should be corrected.
  2760. var powerOf10 = Math.round(exponent);
  2761. var isPowerOf10 = x === Math.pow(10, powerOf10);
  2762. return isPowerOf10 ? powerOf10 : exponent;
  2763. }
  2764. };
  2765. var helpers_math = exports$2;
  2766. // DEPRECATIONS
  2767. /**
  2768. * Provided for backward compatibility, use Chart.helpers.math.log10 instead.
  2769. * @namespace Chart.helpers.log10
  2770. * @deprecated since version 2.9.0
  2771. * @todo remove at version 3
  2772. * @private
  2773. */
  2774. helpers_core.log10 = exports$2.log10;
  2775. var getRtlAdapter = function(rectX, width) {
  2776. return {
  2777. x: function(x) {
  2778. return rectX + rectX + width - x;
  2779. },
  2780. setWidth: function(w) {
  2781. width = w;
  2782. },
  2783. textAlign: function(align) {
  2784. if (align === 'center') {
  2785. return align;
  2786. }
  2787. return align === 'right' ? 'left' : 'right';
  2788. },
  2789. xPlus: function(x, value) {
  2790. return x - value;
  2791. },
  2792. leftForLtr: function(x, itemWidth) {
  2793. return x - itemWidth;
  2794. },
  2795. };
  2796. };
  2797. var getLtrAdapter = function() {
  2798. return {
  2799. x: function(x) {
  2800. return x;
  2801. },
  2802. setWidth: function(w) { // eslint-disable-line no-unused-vars
  2803. },
  2804. textAlign: function(align) {
  2805. return align;
  2806. },
  2807. xPlus: function(x, value) {
  2808. return x + value;
  2809. },
  2810. leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars
  2811. return x;
  2812. },
  2813. };
  2814. };
  2815. var getAdapter = function(rtl, rectX, width) {
  2816. return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();
  2817. };
  2818. var overrideTextDirection = function(ctx, direction) {
  2819. var style, original;
  2820. if (direction === 'ltr' || direction === 'rtl') {
  2821. style = ctx.canvas.style;
  2822. original = [
  2823. style.getPropertyValue('direction'),
  2824. style.getPropertyPriority('direction'),
  2825. ];
  2826. style.setProperty('direction', direction, 'important');
  2827. ctx.prevTextDirection = original;
  2828. }
  2829. };
  2830. var restoreTextDirection = function(ctx) {
  2831. var original = ctx.prevTextDirection;
  2832. if (original !== undefined) {
  2833. delete ctx.prevTextDirection;
  2834. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  2835. }
  2836. };
  2837. var helpers_rtl = {
  2838. getRtlAdapter: getAdapter,
  2839. overrideTextDirection: overrideTextDirection,
  2840. restoreTextDirection: restoreTextDirection,
  2841. };
  2842. var helpers$1 = helpers_core;
  2843. var easing = helpers_easing;
  2844. var canvas = helpers_canvas;
  2845. var options = helpers_options;
  2846. var math = helpers_math;
  2847. var rtl = helpers_rtl;
  2848. helpers$1.easing = easing;
  2849. helpers$1.canvas = canvas;
  2850. helpers$1.options = options;
  2851. helpers$1.math = math;
  2852. helpers$1.rtl = rtl;
  2853. function interpolate(start, view, model, ease) {
  2854. var keys = Object.keys(model);
  2855. var i, ilen, key, actual, origin, target, type, c0, c1;
  2856. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2857. key = keys[i];
  2858. target = model[key];
  2859. // if a value is added to the model after pivot() has been called, the view
  2860. // doesn't contain it, so let's initialize the view to the target value.
  2861. if (!view.hasOwnProperty(key)) {
  2862. view[key] = target;
  2863. }
  2864. actual = view[key];
  2865. if (actual === target || key[0] === '_') {
  2866. continue;
  2867. }
  2868. if (!start.hasOwnProperty(key)) {
  2869. start[key] = actual;
  2870. }
  2871. origin = start[key];
  2872. type = typeof target;
  2873. if (type === typeof origin) {
  2874. if (type === 'string') {
  2875. c0 = chartjsColor(origin);
  2876. if (c0.valid) {
  2877. c1 = chartjsColor(target);
  2878. if (c1.valid) {
  2879. view[key] = c1.mix(c0, ease).rgbString();
  2880. continue;
  2881. }
  2882. }
  2883. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2884. view[key] = origin + (target - origin) * ease;
  2885. continue;
  2886. }
  2887. }
  2888. view[key] = target;
  2889. }
  2890. }
  2891. var Element = function(configuration) {
  2892. helpers$1.extend(this, configuration);
  2893. this.initialize.apply(this, arguments);
  2894. };
  2895. helpers$1.extend(Element.prototype, {
  2896. _type: undefined,
  2897. initialize: function() {
  2898. this.hidden = false;
  2899. },
  2900. pivot: function() {
  2901. var me = this;
  2902. if (!me._view) {
  2903. me._view = helpers$1.extend({}, me._model);
  2904. }
  2905. me._start = {};
  2906. return me;
  2907. },
  2908. transition: function(ease) {
  2909. var me = this;
  2910. var model = me._model;
  2911. var start = me._start;
  2912. var view = me._view;
  2913. // No animation -> No Transition
  2914. if (!model || ease === 1) {
  2915. me._view = helpers$1.extend({}, model);
  2916. me._start = null;
  2917. return me;
  2918. }
  2919. if (!view) {
  2920. view = me._view = {};
  2921. }
  2922. if (!start) {
  2923. start = me._start = {};
  2924. }
  2925. interpolate(start, view, model, ease);
  2926. return me;
  2927. },
  2928. tooltipPosition: function() {
  2929. return {
  2930. x: this._model.x,
  2931. y: this._model.y
  2932. };
  2933. },
  2934. hasValue: function() {
  2935. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2936. }
  2937. });
  2938. Element.extend = helpers$1.inherits;
  2939. var core_element = Element;
  2940. var exports$3 = core_element.extend({
  2941. chart: null, // the animation associated chart instance
  2942. currentStep: 0, // the current animation step
  2943. numSteps: 60, // default number of steps
  2944. easing: '', // the easing to use for this animation
  2945. render: null, // render function used by the animation service
  2946. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2947. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2948. });
  2949. var core_animation = exports$3;
  2950. // DEPRECATIONS
  2951. /**
  2952. * Provided for backward compatibility, use Chart.Animation instead
  2953. * @prop Chart.Animation#animationObject
  2954. * @deprecated since version 2.6.0
  2955. * @todo remove at version 3
  2956. */
  2957. Object.defineProperty(exports$3.prototype, 'animationObject', {
  2958. get: function() {
  2959. return this;
  2960. }
  2961. });
  2962. /**
  2963. * Provided for backward compatibility, use Chart.Animation#chart instead
  2964. * @prop Chart.Animation#chartInstance
  2965. * @deprecated since version 2.6.0
  2966. * @todo remove at version 3
  2967. */
  2968. Object.defineProperty(exports$3.prototype, 'chartInstance', {
  2969. get: function() {
  2970. return this.chart;
  2971. },
  2972. set: function(value) {
  2973. this.chart = value;
  2974. }
  2975. });
  2976. core_defaults._set('global', {
  2977. animation: {
  2978. duration: 1000,
  2979. easing: 'easeOutQuart',
  2980. onProgress: helpers$1.noop,
  2981. onComplete: helpers$1.noop
  2982. }
  2983. });
  2984. var core_animations = {
  2985. animations: [],
  2986. request: null,
  2987. /**
  2988. * @param {Chart} chart - The chart to animate.
  2989. * @param {Chart.Animation} animation - The animation that we will animate.
  2990. * @param {number} duration - The animation duration in ms.
  2991. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  2992. */
  2993. addAnimation: function(chart, animation, duration, lazy) {
  2994. var animations = this.animations;
  2995. var i, ilen;
  2996. animation.chart = chart;
  2997. animation.startTime = Date.now();
  2998. animation.duration = duration;
  2999. if (!lazy) {
  3000. chart.animating = true;
  3001. }
  3002. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  3003. if (animations[i].chart === chart) {
  3004. animations[i] = animation;
  3005. return;
  3006. }
  3007. }
  3008. animations.push(animation);
  3009. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  3010. if (animations.length === 1) {
  3011. this.requestAnimationFrame();
  3012. }
  3013. },
  3014. cancelAnimation: function(chart) {
  3015. var index = helpers$1.findIndex(this.animations, function(animation) {
  3016. return animation.chart === chart;
  3017. });
  3018. if (index !== -1) {
  3019. this.animations.splice(index, 1);
  3020. chart.animating = false;
  3021. }
  3022. },
  3023. requestAnimationFrame: function() {
  3024. var me = this;
  3025. if (me.request === null) {
  3026. // Skip animation frame requests until the active one is executed.
  3027. // This can happen when processing mouse events, e.g. 'mousemove'
  3028. // and 'mouseout' events will trigger multiple renders.
  3029. me.request = helpers$1.requestAnimFrame.call(window, function() {
  3030. me.request = null;
  3031. me.startDigest();
  3032. });
  3033. }
  3034. },
  3035. /**
  3036. * @private
  3037. */
  3038. startDigest: function() {
  3039. var me = this;
  3040. me.advance();
  3041. // Do we have more stuff to animate?
  3042. if (me.animations.length > 0) {
  3043. me.requestAnimationFrame();
  3044. }
  3045. },
  3046. /**
  3047. * @private
  3048. */
  3049. advance: function() {
  3050. var animations = this.animations;
  3051. var animation, chart, numSteps, nextStep;
  3052. var i = 0;
  3053. // 1 animation per chart, so we are looping charts here
  3054. while (i < animations.length) {
  3055. animation = animations[i];
  3056. chart = animation.chart;
  3057. numSteps = animation.numSteps;
  3058. // Make sure that currentStep starts at 1
  3059. // https://github.com/chartjs/Chart.js/issues/6104
  3060. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  3061. animation.currentStep = Math.min(nextStep, numSteps);
  3062. helpers$1.callback(animation.render, [chart, animation], chart);
  3063. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  3064. if (animation.currentStep >= numSteps) {
  3065. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  3066. chart.animating = false;
  3067. animations.splice(i, 1);
  3068. } else {
  3069. ++i;
  3070. }
  3071. }
  3072. }
  3073. };
  3074. var resolve = helpers$1.options.resolve;
  3075. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  3076. /**
  3077. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  3078. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  3079. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  3080. */
  3081. function listenArrayEvents(array, listener) {
  3082. if (array._chartjs) {
  3083. array._chartjs.listeners.push(listener);
  3084. return;
  3085. }
  3086. Object.defineProperty(array, '_chartjs', {
  3087. configurable: true,
  3088. enumerable: false,
  3089. value: {
  3090. listeners: [listener]
  3091. }
  3092. });
  3093. arrayEvents.forEach(function(key) {
  3094. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  3095. var base = array[key];
  3096. Object.defineProperty(array, key, {
  3097. configurable: true,
  3098. enumerable: false,
  3099. value: function() {
  3100. var args = Array.prototype.slice.call(arguments);
  3101. var res = base.apply(this, args);
  3102. helpers$1.each(array._chartjs.listeners, function(object) {
  3103. if (typeof object[method] === 'function') {
  3104. object[method].apply(object, args);
  3105. }
  3106. });
  3107. return res;
  3108. }
  3109. });
  3110. });
  3111. }
  3112. /**
  3113. * Removes the given array event listener and cleanup extra attached properties (such as
  3114. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  3115. */
  3116. function unlistenArrayEvents(array, listener) {
  3117. var stub = array._chartjs;
  3118. if (!stub) {
  3119. return;
  3120. }
  3121. var listeners = stub.listeners;
  3122. var index = listeners.indexOf(listener);
  3123. if (index !== -1) {
  3124. listeners.splice(index, 1);
  3125. }
  3126. if (listeners.length > 0) {
  3127. return;
  3128. }
  3129. arrayEvents.forEach(function(key) {
  3130. delete array[key];
  3131. });
  3132. delete array._chartjs;
  3133. }
  3134. // Base class for all dataset controllers (line, bar, etc)
  3135. var DatasetController = function(chart, datasetIndex) {
  3136. this.initialize(chart, datasetIndex);
  3137. };
  3138. helpers$1.extend(DatasetController.prototype, {
  3139. /**
  3140. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  3141. * @type {Chart.core.element}
  3142. */
  3143. datasetElementType: null,
  3144. /**
  3145. * Element type used to generate a meta data (e.g. Chart.element.Point).
  3146. * @type {Chart.core.element}
  3147. */
  3148. dataElementType: null,
  3149. /**
  3150. * Dataset element option keys to be resolved in _resolveDatasetElementOptions.
  3151. * A derived controller may override this to resolve controller-specific options.
  3152. * The keys defined here are for backward compatibility for legend styles.
  3153. * @private
  3154. */
  3155. _datasetElementOptions: [
  3156. 'backgroundColor',
  3157. 'borderCapStyle',
  3158. 'borderColor',
  3159. 'borderDash',
  3160. 'borderDashOffset',
  3161. 'borderJoinStyle',
  3162. 'borderWidth'
  3163. ],
  3164. /**
  3165. * Data element option keys to be resolved in _resolveDataElementOptions.
  3166. * A derived controller may override this to resolve controller-specific options.
  3167. * The keys defined here are for backward compatibility for legend styles.
  3168. * @private
  3169. */
  3170. _dataElementOptions: [
  3171. 'backgroundColor',
  3172. 'borderColor',
  3173. 'borderWidth',
  3174. 'pointStyle'
  3175. ],
  3176. initialize: function(chart, datasetIndex) {
  3177. var me = this;
  3178. me.chart = chart;
  3179. me.index = datasetIndex;
  3180. me.linkScales();
  3181. me.addElements();
  3182. me._type = me.getMeta().type;
  3183. },
  3184. updateIndex: function(datasetIndex) {
  3185. this.index = datasetIndex;
  3186. },
  3187. linkScales: function() {
  3188. var me = this;
  3189. var meta = me.getMeta();
  3190. var chart = me.chart;
  3191. var scales = chart.scales;
  3192. var dataset = me.getDataset();
  3193. var scalesOpts = chart.options.scales;
  3194. if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
  3195. meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
  3196. }
  3197. if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
  3198. meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
  3199. }
  3200. },
  3201. getDataset: function() {
  3202. return this.chart.data.datasets[this.index];
  3203. },
  3204. getMeta: function() {
  3205. return this.chart.getDatasetMeta(this.index);
  3206. },
  3207. getScaleForId: function(scaleID) {
  3208. return this.chart.scales[scaleID];
  3209. },
  3210. /**
  3211. * @private
  3212. */
  3213. _getValueScaleId: function() {
  3214. return this.getMeta().yAxisID;
  3215. },
  3216. /**
  3217. * @private
  3218. */
  3219. _getIndexScaleId: function() {
  3220. return this.getMeta().xAxisID;
  3221. },
  3222. /**
  3223. * @private
  3224. */
  3225. _getValueScale: function() {
  3226. return this.getScaleForId(this._getValueScaleId());
  3227. },
  3228. /**
  3229. * @private
  3230. */
  3231. _getIndexScale: function() {
  3232. return this.getScaleForId(this._getIndexScaleId());
  3233. },
  3234. reset: function() {
  3235. this._update(true);
  3236. },
  3237. /**
  3238. * @private
  3239. */
  3240. destroy: function() {
  3241. if (this._data) {
  3242. unlistenArrayEvents(this._data, this);
  3243. }
  3244. },
  3245. createMetaDataset: function() {
  3246. var me = this;
  3247. var type = me.datasetElementType;
  3248. return type && new type({
  3249. _chart: me.chart,
  3250. _datasetIndex: me.index
  3251. });
  3252. },
  3253. createMetaData: function(index) {
  3254. var me = this;
  3255. var type = me.dataElementType;
  3256. return type && new type({
  3257. _chart: me.chart,
  3258. _datasetIndex: me.index,
  3259. _index: index
  3260. });
  3261. },
  3262. addElements: function() {
  3263. var me = this;
  3264. var meta = me.getMeta();
  3265. var data = me.getDataset().data || [];
  3266. var metaData = meta.data;
  3267. var i, ilen;
  3268. for (i = 0, ilen = data.length; i < ilen; ++i) {
  3269. metaData[i] = metaData[i] || me.createMetaData(i);
  3270. }
  3271. meta.dataset = meta.dataset || me.createMetaDataset();
  3272. },
  3273. addElementAndReset: function(index) {
  3274. var element = this.createMetaData(index);
  3275. this.getMeta().data.splice(index, 0, element);
  3276. this.updateElement(element, index, true);
  3277. },
  3278. buildOrUpdateElements: function() {
  3279. var me = this;
  3280. var dataset = me.getDataset();
  3281. var data = dataset.data || (dataset.data = []);
  3282. // In order to correctly handle data addition/deletion animation (an thus simulate
  3283. // real-time charts), we need to monitor these data modifications and synchronize
  3284. // the internal meta data accordingly.
  3285. if (me._data !== data) {
  3286. if (me._data) {
  3287. // This case happens when the user replaced the data array instance.
  3288. unlistenArrayEvents(me._data, me);
  3289. }
  3290. if (data && Object.isExtensible(data)) {
  3291. listenArrayEvents(data, me);
  3292. }
  3293. me._data = data;
  3294. }
  3295. // Re-sync meta data in case the user replaced the data array or if we missed
  3296. // any updates and so make sure that we handle number of datapoints changing.
  3297. me.resyncElements();
  3298. },
  3299. /**
  3300. * Returns the merged user-supplied and default dataset-level options
  3301. * @private
  3302. */
  3303. _configure: function() {
  3304. var me = this;
  3305. me._config = helpers$1.merge(Object.create(null), [
  3306. me.chart.options.datasets[me._type],
  3307. me.getDataset(),
  3308. ], {
  3309. merger: function(key, target, source) {
  3310. if (key !== '_meta' && key !== 'data') {
  3311. helpers$1._merger(key, target, source);
  3312. }
  3313. }
  3314. });
  3315. },
  3316. _update: function(reset) {
  3317. var me = this;
  3318. me._configure();
  3319. me._cachedDataOpts = null;
  3320. me.update(reset);
  3321. },
  3322. update: helpers$1.noop,
  3323. transition: function(easingValue) {
  3324. var meta = this.getMeta();
  3325. var elements = meta.data || [];
  3326. var ilen = elements.length;
  3327. var i = 0;
  3328. for (; i < ilen; ++i) {
  3329. elements[i].transition(easingValue);
  3330. }
  3331. if (meta.dataset) {
  3332. meta.dataset.transition(easingValue);
  3333. }
  3334. },
  3335. draw: function() {
  3336. var meta = this.getMeta();
  3337. var elements = meta.data || [];
  3338. var ilen = elements.length;
  3339. var i = 0;
  3340. if (meta.dataset) {
  3341. meta.dataset.draw();
  3342. }
  3343. for (; i < ilen; ++i) {
  3344. elements[i].draw();
  3345. }
  3346. },
  3347. /**
  3348. * Returns a set of predefined style properties that should be used to represent the dataset
  3349. * or the data if the index is specified
  3350. * @param {number} index - data index
  3351. * @return {IStyleInterface} style object
  3352. */
  3353. getStyle: function(index) {
  3354. var me = this;
  3355. var meta = me.getMeta();
  3356. var dataset = meta.dataset;
  3357. var style;
  3358. me._configure();
  3359. if (dataset && index === undefined) {
  3360. style = me._resolveDatasetElementOptions(dataset || {});
  3361. } else {
  3362. index = index || 0;
  3363. style = me._resolveDataElementOptions(meta.data[index] || {}, index);
  3364. }
  3365. if (style.fill === false || style.fill === null) {
  3366. style.backgroundColor = style.borderColor;
  3367. }
  3368. return style;
  3369. },
  3370. /**
  3371. * @private
  3372. */
  3373. _resolveDatasetElementOptions: function(element, hover) {
  3374. var me = this;
  3375. var chart = me.chart;
  3376. var datasetOpts = me._config;
  3377. var custom = element.custom || {};
  3378. var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
  3379. var elementOptions = me._datasetElementOptions;
  3380. var values = {};
  3381. var i, ilen, key, readKey;
  3382. // Scriptable options
  3383. var context = {
  3384. chart: chart,
  3385. dataset: me.getDataset(),
  3386. datasetIndex: me.index,
  3387. hover: hover
  3388. };
  3389. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3390. key = elementOptions[i];
  3391. readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
  3392. values[key] = resolve([
  3393. custom[readKey],
  3394. datasetOpts[readKey],
  3395. options[readKey]
  3396. ], context);
  3397. }
  3398. return values;
  3399. },
  3400. /**
  3401. * @private
  3402. */
  3403. _resolveDataElementOptions: function(element, index) {
  3404. var me = this;
  3405. var custom = element && element.custom;
  3406. var cached = me._cachedDataOpts;
  3407. if (cached && !custom) {
  3408. return cached;
  3409. }
  3410. var chart = me.chart;
  3411. var datasetOpts = me._config;
  3412. var options = chart.options.elements[me.dataElementType.prototype._type] || {};
  3413. var elementOptions = me._dataElementOptions;
  3414. var values = {};
  3415. // Scriptable options
  3416. var context = {
  3417. chart: chart,
  3418. dataIndex: index,
  3419. dataset: me.getDataset(),
  3420. datasetIndex: me.index
  3421. };
  3422. // `resolve` sets cacheable to `false` if any option is indexed or scripted
  3423. var info = {cacheable: !custom};
  3424. var keys, i, ilen, key;
  3425. custom = custom || {};
  3426. if (helpers$1.isArray(elementOptions)) {
  3427. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3428. key = elementOptions[i];
  3429. values[key] = resolve([
  3430. custom[key],
  3431. datasetOpts[key],
  3432. options[key]
  3433. ], context, index, info);
  3434. }
  3435. } else {
  3436. keys = Object.keys(elementOptions);
  3437. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3438. key = keys[i];
  3439. values[key] = resolve([
  3440. custom[key],
  3441. datasetOpts[elementOptions[key]],
  3442. datasetOpts[key],
  3443. options[key]
  3444. ], context, index, info);
  3445. }
  3446. }
  3447. if (info.cacheable) {
  3448. me._cachedDataOpts = Object.freeze(values);
  3449. }
  3450. return values;
  3451. },
  3452. removeHoverStyle: function(element) {
  3453. helpers$1.merge(element._model, element.$previousStyle || {});
  3454. delete element.$previousStyle;
  3455. },
  3456. setHoverStyle: function(element) {
  3457. var dataset = this.chart.data.datasets[element._datasetIndex];
  3458. var index = element._index;
  3459. var custom = element.custom || {};
  3460. var model = element._model;
  3461. var getHoverColor = helpers$1.getHoverColor;
  3462. element.$previousStyle = {
  3463. backgroundColor: model.backgroundColor,
  3464. borderColor: model.borderColor,
  3465. borderWidth: model.borderWidth
  3466. };
  3467. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  3468. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  3469. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  3470. },
  3471. /**
  3472. * @private
  3473. */
  3474. _removeDatasetHoverStyle: function() {
  3475. var element = this.getMeta().dataset;
  3476. if (element) {
  3477. this.removeHoverStyle(element);
  3478. }
  3479. },
  3480. /**
  3481. * @private
  3482. */
  3483. _setDatasetHoverStyle: function() {
  3484. var element = this.getMeta().dataset;
  3485. var prev = {};
  3486. var i, ilen, key, keys, hoverOptions, model;
  3487. if (!element) {
  3488. return;
  3489. }
  3490. model = element._model;
  3491. hoverOptions = this._resolveDatasetElementOptions(element, true);
  3492. keys = Object.keys(hoverOptions);
  3493. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3494. key = keys[i];
  3495. prev[key] = model[key];
  3496. model[key] = hoverOptions[key];
  3497. }
  3498. element.$previousStyle = prev;
  3499. },
  3500. /**
  3501. * @private
  3502. */
  3503. resyncElements: function() {
  3504. var me = this;
  3505. var meta = me.getMeta();
  3506. var data = me.getDataset().data;
  3507. var numMeta = meta.data.length;
  3508. var numData = data.length;
  3509. if (numData < numMeta) {
  3510. meta.data.splice(numData, numMeta - numData);
  3511. } else if (numData > numMeta) {
  3512. me.insertElements(numMeta, numData - numMeta);
  3513. }
  3514. },
  3515. /**
  3516. * @private
  3517. */
  3518. insertElements: function(start, count) {
  3519. for (var i = 0; i < count; ++i) {
  3520. this.addElementAndReset(start + i);
  3521. }
  3522. },
  3523. /**
  3524. * @private
  3525. */
  3526. onDataPush: function() {
  3527. var count = arguments.length;
  3528. this.insertElements(this.getDataset().data.length - count, count);
  3529. },
  3530. /**
  3531. * @private
  3532. */
  3533. onDataPop: function() {
  3534. this.getMeta().data.pop();
  3535. },
  3536. /**
  3537. * @private
  3538. */
  3539. onDataShift: function() {
  3540. this.getMeta().data.shift();
  3541. },
  3542. /**
  3543. * @private
  3544. */
  3545. onDataSplice: function(start, count) {
  3546. this.getMeta().data.splice(start, count);
  3547. this.insertElements(start, arguments.length - 2);
  3548. },
  3549. /**
  3550. * @private
  3551. */
  3552. onDataUnshift: function() {
  3553. this.insertElements(0, arguments.length);
  3554. }
  3555. });
  3556. DatasetController.extend = helpers$1.inherits;
  3557. var core_datasetController = DatasetController;
  3558. var TAU = Math.PI * 2;
  3559. core_defaults._set('global', {
  3560. elements: {
  3561. arc: {
  3562. backgroundColor: core_defaults.global.defaultColor,
  3563. borderColor: '#fff',
  3564. borderWidth: 2,
  3565. borderAlign: 'center'
  3566. }
  3567. }
  3568. });
  3569. function clipArc(ctx, arc) {
  3570. var startAngle = arc.startAngle;
  3571. var endAngle = arc.endAngle;
  3572. var pixelMargin = arc.pixelMargin;
  3573. var angleMargin = pixelMargin / arc.outerRadius;
  3574. var x = arc.x;
  3575. var y = arc.y;
  3576. // Draw an inner border by cliping the arc and drawing a double-width border
  3577. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  3578. ctx.beginPath();
  3579. ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  3580. if (arc.innerRadius > pixelMargin) {
  3581. angleMargin = pixelMargin / arc.innerRadius;
  3582. ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);
  3583. } else {
  3584. ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);
  3585. }
  3586. ctx.closePath();
  3587. ctx.clip();
  3588. }
  3589. function drawFullCircleBorders(ctx, vm, arc, inner) {
  3590. var endAngle = arc.endAngle;
  3591. var i;
  3592. if (inner) {
  3593. arc.endAngle = arc.startAngle + TAU;
  3594. clipArc(ctx, arc);
  3595. arc.endAngle = endAngle;
  3596. if (arc.endAngle === arc.startAngle && arc.fullCircles) {
  3597. arc.endAngle += TAU;
  3598. arc.fullCircles--;
  3599. }
  3600. }
  3601. ctx.beginPath();
  3602. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);
  3603. for (i = 0; i < arc.fullCircles; ++i) {
  3604. ctx.stroke();
  3605. }
  3606. ctx.beginPath();
  3607. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);
  3608. for (i = 0; i < arc.fullCircles; ++i) {
  3609. ctx.stroke();
  3610. }
  3611. }
  3612. function drawBorder(ctx, vm, arc) {
  3613. var inner = vm.borderAlign === 'inner';
  3614. if (inner) {
  3615. ctx.lineWidth = vm.borderWidth * 2;
  3616. ctx.lineJoin = 'round';
  3617. } else {
  3618. ctx.lineWidth = vm.borderWidth;
  3619. ctx.lineJoin = 'bevel';
  3620. }
  3621. if (arc.fullCircles) {
  3622. drawFullCircleBorders(ctx, vm, arc, inner);
  3623. }
  3624. if (inner) {
  3625. clipArc(ctx, arc);
  3626. }
  3627. ctx.beginPath();
  3628. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);
  3629. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3630. ctx.closePath();
  3631. ctx.stroke();
  3632. }
  3633. var element_arc = core_element.extend({
  3634. _type: 'arc',
  3635. inLabelRange: function(mouseX) {
  3636. var vm = this._view;
  3637. if (vm) {
  3638. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  3639. }
  3640. return false;
  3641. },
  3642. inRange: function(chartX, chartY) {
  3643. var vm = this._view;
  3644. if (vm) {
  3645. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  3646. var angle = pointRelativePosition.angle;
  3647. var distance = pointRelativePosition.distance;
  3648. // Sanitise angle range
  3649. var startAngle = vm.startAngle;
  3650. var endAngle = vm.endAngle;
  3651. while (endAngle < startAngle) {
  3652. endAngle += TAU;
  3653. }
  3654. while (angle > endAngle) {
  3655. angle -= TAU;
  3656. }
  3657. while (angle < startAngle) {
  3658. angle += TAU;
  3659. }
  3660. // Check if within the range of the open/close angle
  3661. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  3662. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  3663. return (betweenAngles && withinRadius);
  3664. }
  3665. return false;
  3666. },
  3667. getCenterPoint: function() {
  3668. var vm = this._view;
  3669. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  3670. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  3671. return {
  3672. x: vm.x + Math.cos(halfAngle) * halfRadius,
  3673. y: vm.y + Math.sin(halfAngle) * halfRadius
  3674. };
  3675. },
  3676. getArea: function() {
  3677. var vm = this._view;
  3678. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  3679. },
  3680. tooltipPosition: function() {
  3681. var vm = this._view;
  3682. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  3683. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  3684. return {
  3685. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  3686. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  3687. };
  3688. },
  3689. draw: function() {
  3690. var ctx = this._chart.ctx;
  3691. var vm = this._view;
  3692. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  3693. var arc = {
  3694. x: vm.x,
  3695. y: vm.y,
  3696. innerRadius: vm.innerRadius,
  3697. outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),
  3698. pixelMargin: pixelMargin,
  3699. startAngle: vm.startAngle,
  3700. endAngle: vm.endAngle,
  3701. fullCircles: Math.floor(vm.circumference / TAU)
  3702. };
  3703. var i;
  3704. ctx.save();
  3705. ctx.fillStyle = vm.backgroundColor;
  3706. ctx.strokeStyle = vm.borderColor;
  3707. if (arc.fullCircles) {
  3708. arc.endAngle = arc.startAngle + TAU;
  3709. ctx.beginPath();
  3710. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3711. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3712. ctx.closePath();
  3713. for (i = 0; i < arc.fullCircles; ++i) {
  3714. ctx.fill();
  3715. }
  3716. arc.endAngle = arc.startAngle + vm.circumference % TAU;
  3717. }
  3718. ctx.beginPath();
  3719. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3720. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3721. ctx.closePath();
  3722. ctx.fill();
  3723. if (vm.borderWidth) {
  3724. drawBorder(ctx, vm, arc);
  3725. }
  3726. ctx.restore();
  3727. }
  3728. });
  3729. var valueOrDefault$1 = helpers$1.valueOrDefault;
  3730. var defaultColor = core_defaults.global.defaultColor;
  3731. core_defaults._set('global', {
  3732. elements: {
  3733. line: {
  3734. tension: 0.4,
  3735. backgroundColor: defaultColor,
  3736. borderWidth: 3,
  3737. borderColor: defaultColor,
  3738. borderCapStyle: 'butt',
  3739. borderDash: [],
  3740. borderDashOffset: 0.0,
  3741. borderJoinStyle: 'miter',
  3742. capBezierPoints: true,
  3743. fill: true, // do we fill in the area between the line and its base axis
  3744. }
  3745. }
  3746. });
  3747. var element_line = core_element.extend({
  3748. _type: 'line',
  3749. draw: function() {
  3750. var me = this;
  3751. var vm = me._view;
  3752. var ctx = me._chart.ctx;
  3753. var spanGaps = vm.spanGaps;
  3754. var points = me._children.slice(); // clone array
  3755. var globalDefaults = core_defaults.global;
  3756. var globalOptionLineElements = globalDefaults.elements.line;
  3757. var lastDrawnIndex = -1;
  3758. var closePath = me._loop;
  3759. var index, previous, currentVM;
  3760. if (!points.length) {
  3761. return;
  3762. }
  3763. if (me._loop) {
  3764. for (index = 0; index < points.length; ++index) {
  3765. previous = helpers$1.previousItem(points, index);
  3766. // If the line has an open path, shift the point array
  3767. if (!points[index]._view.skip && previous._view.skip) {
  3768. points = points.slice(index).concat(points.slice(0, index));
  3769. closePath = spanGaps;
  3770. break;
  3771. }
  3772. }
  3773. // If the line has a close path, add the first point again
  3774. if (closePath) {
  3775. points.push(points[0]);
  3776. }
  3777. }
  3778. ctx.save();
  3779. // Stroke Line Options
  3780. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3781. // IE 9 and 10 do not support line dash
  3782. if (ctx.setLineDash) {
  3783. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3784. }
  3785. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3786. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3787. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3788. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3789. // Stroke Line
  3790. ctx.beginPath();
  3791. // First point moves to it's starting position no matter what
  3792. currentVM = points[0]._view;
  3793. if (!currentVM.skip) {
  3794. ctx.moveTo(currentVM.x, currentVM.y);
  3795. lastDrawnIndex = 0;
  3796. }
  3797. for (index = 1; index < points.length; ++index) {
  3798. currentVM = points[index]._view;
  3799. previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];
  3800. if (!currentVM.skip) {
  3801. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3802. // There was a gap and this is the first point after the gap
  3803. ctx.moveTo(currentVM.x, currentVM.y);
  3804. } else {
  3805. // Line to next point
  3806. helpers$1.canvas.lineTo(ctx, previous._view, currentVM);
  3807. }
  3808. lastDrawnIndex = index;
  3809. }
  3810. }
  3811. if (closePath) {
  3812. ctx.closePath();
  3813. }
  3814. ctx.stroke();
  3815. ctx.restore();
  3816. }
  3817. });
  3818. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3819. var defaultColor$1 = core_defaults.global.defaultColor;
  3820. core_defaults._set('global', {
  3821. elements: {
  3822. point: {
  3823. radius: 3,
  3824. pointStyle: 'circle',
  3825. backgroundColor: defaultColor$1,
  3826. borderColor: defaultColor$1,
  3827. borderWidth: 1,
  3828. // Hover
  3829. hitRadius: 1,
  3830. hoverRadius: 4,
  3831. hoverBorderWidth: 1
  3832. }
  3833. }
  3834. });
  3835. function xRange(mouseX) {
  3836. var vm = this._view;
  3837. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3838. }
  3839. function yRange(mouseY) {
  3840. var vm = this._view;
  3841. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3842. }
  3843. var element_point = core_element.extend({
  3844. _type: 'point',
  3845. inRange: function(mouseX, mouseY) {
  3846. var vm = this._view;
  3847. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3848. },
  3849. inLabelRange: xRange,
  3850. inXRange: xRange,
  3851. inYRange: yRange,
  3852. getCenterPoint: function() {
  3853. var vm = this._view;
  3854. return {
  3855. x: vm.x,
  3856. y: vm.y
  3857. };
  3858. },
  3859. getArea: function() {
  3860. return Math.PI * Math.pow(this._view.radius, 2);
  3861. },
  3862. tooltipPosition: function() {
  3863. var vm = this._view;
  3864. return {
  3865. x: vm.x,
  3866. y: vm.y,
  3867. padding: vm.radius + vm.borderWidth
  3868. };
  3869. },
  3870. draw: function(chartArea) {
  3871. var vm = this._view;
  3872. var ctx = this._chart.ctx;
  3873. var pointStyle = vm.pointStyle;
  3874. var rotation = vm.rotation;
  3875. var radius = vm.radius;
  3876. var x = vm.x;
  3877. var y = vm.y;
  3878. var globalDefaults = core_defaults.global;
  3879. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3880. if (vm.skip) {
  3881. return;
  3882. }
  3883. // Clipping for Points.
  3884. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3885. ctx.strokeStyle = vm.borderColor || defaultColor;
  3886. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3887. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3888. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3889. }
  3890. }
  3891. });
  3892. var defaultColor$2 = core_defaults.global.defaultColor;
  3893. core_defaults._set('global', {
  3894. elements: {
  3895. rectangle: {
  3896. backgroundColor: defaultColor$2,
  3897. borderColor: defaultColor$2,
  3898. borderSkipped: 'bottom',
  3899. borderWidth: 0
  3900. }
  3901. }
  3902. });
  3903. function isVertical(vm) {
  3904. return vm && vm.width !== undefined;
  3905. }
  3906. /**
  3907. * Helper function to get the bounds of the bar regardless of the orientation
  3908. * @param bar {Chart.Element.Rectangle} the bar
  3909. * @return {Bounds} bounds of the bar
  3910. * @private
  3911. */
  3912. function getBarBounds(vm) {
  3913. var x1, x2, y1, y2, half;
  3914. if (isVertical(vm)) {
  3915. half = vm.width / 2;
  3916. x1 = vm.x - half;
  3917. x2 = vm.x + half;
  3918. y1 = Math.min(vm.y, vm.base);
  3919. y2 = Math.max(vm.y, vm.base);
  3920. } else {
  3921. half = vm.height / 2;
  3922. x1 = Math.min(vm.x, vm.base);
  3923. x2 = Math.max(vm.x, vm.base);
  3924. y1 = vm.y - half;
  3925. y2 = vm.y + half;
  3926. }
  3927. return {
  3928. left: x1,
  3929. top: y1,
  3930. right: x2,
  3931. bottom: y2
  3932. };
  3933. }
  3934. function swap(orig, v1, v2) {
  3935. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3936. }
  3937. function parseBorderSkipped(vm) {
  3938. var edge = vm.borderSkipped;
  3939. var res = {};
  3940. if (!edge) {
  3941. return res;
  3942. }
  3943. if (vm.horizontal) {
  3944. if (vm.base > vm.x) {
  3945. edge = swap(edge, 'left', 'right');
  3946. }
  3947. } else if (vm.base < vm.y) {
  3948. edge = swap(edge, 'bottom', 'top');
  3949. }
  3950. res[edge] = true;
  3951. return res;
  3952. }
  3953. function parseBorderWidth(vm, maxW, maxH) {
  3954. var value = vm.borderWidth;
  3955. var skip = parseBorderSkipped(vm);
  3956. var t, r, b, l;
  3957. if (helpers$1.isObject(value)) {
  3958. t = +value.top || 0;
  3959. r = +value.right || 0;
  3960. b = +value.bottom || 0;
  3961. l = +value.left || 0;
  3962. } else {
  3963. t = r = b = l = +value || 0;
  3964. }
  3965. return {
  3966. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  3967. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  3968. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  3969. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  3970. };
  3971. }
  3972. function boundingRects(vm) {
  3973. var bounds = getBarBounds(vm);
  3974. var width = bounds.right - bounds.left;
  3975. var height = bounds.bottom - bounds.top;
  3976. var border = parseBorderWidth(vm, width / 2, height / 2);
  3977. return {
  3978. outer: {
  3979. x: bounds.left,
  3980. y: bounds.top,
  3981. w: width,
  3982. h: height
  3983. },
  3984. inner: {
  3985. x: bounds.left + border.l,
  3986. y: bounds.top + border.t,
  3987. w: width - border.l - border.r,
  3988. h: height - border.t - border.b
  3989. }
  3990. };
  3991. }
  3992. function inRange(vm, x, y) {
  3993. var skipX = x === null;
  3994. var skipY = y === null;
  3995. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  3996. return bounds
  3997. && (skipX || x >= bounds.left && x <= bounds.right)
  3998. && (skipY || y >= bounds.top && y <= bounds.bottom);
  3999. }
  4000. var element_rectangle = core_element.extend({
  4001. _type: 'rectangle',
  4002. draw: function() {
  4003. var ctx = this._chart.ctx;
  4004. var vm = this._view;
  4005. var rects = boundingRects(vm);
  4006. var outer = rects.outer;
  4007. var inner = rects.inner;
  4008. ctx.fillStyle = vm.backgroundColor;
  4009. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  4010. if (outer.w === inner.w && outer.h === inner.h) {
  4011. return;
  4012. }
  4013. ctx.save();
  4014. ctx.beginPath();
  4015. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  4016. ctx.clip();
  4017. ctx.fillStyle = vm.borderColor;
  4018. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  4019. ctx.fill('evenodd');
  4020. ctx.restore();
  4021. },
  4022. height: function() {
  4023. var vm = this._view;
  4024. return vm.base - vm.y;
  4025. },
  4026. inRange: function(mouseX, mouseY) {
  4027. return inRange(this._view, mouseX, mouseY);
  4028. },
  4029. inLabelRange: function(mouseX, mouseY) {
  4030. var vm = this._view;
  4031. return isVertical(vm)
  4032. ? inRange(vm, mouseX, null)
  4033. : inRange(vm, null, mouseY);
  4034. },
  4035. inXRange: function(mouseX) {
  4036. return inRange(this._view, mouseX, null);
  4037. },
  4038. inYRange: function(mouseY) {
  4039. return inRange(this._view, null, mouseY);
  4040. },
  4041. getCenterPoint: function() {
  4042. var vm = this._view;
  4043. var x, y;
  4044. if (isVertical(vm)) {
  4045. x = vm.x;
  4046. y = (vm.y + vm.base) / 2;
  4047. } else {
  4048. x = (vm.x + vm.base) / 2;
  4049. y = vm.y;
  4050. }
  4051. return {x: x, y: y};
  4052. },
  4053. getArea: function() {
  4054. var vm = this._view;
  4055. return isVertical(vm)
  4056. ? vm.width * Math.abs(vm.y - vm.base)
  4057. : vm.height * Math.abs(vm.x - vm.base);
  4058. },
  4059. tooltipPosition: function() {
  4060. var vm = this._view;
  4061. return {
  4062. x: vm.x,
  4063. y: vm.y
  4064. };
  4065. }
  4066. });
  4067. var elements = {};
  4068. var Arc = element_arc;
  4069. var Line = element_line;
  4070. var Point = element_point;
  4071. var Rectangle = element_rectangle;
  4072. elements.Arc = Arc;
  4073. elements.Line = Line;
  4074. elements.Point = Point;
  4075. elements.Rectangle = Rectangle;
  4076. var deprecated = helpers$1._deprecated;
  4077. var valueOrDefault$3 = helpers$1.valueOrDefault;
  4078. core_defaults._set('bar', {
  4079. hover: {
  4080. mode: 'label'
  4081. },
  4082. scales: {
  4083. xAxes: [{
  4084. type: 'category',
  4085. offset: true,
  4086. gridLines: {
  4087. offsetGridLines: true
  4088. }
  4089. }],
  4090. yAxes: [{
  4091. type: 'linear'
  4092. }]
  4093. }
  4094. });
  4095. core_defaults._set('global', {
  4096. datasets: {
  4097. bar: {
  4098. categoryPercentage: 0.8,
  4099. barPercentage: 0.9
  4100. }
  4101. }
  4102. });
  4103. /**
  4104. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  4105. * @private
  4106. */
  4107. function computeMinSampleSize(scale, pixels) {
  4108. var min = scale._length;
  4109. var prev, curr, i, ilen;
  4110. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  4111. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  4112. }
  4113. for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
  4114. curr = scale.getPixelForTick(i);
  4115. min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
  4116. prev = curr;
  4117. }
  4118. return min;
  4119. }
  4120. /**
  4121. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  4122. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  4123. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  4124. * @private
  4125. */
  4126. function computeFitCategoryTraits(index, ruler, options) {
  4127. var thickness = options.barThickness;
  4128. var count = ruler.stackCount;
  4129. var curr = ruler.pixels[index];
  4130. var min = helpers$1.isNullOrUndef(thickness)
  4131. ? computeMinSampleSize(ruler.scale, ruler.pixels)
  4132. : -1;
  4133. var size, ratio;
  4134. if (helpers$1.isNullOrUndef(thickness)) {
  4135. size = min * options.categoryPercentage;
  4136. ratio = options.barPercentage;
  4137. } else {
  4138. // When bar thickness is enforced, category and bar percentages are ignored.
  4139. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  4140. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  4141. size = thickness * count;
  4142. ratio = 1;
  4143. }
  4144. return {
  4145. chunk: size / count,
  4146. ratio: ratio,
  4147. start: curr - (size / 2)
  4148. };
  4149. }
  4150. /**
  4151. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  4152. * percentage options are 1), based on the previous and following categories. This mode
  4153. * generates bars with different widths when data are not evenly spaced.
  4154. * @private
  4155. */
  4156. function computeFlexCategoryTraits(index, ruler, options) {
  4157. var pixels = ruler.pixels;
  4158. var curr = pixels[index];
  4159. var prev = index > 0 ? pixels[index - 1] : null;
  4160. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  4161. var percent = options.categoryPercentage;
  4162. var start, size;
  4163. if (prev === null) {
  4164. // first data: its size is double based on the next point or,
  4165. // if it's also the last data, we use the scale size.
  4166. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  4167. }
  4168. if (next === null) {
  4169. // last data: its size is also double based on the previous point.
  4170. next = curr + curr - prev;
  4171. }
  4172. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  4173. size = Math.abs(next - prev) / 2 * percent;
  4174. return {
  4175. chunk: size / ruler.stackCount,
  4176. ratio: options.barPercentage,
  4177. start: start
  4178. };
  4179. }
  4180. var controller_bar = core_datasetController.extend({
  4181. dataElementType: elements.Rectangle,
  4182. /**
  4183. * @private
  4184. */
  4185. _dataElementOptions: [
  4186. 'backgroundColor',
  4187. 'borderColor',
  4188. 'borderSkipped',
  4189. 'borderWidth',
  4190. 'barPercentage',
  4191. 'barThickness',
  4192. 'categoryPercentage',
  4193. 'maxBarThickness',
  4194. 'minBarLength'
  4195. ],
  4196. initialize: function() {
  4197. var me = this;
  4198. var meta, scaleOpts;
  4199. core_datasetController.prototype.initialize.apply(me, arguments);
  4200. meta = me.getMeta();
  4201. meta.stack = me.getDataset().stack;
  4202. meta.bar = true;
  4203. scaleOpts = me._getIndexScale().options;
  4204. deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
  4205. deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
  4206. deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
  4207. deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
  4208. deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
  4209. },
  4210. update: function(reset) {
  4211. var me = this;
  4212. var rects = me.getMeta().data;
  4213. var i, ilen;
  4214. me._ruler = me.getRuler();
  4215. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  4216. me.updateElement(rects[i], i, reset);
  4217. }
  4218. },
  4219. updateElement: function(rectangle, index, reset) {
  4220. var me = this;
  4221. var meta = me.getMeta();
  4222. var dataset = me.getDataset();
  4223. var options = me._resolveDataElementOptions(rectangle, index);
  4224. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  4225. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  4226. rectangle._datasetIndex = me.index;
  4227. rectangle._index = index;
  4228. rectangle._model = {
  4229. backgroundColor: options.backgroundColor,
  4230. borderColor: options.borderColor,
  4231. borderSkipped: options.borderSkipped,
  4232. borderWidth: options.borderWidth,
  4233. datasetLabel: dataset.label,
  4234. label: me.chart.data.labels[index]
  4235. };
  4236. if (helpers$1.isArray(dataset.data[index])) {
  4237. rectangle._model.borderSkipped = null;
  4238. }
  4239. me._updateElementGeometry(rectangle, index, reset, options);
  4240. rectangle.pivot();
  4241. },
  4242. /**
  4243. * @private
  4244. */
  4245. _updateElementGeometry: function(rectangle, index, reset, options) {
  4246. var me = this;
  4247. var model = rectangle._model;
  4248. var vscale = me._getValueScale();
  4249. var base = vscale.getBasePixel();
  4250. var horizontal = vscale.isHorizontal();
  4251. var ruler = me._ruler || me.getRuler();
  4252. var vpixels = me.calculateBarValuePixels(me.index, index, options);
  4253. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
  4254. model.horizontal = horizontal;
  4255. model.base = reset ? base : vpixels.base;
  4256. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  4257. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  4258. model.height = horizontal ? ipixels.size : undefined;
  4259. model.width = horizontal ? undefined : ipixels.size;
  4260. },
  4261. /**
  4262. * Returns the stacks based on groups and bar visibility.
  4263. * @param {number} [last] - The dataset index
  4264. * @returns {string[]} The list of stack IDs
  4265. * @private
  4266. */
  4267. _getStacks: function(last) {
  4268. var me = this;
  4269. var scale = me._getIndexScale();
  4270. var metasets = scale._getMatchingVisibleMetas(me._type);
  4271. var stacked = scale.options.stacked;
  4272. var ilen = metasets.length;
  4273. var stacks = [];
  4274. var i, meta;
  4275. for (i = 0; i < ilen; ++i) {
  4276. meta = metasets[i];
  4277. // stacked | meta.stack
  4278. // | found | not found | undefined
  4279. // false | x | x | x
  4280. // true | | x |
  4281. // undefined | | x | x
  4282. if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
  4283. (stacked === undefined && meta.stack === undefined)) {
  4284. stacks.push(meta.stack);
  4285. }
  4286. if (meta.index === last) {
  4287. break;
  4288. }
  4289. }
  4290. return stacks;
  4291. },
  4292. /**
  4293. * Returns the effective number of stacks based on groups and bar visibility.
  4294. * @private
  4295. */
  4296. getStackCount: function() {
  4297. return this._getStacks().length;
  4298. },
  4299. /**
  4300. * Returns the stack index for the given dataset based on groups and bar visibility.
  4301. * @param {number} [datasetIndex] - The dataset index
  4302. * @param {string} [name] - The stack name to find
  4303. * @returns {number} The stack index
  4304. * @private
  4305. */
  4306. getStackIndex: function(datasetIndex, name) {
  4307. var stacks = this._getStacks(datasetIndex);
  4308. var index = (name !== undefined)
  4309. ? stacks.indexOf(name)
  4310. : -1; // indexOf returns -1 if element is not present
  4311. return (index === -1)
  4312. ? stacks.length - 1
  4313. : index;
  4314. },
  4315. /**
  4316. * @private
  4317. */
  4318. getRuler: function() {
  4319. var me = this;
  4320. var scale = me._getIndexScale();
  4321. var pixels = [];
  4322. var i, ilen;
  4323. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  4324. pixels.push(scale.getPixelForValue(null, i, me.index));
  4325. }
  4326. return {
  4327. pixels: pixels,
  4328. start: scale._startPixel,
  4329. end: scale._endPixel,
  4330. stackCount: me.getStackCount(),
  4331. scale: scale
  4332. };
  4333. },
  4334. /**
  4335. * Note: pixel values are not clamped to the scale area.
  4336. * @private
  4337. */
  4338. calculateBarValuePixels: function(datasetIndex, index, options) {
  4339. var me = this;
  4340. var chart = me.chart;
  4341. var scale = me._getValueScale();
  4342. var isHorizontal = scale.isHorizontal();
  4343. var datasets = chart.data.datasets;
  4344. var metasets = scale._getMatchingVisibleMetas(me._type);
  4345. var value = scale._parseValue(datasets[datasetIndex].data[index]);
  4346. var minBarLength = options.minBarLength;
  4347. var stacked = scale.options.stacked;
  4348. var stack = me.getMeta().stack;
  4349. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  4350. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  4351. var ilen = metasets.length;
  4352. var i, imeta, ivalue, base, head, size, stackLength;
  4353. if (stacked || (stacked === undefined && stack !== undefined)) {
  4354. for (i = 0; i < ilen; ++i) {
  4355. imeta = metasets[i];
  4356. if (imeta.index === datasetIndex) {
  4357. break;
  4358. }
  4359. if (imeta.stack === stack) {
  4360. stackLength = scale._parseValue(datasets[imeta.index].data[index]);
  4361. ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
  4362. if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
  4363. start += ivalue;
  4364. }
  4365. }
  4366. }
  4367. }
  4368. base = scale.getPixelForValue(start);
  4369. head = scale.getPixelForValue(start + length);
  4370. size = head - base;
  4371. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  4372. size = minBarLength;
  4373. if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
  4374. head = base - minBarLength;
  4375. } else {
  4376. head = base + minBarLength;
  4377. }
  4378. }
  4379. return {
  4380. size: size,
  4381. base: base,
  4382. head: head,
  4383. center: head + size / 2
  4384. };
  4385. },
  4386. /**
  4387. * @private
  4388. */
  4389. calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {
  4390. var me = this;
  4391. var range = options.barThickness === 'flex'
  4392. ? computeFlexCategoryTraits(index, ruler, options)
  4393. : computeFitCategoryTraits(index, ruler, options);
  4394. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  4395. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  4396. var size = Math.min(
  4397. valueOrDefault$3(options.maxBarThickness, Infinity),
  4398. range.chunk * range.ratio);
  4399. return {
  4400. base: center - size / 2,
  4401. head: center + size / 2,
  4402. center: center,
  4403. size: size
  4404. };
  4405. },
  4406. draw: function() {
  4407. var me = this;
  4408. var chart = me.chart;
  4409. var scale = me._getValueScale();
  4410. var rects = me.getMeta().data;
  4411. var dataset = me.getDataset();
  4412. var ilen = rects.length;
  4413. var i = 0;
  4414. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  4415. for (; i < ilen; ++i) {
  4416. var val = scale._parseValue(dataset.data[i]);
  4417. if (!isNaN(val.min) && !isNaN(val.max)) {
  4418. rects[i].draw();
  4419. }
  4420. }
  4421. helpers$1.canvas.unclipArea(chart.ctx);
  4422. },
  4423. /**
  4424. * @private
  4425. */
  4426. _resolveDataElementOptions: function() {
  4427. var me = this;
  4428. var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));
  4429. var indexOpts = me._getIndexScale().options;
  4430. var valueOpts = me._getValueScale().options;
  4431. values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);
  4432. values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);
  4433. values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);
  4434. values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);
  4435. values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);
  4436. return values;
  4437. }
  4438. });
  4439. var valueOrDefault$4 = helpers$1.valueOrDefault;
  4440. var resolve$1 = helpers$1.options.resolve;
  4441. core_defaults._set('bubble', {
  4442. hover: {
  4443. mode: 'single'
  4444. },
  4445. scales: {
  4446. xAxes: [{
  4447. type: 'linear', // bubble should probably use a linear scale by default
  4448. position: 'bottom',
  4449. id: 'x-axis-0' // need an ID so datasets can reference the scale
  4450. }],
  4451. yAxes: [{
  4452. type: 'linear',
  4453. position: 'left',
  4454. id: 'y-axis-0'
  4455. }]
  4456. },
  4457. tooltips: {
  4458. callbacks: {
  4459. title: function() {
  4460. // Title doesn't make sense for scatter since we format the data as a point
  4461. return '';
  4462. },
  4463. label: function(item, data) {
  4464. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  4465. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  4466. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  4467. }
  4468. }
  4469. }
  4470. });
  4471. var controller_bubble = core_datasetController.extend({
  4472. /**
  4473. * @protected
  4474. */
  4475. dataElementType: elements.Point,
  4476. /**
  4477. * @private
  4478. */
  4479. _dataElementOptions: [
  4480. 'backgroundColor',
  4481. 'borderColor',
  4482. 'borderWidth',
  4483. 'hoverBackgroundColor',
  4484. 'hoverBorderColor',
  4485. 'hoverBorderWidth',
  4486. 'hoverRadius',
  4487. 'hitRadius',
  4488. 'pointStyle',
  4489. 'rotation'
  4490. ],
  4491. /**
  4492. * @protected
  4493. */
  4494. update: function(reset) {
  4495. var me = this;
  4496. var meta = me.getMeta();
  4497. var points = meta.data;
  4498. // Update Points
  4499. helpers$1.each(points, function(point, index) {
  4500. me.updateElement(point, index, reset);
  4501. });
  4502. },
  4503. /**
  4504. * @protected
  4505. */
  4506. updateElement: function(point, index, reset) {
  4507. var me = this;
  4508. var meta = me.getMeta();
  4509. var custom = point.custom || {};
  4510. var xScale = me.getScaleForId(meta.xAxisID);
  4511. var yScale = me.getScaleForId(meta.yAxisID);
  4512. var options = me._resolveDataElementOptions(point, index);
  4513. var data = me.getDataset().data[index];
  4514. var dsIndex = me.index;
  4515. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  4516. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  4517. point._xScale = xScale;
  4518. point._yScale = yScale;
  4519. point._options = options;
  4520. point._datasetIndex = dsIndex;
  4521. point._index = index;
  4522. point._model = {
  4523. backgroundColor: options.backgroundColor,
  4524. borderColor: options.borderColor,
  4525. borderWidth: options.borderWidth,
  4526. hitRadius: options.hitRadius,
  4527. pointStyle: options.pointStyle,
  4528. rotation: options.rotation,
  4529. radius: reset ? 0 : options.radius,
  4530. skip: custom.skip || isNaN(x) || isNaN(y),
  4531. x: x,
  4532. y: y,
  4533. };
  4534. point.pivot();
  4535. },
  4536. /**
  4537. * @protected
  4538. */
  4539. setHoverStyle: function(point) {
  4540. var model = point._model;
  4541. var options = point._options;
  4542. var getHoverColor = helpers$1.getHoverColor;
  4543. point.$previousStyle = {
  4544. backgroundColor: model.backgroundColor,
  4545. borderColor: model.borderColor,
  4546. borderWidth: model.borderWidth,
  4547. radius: model.radius
  4548. };
  4549. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4550. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4551. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4552. model.radius = options.radius + options.hoverRadius;
  4553. },
  4554. /**
  4555. * @private
  4556. */
  4557. _resolveDataElementOptions: function(point, index) {
  4558. var me = this;
  4559. var chart = me.chart;
  4560. var dataset = me.getDataset();
  4561. var custom = point.custom || {};
  4562. var data = dataset.data[index] || {};
  4563. var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);
  4564. // Scriptable options
  4565. var context = {
  4566. chart: chart,
  4567. dataIndex: index,
  4568. dataset: dataset,
  4569. datasetIndex: me.index
  4570. };
  4571. // In case values were cached (and thus frozen), we need to clone the values
  4572. if (me._cachedDataOpts === values) {
  4573. values = helpers$1.extend({}, values);
  4574. }
  4575. // Custom radius resolution
  4576. values.radius = resolve$1([
  4577. custom.radius,
  4578. data.r,
  4579. me._config.radius,
  4580. chart.options.elements.point.radius
  4581. ], context, index);
  4582. return values;
  4583. }
  4584. });
  4585. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4586. var PI$1 = Math.PI;
  4587. var DOUBLE_PI$1 = PI$1 * 2;
  4588. var HALF_PI$1 = PI$1 / 2;
  4589. core_defaults._set('doughnut', {
  4590. animation: {
  4591. // Boolean - Whether we animate the rotation of the Doughnut
  4592. animateRotate: true,
  4593. // Boolean - Whether we animate scaling the Doughnut from the centre
  4594. animateScale: false
  4595. },
  4596. hover: {
  4597. mode: 'single'
  4598. },
  4599. legendCallback: function(chart) {
  4600. var list = document.createElement('ul');
  4601. var data = chart.data;
  4602. var datasets = data.datasets;
  4603. var labels = data.labels;
  4604. var i, ilen, listItem, listItemSpan;
  4605. list.setAttribute('class', chart.id + '-legend');
  4606. if (datasets.length) {
  4607. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  4608. listItem = list.appendChild(document.createElement('li'));
  4609. listItemSpan = listItem.appendChild(document.createElement('span'));
  4610. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  4611. if (labels[i]) {
  4612. listItem.appendChild(document.createTextNode(labels[i]));
  4613. }
  4614. }
  4615. }
  4616. return list.outerHTML;
  4617. },
  4618. legend: {
  4619. labels: {
  4620. generateLabels: function(chart) {
  4621. var data = chart.data;
  4622. if (data.labels.length && data.datasets.length) {
  4623. return data.labels.map(function(label, i) {
  4624. var meta = chart.getDatasetMeta(0);
  4625. var style = meta.controller.getStyle(i);
  4626. return {
  4627. text: label,
  4628. fillStyle: style.backgroundColor,
  4629. strokeStyle: style.borderColor,
  4630. lineWidth: style.borderWidth,
  4631. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  4632. // Extra data used for toggling the correct item
  4633. index: i
  4634. };
  4635. });
  4636. }
  4637. return [];
  4638. }
  4639. },
  4640. onClick: function(e, legendItem) {
  4641. var index = legendItem.index;
  4642. var chart = this.chart;
  4643. var i, ilen, meta;
  4644. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4645. meta = chart.getDatasetMeta(i);
  4646. // toggle visibility of index if exists
  4647. if (meta.data[index]) {
  4648. meta.data[index].hidden = !meta.data[index].hidden;
  4649. }
  4650. }
  4651. chart.update();
  4652. }
  4653. },
  4654. // The percentage of the chart that we cut out of the middle.
  4655. cutoutPercentage: 50,
  4656. // The rotation of the chart, where the first data arc begins.
  4657. rotation: -HALF_PI$1,
  4658. // The total circumference of the chart.
  4659. circumference: DOUBLE_PI$1,
  4660. // Need to override these to give a nice default
  4661. tooltips: {
  4662. callbacks: {
  4663. title: function() {
  4664. return '';
  4665. },
  4666. label: function(tooltipItem, data) {
  4667. var dataLabel = data.labels[tooltipItem.index];
  4668. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  4669. if (helpers$1.isArray(dataLabel)) {
  4670. // show value on first line of multiline label
  4671. // need to clone because we are changing the value
  4672. dataLabel = dataLabel.slice();
  4673. dataLabel[0] += value;
  4674. } else {
  4675. dataLabel += value;
  4676. }
  4677. return dataLabel;
  4678. }
  4679. }
  4680. }
  4681. });
  4682. var controller_doughnut = core_datasetController.extend({
  4683. dataElementType: elements.Arc,
  4684. linkScales: helpers$1.noop,
  4685. /**
  4686. * @private
  4687. */
  4688. _dataElementOptions: [
  4689. 'backgroundColor',
  4690. 'borderColor',
  4691. 'borderWidth',
  4692. 'borderAlign',
  4693. 'hoverBackgroundColor',
  4694. 'hoverBorderColor',
  4695. 'hoverBorderWidth',
  4696. ],
  4697. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  4698. getRingIndex: function(datasetIndex) {
  4699. var ringIndex = 0;
  4700. for (var j = 0; j < datasetIndex; ++j) {
  4701. if (this.chart.isDatasetVisible(j)) {
  4702. ++ringIndex;
  4703. }
  4704. }
  4705. return ringIndex;
  4706. },
  4707. update: function(reset) {
  4708. var me = this;
  4709. var chart = me.chart;
  4710. var chartArea = chart.chartArea;
  4711. var opts = chart.options;
  4712. var ratioX = 1;
  4713. var ratioY = 1;
  4714. var offsetX = 0;
  4715. var offsetY = 0;
  4716. var meta = me.getMeta();
  4717. var arcs = meta.data;
  4718. var cutout = opts.cutoutPercentage / 100 || 0;
  4719. var circumference = opts.circumference;
  4720. var chartWeight = me._getRingWeight(me.index);
  4721. var maxWidth, maxHeight, i, ilen;
  4722. // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
  4723. if (circumference < DOUBLE_PI$1) {
  4724. var startAngle = opts.rotation % DOUBLE_PI$1;
  4725. startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;
  4726. var endAngle = startAngle + circumference;
  4727. var startX = Math.cos(startAngle);
  4728. var startY = Math.sin(startAngle);
  4729. var endX = Math.cos(endAngle);
  4730. var endY = Math.sin(endAngle);
  4731. var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;
  4732. var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;
  4733. var contains180 = startAngle === -PI$1 || endAngle >= PI$1;
  4734. var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;
  4735. var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
  4736. var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
  4737. var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
  4738. var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
  4739. ratioX = (maxX - minX) / 2;
  4740. ratioY = (maxY - minY) / 2;
  4741. offsetX = -(maxX + minX) / 2;
  4742. offsetY = -(maxY + minY) / 2;
  4743. }
  4744. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4745. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  4746. }
  4747. chart.borderWidth = me.getMaxBorderWidth();
  4748. maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
  4749. maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
  4750. chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  4751. chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
  4752. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  4753. chart.offsetX = offsetX * chart.outerRadius;
  4754. chart.offsetY = offsetY * chart.outerRadius;
  4755. meta.total = me.calculateTotal();
  4756. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  4757. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  4758. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4759. me.updateElement(arcs[i], i, reset);
  4760. }
  4761. },
  4762. updateElement: function(arc, index, reset) {
  4763. var me = this;
  4764. var chart = me.chart;
  4765. var chartArea = chart.chartArea;
  4766. var opts = chart.options;
  4767. var animationOpts = opts.animation;
  4768. var centerX = (chartArea.left + chartArea.right) / 2;
  4769. var centerY = (chartArea.top + chartArea.bottom) / 2;
  4770. var startAngle = opts.rotation; // non reset case handled later
  4771. var endAngle = opts.rotation; // non reset case handled later
  4772. var dataset = me.getDataset();
  4773. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1);
  4774. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  4775. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  4776. var options = arc._options || {};
  4777. helpers$1.extend(arc, {
  4778. // Utility
  4779. _datasetIndex: me.index,
  4780. _index: index,
  4781. // Desired view properties
  4782. _model: {
  4783. backgroundColor: options.backgroundColor,
  4784. borderColor: options.borderColor,
  4785. borderWidth: options.borderWidth,
  4786. borderAlign: options.borderAlign,
  4787. x: centerX + chart.offsetX,
  4788. y: centerY + chart.offsetY,
  4789. startAngle: startAngle,
  4790. endAngle: endAngle,
  4791. circumference: circumference,
  4792. outerRadius: outerRadius,
  4793. innerRadius: innerRadius,
  4794. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4795. }
  4796. });
  4797. var model = arc._model;
  4798. // Set correct angles if not resetting
  4799. if (!reset || !animationOpts.animateRotate) {
  4800. if (index === 0) {
  4801. model.startAngle = opts.rotation;
  4802. } else {
  4803. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4804. }
  4805. model.endAngle = model.startAngle + model.circumference;
  4806. }
  4807. arc.pivot();
  4808. },
  4809. calculateTotal: function() {
  4810. var dataset = this.getDataset();
  4811. var meta = this.getMeta();
  4812. var total = 0;
  4813. var value;
  4814. helpers$1.each(meta.data, function(element, index) {
  4815. value = dataset.data[index];
  4816. if (!isNaN(value) && !element.hidden) {
  4817. total += Math.abs(value);
  4818. }
  4819. });
  4820. /* if (total === 0) {
  4821. total = NaN;
  4822. }*/
  4823. return total;
  4824. },
  4825. calculateCircumference: function(value) {
  4826. var total = this.getMeta().total;
  4827. if (total > 0 && !isNaN(value)) {
  4828. return DOUBLE_PI$1 * (Math.abs(value) / total);
  4829. }
  4830. return 0;
  4831. },
  4832. // gets the max border or hover width to properly scale pie charts
  4833. getMaxBorderWidth: function(arcs) {
  4834. var me = this;
  4835. var max = 0;
  4836. var chart = me.chart;
  4837. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4838. if (!arcs) {
  4839. // Find the outmost visible dataset
  4840. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4841. if (chart.isDatasetVisible(i)) {
  4842. meta = chart.getDatasetMeta(i);
  4843. arcs = meta.data;
  4844. if (i !== me.index) {
  4845. controller = meta.controller;
  4846. }
  4847. break;
  4848. }
  4849. }
  4850. }
  4851. if (!arcs) {
  4852. return 0;
  4853. }
  4854. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4855. arc = arcs[i];
  4856. if (controller) {
  4857. controller._configure();
  4858. options = controller._resolveDataElementOptions(arc, i);
  4859. } else {
  4860. options = arc._options;
  4861. }
  4862. if (options.borderAlign !== 'inner') {
  4863. borderWidth = options.borderWidth;
  4864. hoverWidth = options.hoverBorderWidth;
  4865. max = borderWidth > max ? borderWidth : max;
  4866. max = hoverWidth > max ? hoverWidth : max;
  4867. }
  4868. }
  4869. return max;
  4870. },
  4871. /**
  4872. * @protected
  4873. */
  4874. setHoverStyle: function(arc) {
  4875. var model = arc._model;
  4876. var options = arc._options;
  4877. var getHoverColor = helpers$1.getHoverColor;
  4878. arc.$previousStyle = {
  4879. backgroundColor: model.backgroundColor,
  4880. borderColor: model.borderColor,
  4881. borderWidth: model.borderWidth,
  4882. };
  4883. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4884. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4885. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4886. },
  4887. /**
  4888. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4889. * @private
  4890. */
  4891. _getRingWeightOffset: function(datasetIndex) {
  4892. var ringWeightOffset = 0;
  4893. for (var i = 0; i < datasetIndex; ++i) {
  4894. if (this.chart.isDatasetVisible(i)) {
  4895. ringWeightOffset += this._getRingWeight(i);
  4896. }
  4897. }
  4898. return ringWeightOffset;
  4899. },
  4900. /**
  4901. * @private
  4902. */
  4903. _getRingWeight: function(dataSetIndex) {
  4904. return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4905. },
  4906. /**
  4907. * Returns the sum of all visibile data set weights. This value can be 0.
  4908. * @private
  4909. */
  4910. _getVisibleDatasetWeightTotal: function() {
  4911. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4912. }
  4913. });
  4914. core_defaults._set('horizontalBar', {
  4915. hover: {
  4916. mode: 'index',
  4917. axis: 'y'
  4918. },
  4919. scales: {
  4920. xAxes: [{
  4921. type: 'linear',
  4922. position: 'bottom'
  4923. }],
  4924. yAxes: [{
  4925. type: 'category',
  4926. position: 'left',
  4927. offset: true,
  4928. gridLines: {
  4929. offsetGridLines: true
  4930. }
  4931. }]
  4932. },
  4933. elements: {
  4934. rectangle: {
  4935. borderSkipped: 'left'
  4936. }
  4937. },
  4938. tooltips: {
  4939. mode: 'index',
  4940. axis: 'y'
  4941. }
  4942. });
  4943. core_defaults._set('global', {
  4944. datasets: {
  4945. horizontalBar: {
  4946. categoryPercentage: 0.8,
  4947. barPercentage: 0.9
  4948. }
  4949. }
  4950. });
  4951. var controller_horizontalBar = controller_bar.extend({
  4952. /**
  4953. * @private
  4954. */
  4955. _getValueScaleId: function() {
  4956. return this.getMeta().xAxisID;
  4957. },
  4958. /**
  4959. * @private
  4960. */
  4961. _getIndexScaleId: function() {
  4962. return this.getMeta().yAxisID;
  4963. }
  4964. });
  4965. var valueOrDefault$6 = helpers$1.valueOrDefault;
  4966. var resolve$2 = helpers$1.options.resolve;
  4967. var isPointInArea = helpers$1.canvas._isPointInArea;
  4968. core_defaults._set('line', {
  4969. showLines: true,
  4970. spanGaps: false,
  4971. hover: {
  4972. mode: 'label'
  4973. },
  4974. scales: {
  4975. xAxes: [{
  4976. type: 'category',
  4977. id: 'x-axis-0'
  4978. }],
  4979. yAxes: [{
  4980. type: 'linear',
  4981. id: 'y-axis-0'
  4982. }]
  4983. }
  4984. });
  4985. function scaleClip(scale, halfBorderWidth) {
  4986. var tickOpts = scale && scale.options.ticks || {};
  4987. var reverse = tickOpts.reverse;
  4988. var min = tickOpts.min === undefined ? halfBorderWidth : 0;
  4989. var max = tickOpts.max === undefined ? halfBorderWidth : 0;
  4990. return {
  4991. start: reverse ? max : min,
  4992. end: reverse ? min : max
  4993. };
  4994. }
  4995. function defaultClip(xScale, yScale, borderWidth) {
  4996. var halfBorderWidth = borderWidth / 2;
  4997. var x = scaleClip(xScale, halfBorderWidth);
  4998. var y = scaleClip(yScale, halfBorderWidth);
  4999. return {
  5000. top: y.end,
  5001. right: x.end,
  5002. bottom: y.start,
  5003. left: x.start
  5004. };
  5005. }
  5006. function toClip(value) {
  5007. var t, r, b, l;
  5008. if (helpers$1.isObject(value)) {
  5009. t = value.top;
  5010. r = value.right;
  5011. b = value.bottom;
  5012. l = value.left;
  5013. } else {
  5014. t = r = b = l = value;
  5015. }
  5016. return {
  5017. top: t,
  5018. right: r,
  5019. bottom: b,
  5020. left: l
  5021. };
  5022. }
  5023. var controller_line = core_datasetController.extend({
  5024. datasetElementType: elements.Line,
  5025. dataElementType: elements.Point,
  5026. /**
  5027. * @private
  5028. */
  5029. _datasetElementOptions: [
  5030. 'backgroundColor',
  5031. 'borderCapStyle',
  5032. 'borderColor',
  5033. 'borderDash',
  5034. 'borderDashOffset',
  5035. 'borderJoinStyle',
  5036. 'borderWidth',
  5037. 'cubicInterpolationMode',
  5038. 'fill'
  5039. ],
  5040. /**
  5041. * @private
  5042. */
  5043. _dataElementOptions: {
  5044. backgroundColor: 'pointBackgroundColor',
  5045. borderColor: 'pointBorderColor',
  5046. borderWidth: 'pointBorderWidth',
  5047. hitRadius: 'pointHitRadius',
  5048. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5049. hoverBorderColor: 'pointHoverBorderColor',
  5050. hoverBorderWidth: 'pointHoverBorderWidth',
  5051. hoverRadius: 'pointHoverRadius',
  5052. pointStyle: 'pointStyle',
  5053. radius: 'pointRadius',
  5054. rotation: 'pointRotation'
  5055. },
  5056. update: function(reset) {
  5057. var me = this;
  5058. var meta = me.getMeta();
  5059. var line = meta.dataset;
  5060. var points = meta.data || [];
  5061. var options = me.chart.options;
  5062. var config = me._config;
  5063. var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);
  5064. var i, ilen;
  5065. me._xScale = me.getScaleForId(meta.xAxisID);
  5066. me._yScale = me.getScaleForId(meta.yAxisID);
  5067. // Update Line
  5068. if (showLine) {
  5069. // Compatibility: If the properties are defined with only the old name, use those values
  5070. if (config.tension !== undefined && config.lineTension === undefined) {
  5071. config.lineTension = config.tension;
  5072. }
  5073. // Utility
  5074. line._scale = me._yScale;
  5075. line._datasetIndex = me.index;
  5076. // Data
  5077. line._children = points;
  5078. // Model
  5079. line._model = me._resolveDatasetElementOptions(line);
  5080. line.pivot();
  5081. }
  5082. // Update Points
  5083. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5084. me.updateElement(points[i], i, reset);
  5085. }
  5086. if (showLine && line._model.tension !== 0) {
  5087. me.updateBezierControlPoints();
  5088. }
  5089. // Now pivot the point for animation
  5090. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5091. points[i].pivot();
  5092. }
  5093. },
  5094. updateElement: function(point, index, reset) {
  5095. var me = this;
  5096. var meta = me.getMeta();
  5097. var custom = point.custom || {};
  5098. var dataset = me.getDataset();
  5099. var datasetIndex = me.index;
  5100. var value = dataset.data[index];
  5101. var xScale = me._xScale;
  5102. var yScale = me._yScale;
  5103. var lineModel = meta.dataset._model;
  5104. var x, y;
  5105. var options = me._resolveDataElementOptions(point, index);
  5106. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  5107. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  5108. // Utility
  5109. point._xScale = xScale;
  5110. point._yScale = yScale;
  5111. point._options = options;
  5112. point._datasetIndex = datasetIndex;
  5113. point._index = index;
  5114. // Desired view properties
  5115. point._model = {
  5116. x: x,
  5117. y: y,
  5118. skip: custom.skip || isNaN(x) || isNaN(y),
  5119. // Appearance
  5120. radius: options.radius,
  5121. pointStyle: options.pointStyle,
  5122. rotation: options.rotation,
  5123. backgroundColor: options.backgroundColor,
  5124. borderColor: options.borderColor,
  5125. borderWidth: options.borderWidth,
  5126. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  5127. steppedLine: lineModel ? lineModel.steppedLine : false,
  5128. // Tooltip
  5129. hitRadius: options.hitRadius
  5130. };
  5131. },
  5132. /**
  5133. * @private
  5134. */
  5135. _resolveDatasetElementOptions: function(element) {
  5136. var me = this;
  5137. var config = me._config;
  5138. var custom = element.custom || {};
  5139. var options = me.chart.options;
  5140. var lineOptions = options.elements.line;
  5141. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5142. // The default behavior of lines is to break at null values, according
  5143. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  5144. // This option gives lines the ability to span gaps
  5145. values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps);
  5146. values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);
  5147. values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
  5148. values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
  5149. return values;
  5150. },
  5151. calculatePointY: function(value, index, datasetIndex) {
  5152. var me = this;
  5153. var chart = me.chart;
  5154. var yScale = me._yScale;
  5155. var sumPos = 0;
  5156. var sumNeg = 0;
  5157. var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
  5158. if (yScale.options.stacked) {
  5159. rightValue = +yScale.getRightValue(value);
  5160. metasets = chart._getSortedVisibleDatasetMetas();
  5161. ilen = metasets.length;
  5162. for (i = 0; i < ilen; ++i) {
  5163. dsMeta = metasets[i];
  5164. if (dsMeta.index === datasetIndex) {
  5165. break;
  5166. }
  5167. ds = chart.data.datasets[dsMeta.index];
  5168. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
  5169. stackedRightValue = +yScale.getRightValue(ds.data[index]);
  5170. if (stackedRightValue < 0) {
  5171. sumNeg += stackedRightValue || 0;
  5172. } else {
  5173. sumPos += stackedRightValue || 0;
  5174. }
  5175. }
  5176. }
  5177. if (rightValue < 0) {
  5178. return yScale.getPixelForValue(sumNeg + rightValue);
  5179. }
  5180. return yScale.getPixelForValue(sumPos + rightValue);
  5181. }
  5182. return yScale.getPixelForValue(value);
  5183. },
  5184. updateBezierControlPoints: function() {
  5185. var me = this;
  5186. var chart = me.chart;
  5187. var meta = me.getMeta();
  5188. var lineModel = meta.dataset._model;
  5189. var area = chart.chartArea;
  5190. var points = meta.data || [];
  5191. var i, ilen, model, controlPoints;
  5192. // Only consider points that are drawn in case the spanGaps option is used
  5193. if (lineModel.spanGaps) {
  5194. points = points.filter(function(pt) {
  5195. return !pt._model.skip;
  5196. });
  5197. }
  5198. function capControlPoint(pt, min, max) {
  5199. return Math.max(Math.min(pt, max), min);
  5200. }
  5201. if (lineModel.cubicInterpolationMode === 'monotone') {
  5202. helpers$1.splineCurveMonotone(points);
  5203. } else {
  5204. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5205. model = points[i]._model;
  5206. controlPoints = helpers$1.splineCurve(
  5207. helpers$1.previousItem(points, i)._model,
  5208. model,
  5209. helpers$1.nextItem(points, i)._model,
  5210. lineModel.tension
  5211. );
  5212. model.controlPointPreviousX = controlPoints.previous.x;
  5213. model.controlPointPreviousY = controlPoints.previous.y;
  5214. model.controlPointNextX = controlPoints.next.x;
  5215. model.controlPointNextY = controlPoints.next.y;
  5216. }
  5217. }
  5218. if (chart.options.elements.line.capBezierPoints) {
  5219. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5220. model = points[i]._model;
  5221. if (isPointInArea(model, area)) {
  5222. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  5223. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  5224. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  5225. }
  5226. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  5227. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  5228. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  5229. }
  5230. }
  5231. }
  5232. }
  5233. },
  5234. draw: function() {
  5235. var me = this;
  5236. var chart = me.chart;
  5237. var meta = me.getMeta();
  5238. var points = meta.data || [];
  5239. var area = chart.chartArea;
  5240. var canvas = chart.canvas;
  5241. var i = 0;
  5242. var ilen = points.length;
  5243. var clip;
  5244. if (me._showLine) {
  5245. clip = meta.dataset._model.clip;
  5246. helpers$1.canvas.clipArea(chart.ctx, {
  5247. left: clip.left === false ? 0 : area.left - clip.left,
  5248. right: clip.right === false ? canvas.width : area.right + clip.right,
  5249. top: clip.top === false ? 0 : area.top - clip.top,
  5250. bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
  5251. });
  5252. meta.dataset.draw();
  5253. helpers$1.canvas.unclipArea(chart.ctx);
  5254. }
  5255. // Draw the points
  5256. for (; i < ilen; ++i) {
  5257. points[i].draw(area);
  5258. }
  5259. },
  5260. /**
  5261. * @protected
  5262. */
  5263. setHoverStyle: function(point) {
  5264. var model = point._model;
  5265. var options = point._options;
  5266. var getHoverColor = helpers$1.getHoverColor;
  5267. point.$previousStyle = {
  5268. backgroundColor: model.backgroundColor,
  5269. borderColor: model.borderColor,
  5270. borderWidth: model.borderWidth,
  5271. radius: model.radius
  5272. };
  5273. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5274. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  5275. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  5276. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  5277. },
  5278. });
  5279. var resolve$3 = helpers$1.options.resolve;
  5280. core_defaults._set('polarArea', {
  5281. scale: {
  5282. type: 'radialLinear',
  5283. angleLines: {
  5284. display: false
  5285. },
  5286. gridLines: {
  5287. circular: true
  5288. },
  5289. pointLabels: {
  5290. display: false
  5291. },
  5292. ticks: {
  5293. beginAtZero: true
  5294. }
  5295. },
  5296. // Boolean - Whether to animate the rotation of the chart
  5297. animation: {
  5298. animateRotate: true,
  5299. animateScale: true
  5300. },
  5301. startAngle: -0.5 * Math.PI,
  5302. legendCallback: function(chart) {
  5303. var list = document.createElement('ul');
  5304. var data = chart.data;
  5305. var datasets = data.datasets;
  5306. var labels = data.labels;
  5307. var i, ilen, listItem, listItemSpan;
  5308. list.setAttribute('class', chart.id + '-legend');
  5309. if (datasets.length) {
  5310. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  5311. listItem = list.appendChild(document.createElement('li'));
  5312. listItemSpan = listItem.appendChild(document.createElement('span'));
  5313. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  5314. if (labels[i]) {
  5315. listItem.appendChild(document.createTextNode(labels[i]));
  5316. }
  5317. }
  5318. }
  5319. return list.outerHTML;
  5320. },
  5321. legend: {
  5322. labels: {
  5323. generateLabels: function(chart) {
  5324. var data = chart.data;
  5325. if (data.labels.length && data.datasets.length) {
  5326. return data.labels.map(function(label, i) {
  5327. var meta = chart.getDatasetMeta(0);
  5328. var style = meta.controller.getStyle(i);
  5329. return {
  5330. text: label,
  5331. fillStyle: style.backgroundColor,
  5332. strokeStyle: style.borderColor,
  5333. lineWidth: style.borderWidth,
  5334. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  5335. // Extra data used for toggling the correct item
  5336. index: i
  5337. };
  5338. });
  5339. }
  5340. return [];
  5341. }
  5342. },
  5343. onClick: function(e, legendItem) {
  5344. var index = legendItem.index;
  5345. var chart = this.chart;
  5346. var i, ilen, meta;
  5347. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  5348. meta = chart.getDatasetMeta(i);
  5349. meta.data[index].hidden = !meta.data[index].hidden;
  5350. }
  5351. chart.update();
  5352. }
  5353. },
  5354. // Need to override these to give a nice default
  5355. tooltips: {
  5356. callbacks: {
  5357. title: function() {
  5358. return '';
  5359. },
  5360. label: function(item, data) {
  5361. return data.labels[item.index] + ': ' + item.yLabel;
  5362. }
  5363. }
  5364. }
  5365. });
  5366. var controller_polarArea = core_datasetController.extend({
  5367. dataElementType: elements.Arc,
  5368. linkScales: helpers$1.noop,
  5369. /**
  5370. * @private
  5371. */
  5372. _dataElementOptions: [
  5373. 'backgroundColor',
  5374. 'borderColor',
  5375. 'borderWidth',
  5376. 'borderAlign',
  5377. 'hoverBackgroundColor',
  5378. 'hoverBorderColor',
  5379. 'hoverBorderWidth',
  5380. ],
  5381. /**
  5382. * @private
  5383. */
  5384. _getIndexScaleId: function() {
  5385. return this.chart.scale.id;
  5386. },
  5387. /**
  5388. * @private
  5389. */
  5390. _getValueScaleId: function() {
  5391. return this.chart.scale.id;
  5392. },
  5393. update: function(reset) {
  5394. var me = this;
  5395. var dataset = me.getDataset();
  5396. var meta = me.getMeta();
  5397. var start = me.chart.options.startAngle || 0;
  5398. var starts = me._starts = [];
  5399. var angles = me._angles = [];
  5400. var arcs = meta.data;
  5401. var i, ilen, angle;
  5402. me._updateRadius();
  5403. meta.count = me.countVisibleElements();
  5404. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  5405. starts[i] = start;
  5406. angle = me._computeAngle(i);
  5407. angles[i] = angle;
  5408. start += angle;
  5409. }
  5410. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  5411. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  5412. me.updateElement(arcs[i], i, reset);
  5413. }
  5414. },
  5415. /**
  5416. * @private
  5417. */
  5418. _updateRadius: function() {
  5419. var me = this;
  5420. var chart = me.chart;
  5421. var chartArea = chart.chartArea;
  5422. var opts = chart.options;
  5423. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  5424. chart.outerRadius = Math.max(minSize / 2, 0);
  5425. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  5426. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  5427. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  5428. me.innerRadius = me.outerRadius - chart.radiusLength;
  5429. },
  5430. updateElement: function(arc, index, reset) {
  5431. var me = this;
  5432. var chart = me.chart;
  5433. var dataset = me.getDataset();
  5434. var opts = chart.options;
  5435. var animationOpts = opts.animation;
  5436. var scale = chart.scale;
  5437. var labels = chart.data.labels;
  5438. var centerX = scale.xCenter;
  5439. var centerY = scale.yCenter;
  5440. // var negHalfPI = -0.5 * Math.PI;
  5441. var datasetStartAngle = opts.startAngle;
  5442. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5443. var startAngle = me._starts[index];
  5444. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  5445. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5446. var options = arc._options || {};
  5447. helpers$1.extend(arc, {
  5448. // Utility
  5449. _datasetIndex: me.index,
  5450. _index: index,
  5451. _scale: scale,
  5452. // Desired view properties
  5453. _model: {
  5454. backgroundColor: options.backgroundColor,
  5455. borderColor: options.borderColor,
  5456. borderWidth: options.borderWidth,
  5457. borderAlign: options.borderAlign,
  5458. x: centerX,
  5459. y: centerY,
  5460. innerRadius: 0,
  5461. outerRadius: reset ? resetRadius : distance,
  5462. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  5463. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  5464. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  5465. }
  5466. });
  5467. arc.pivot();
  5468. },
  5469. countVisibleElements: function() {
  5470. var dataset = this.getDataset();
  5471. var meta = this.getMeta();
  5472. var count = 0;
  5473. helpers$1.each(meta.data, function(element, index) {
  5474. if (!isNaN(dataset.data[index]) && !element.hidden) {
  5475. count++;
  5476. }
  5477. });
  5478. return count;
  5479. },
  5480. /**
  5481. * @protected
  5482. */
  5483. setHoverStyle: function(arc) {
  5484. var model = arc._model;
  5485. var options = arc._options;
  5486. var getHoverColor = helpers$1.getHoverColor;
  5487. var valueOrDefault = helpers$1.valueOrDefault;
  5488. arc.$previousStyle = {
  5489. backgroundColor: model.backgroundColor,
  5490. borderColor: model.borderColor,
  5491. borderWidth: model.borderWidth,
  5492. };
  5493. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5494. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  5495. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  5496. },
  5497. /**
  5498. * @private
  5499. */
  5500. _computeAngle: function(index) {
  5501. var me = this;
  5502. var count = this.getMeta().count;
  5503. var dataset = me.getDataset();
  5504. var meta = me.getMeta();
  5505. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  5506. return 0;
  5507. }
  5508. // Scriptable options
  5509. var context = {
  5510. chart: me.chart,
  5511. dataIndex: index,
  5512. dataset: dataset,
  5513. datasetIndex: me.index
  5514. };
  5515. return resolve$3([
  5516. me.chart.options.elements.arc.angle,
  5517. (2 * Math.PI) / count
  5518. ], context, index);
  5519. }
  5520. });
  5521. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  5522. core_defaults._set('pie', {
  5523. cutoutPercentage: 0
  5524. });
  5525. // Pie charts are Doughnut chart with different defaults
  5526. var controller_pie = controller_doughnut;
  5527. var valueOrDefault$7 = helpers$1.valueOrDefault;
  5528. core_defaults._set('radar', {
  5529. spanGaps: false,
  5530. scale: {
  5531. type: 'radialLinear'
  5532. },
  5533. elements: {
  5534. line: {
  5535. fill: 'start',
  5536. tension: 0 // no bezier in radar
  5537. }
  5538. }
  5539. });
  5540. var controller_radar = core_datasetController.extend({
  5541. datasetElementType: elements.Line,
  5542. dataElementType: elements.Point,
  5543. linkScales: helpers$1.noop,
  5544. /**
  5545. * @private
  5546. */
  5547. _datasetElementOptions: [
  5548. 'backgroundColor',
  5549. 'borderWidth',
  5550. 'borderColor',
  5551. 'borderCapStyle',
  5552. 'borderDash',
  5553. 'borderDashOffset',
  5554. 'borderJoinStyle',
  5555. 'fill'
  5556. ],
  5557. /**
  5558. * @private
  5559. */
  5560. _dataElementOptions: {
  5561. backgroundColor: 'pointBackgroundColor',
  5562. borderColor: 'pointBorderColor',
  5563. borderWidth: 'pointBorderWidth',
  5564. hitRadius: 'pointHitRadius',
  5565. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5566. hoverBorderColor: 'pointHoverBorderColor',
  5567. hoverBorderWidth: 'pointHoverBorderWidth',
  5568. hoverRadius: 'pointHoverRadius',
  5569. pointStyle: 'pointStyle',
  5570. radius: 'pointRadius',
  5571. rotation: 'pointRotation'
  5572. },
  5573. /**
  5574. * @private
  5575. */
  5576. _getIndexScaleId: function() {
  5577. return this.chart.scale.id;
  5578. },
  5579. /**
  5580. * @private
  5581. */
  5582. _getValueScaleId: function() {
  5583. return this.chart.scale.id;
  5584. },
  5585. update: function(reset) {
  5586. var me = this;
  5587. var meta = me.getMeta();
  5588. var line = meta.dataset;
  5589. var points = meta.data || [];
  5590. var scale = me.chart.scale;
  5591. var config = me._config;
  5592. var i, ilen;
  5593. // Compatibility: If the properties are defined with only the old name, use those values
  5594. if (config.tension !== undefined && config.lineTension === undefined) {
  5595. config.lineTension = config.tension;
  5596. }
  5597. // Utility
  5598. line._scale = scale;
  5599. line._datasetIndex = me.index;
  5600. // Data
  5601. line._children = points;
  5602. line._loop = true;
  5603. // Model
  5604. line._model = me._resolveDatasetElementOptions(line);
  5605. line.pivot();
  5606. // Update Points
  5607. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5608. me.updateElement(points[i], i, reset);
  5609. }
  5610. // Update bezier control points
  5611. me.updateBezierControlPoints();
  5612. // Now pivot the point for animation
  5613. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5614. points[i].pivot();
  5615. }
  5616. },
  5617. updateElement: function(point, index, reset) {
  5618. var me = this;
  5619. var custom = point.custom || {};
  5620. var dataset = me.getDataset();
  5621. var scale = me.chart.scale;
  5622. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  5623. var options = me._resolveDataElementOptions(point, index);
  5624. var lineModel = me.getMeta().dataset._model;
  5625. var x = reset ? scale.xCenter : pointPosition.x;
  5626. var y = reset ? scale.yCenter : pointPosition.y;
  5627. // Utility
  5628. point._scale = scale;
  5629. point._options = options;
  5630. point._datasetIndex = me.index;
  5631. point._index = index;
  5632. // Desired view properties
  5633. point._model = {
  5634. x: x, // value not used in dataset scale, but we want a consistent API between scales
  5635. y: y,
  5636. skip: custom.skip || isNaN(x) || isNaN(y),
  5637. // Appearance
  5638. radius: options.radius,
  5639. pointStyle: options.pointStyle,
  5640. rotation: options.rotation,
  5641. backgroundColor: options.backgroundColor,
  5642. borderColor: options.borderColor,
  5643. borderWidth: options.borderWidth,
  5644. tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0),
  5645. // Tooltip
  5646. hitRadius: options.hitRadius
  5647. };
  5648. },
  5649. /**
  5650. * @private
  5651. */
  5652. _resolveDatasetElementOptions: function() {
  5653. var me = this;
  5654. var config = me._config;
  5655. var options = me.chart.options;
  5656. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5657. values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);
  5658. values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);
  5659. return values;
  5660. },
  5661. updateBezierControlPoints: function() {
  5662. var me = this;
  5663. var meta = me.getMeta();
  5664. var area = me.chart.chartArea;
  5665. var points = meta.data || [];
  5666. var i, ilen, model, controlPoints;
  5667. // Only consider points that are drawn in case the spanGaps option is used
  5668. if (meta.dataset._model.spanGaps) {
  5669. points = points.filter(function(pt) {
  5670. return !pt._model.skip;
  5671. });
  5672. }
  5673. function capControlPoint(pt, min, max) {
  5674. return Math.max(Math.min(pt, max), min);
  5675. }
  5676. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5677. model = points[i]._model;
  5678. controlPoints = helpers$1.splineCurve(
  5679. helpers$1.previousItem(points, i, true)._model,
  5680. model,
  5681. helpers$1.nextItem(points, i, true)._model,
  5682. model.tension
  5683. );
  5684. // Prevent the bezier going outside of the bounds of the graph
  5685. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  5686. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  5687. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  5688. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  5689. }
  5690. },
  5691. setHoverStyle: function(point) {
  5692. var model = point._model;
  5693. var options = point._options;
  5694. var getHoverColor = helpers$1.getHoverColor;
  5695. point.$previousStyle = {
  5696. backgroundColor: model.backgroundColor,
  5697. borderColor: model.borderColor,
  5698. borderWidth: model.borderWidth,
  5699. radius: model.radius
  5700. };
  5701. model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5702. model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));
  5703. model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);
  5704. model.radius = valueOrDefault$7(options.hoverRadius, options.radius);
  5705. }
  5706. });
  5707. core_defaults._set('scatter', {
  5708. hover: {
  5709. mode: 'single'
  5710. },
  5711. scales: {
  5712. xAxes: [{
  5713. id: 'x-axis-1', // need an ID so datasets can reference the scale
  5714. type: 'linear', // scatter should not use a category axis
  5715. position: 'bottom'
  5716. }],
  5717. yAxes: [{
  5718. id: 'y-axis-1',
  5719. type: 'linear',
  5720. position: 'left'
  5721. }]
  5722. },
  5723. tooltips: {
  5724. callbacks: {
  5725. title: function() {
  5726. return ''; // doesn't make sense for scatter since data are formatted as a point
  5727. },
  5728. label: function(item) {
  5729. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  5730. }
  5731. }
  5732. }
  5733. });
  5734. core_defaults._set('global', {
  5735. datasets: {
  5736. scatter: {
  5737. showLine: false
  5738. }
  5739. }
  5740. });
  5741. // Scatter charts use line controllers
  5742. var controller_scatter = controller_line;
  5743. // NOTE export a map in which the key represents the controller type, not
  5744. // the class, and so must be CamelCase in order to be correctly retrieved
  5745. // by the controller in core.controller.js (`controllers[meta.type]`).
  5746. var controllers = {
  5747. bar: controller_bar,
  5748. bubble: controller_bubble,
  5749. doughnut: controller_doughnut,
  5750. horizontalBar: controller_horizontalBar,
  5751. line: controller_line,
  5752. polarArea: controller_polarArea,
  5753. pie: controller_pie,
  5754. radar: controller_radar,
  5755. scatter: controller_scatter
  5756. };
  5757. /**
  5758. * Helper function to get relative position for an event
  5759. * @param {Event|IEvent} event - The event to get the position for
  5760. * @param {Chart} chart - The chart
  5761. * @returns {object} the event position
  5762. */
  5763. function getRelativePosition(e, chart) {
  5764. if (e.native) {
  5765. return {
  5766. x: e.x,
  5767. y: e.y
  5768. };
  5769. }
  5770. return helpers$1.getRelativePosition(e, chart);
  5771. }
  5772. /**
  5773. * Helper function to traverse all of the visible elements in the chart
  5774. * @param {Chart} chart - the chart
  5775. * @param {function} handler - the callback to execute for each visible item
  5776. */
  5777. function parseVisibleItems(chart, handler) {
  5778. var metasets = chart._getSortedVisibleDatasetMetas();
  5779. var metadata, i, j, ilen, jlen, element;
  5780. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  5781. metadata = metasets[i].data;
  5782. for (j = 0, jlen = metadata.length; j < jlen; ++j) {
  5783. element = metadata[j];
  5784. if (!element._view.skip) {
  5785. handler(element);
  5786. }
  5787. }
  5788. }
  5789. }
  5790. /**
  5791. * Helper function to get the items that intersect the event position
  5792. * @param {ChartElement[]} items - elements to filter
  5793. * @param {object} position - the point to be nearest to
  5794. * @return {ChartElement[]} the nearest items
  5795. */
  5796. function getIntersectItems(chart, position) {
  5797. var elements = [];
  5798. parseVisibleItems(chart, function(element) {
  5799. if (element.inRange(position.x, position.y)) {
  5800. elements.push(element);
  5801. }
  5802. });
  5803. return elements;
  5804. }
  5805. /**
  5806. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5807. * @param {Chart} chart - the chart to look at elements from
  5808. * @param {object} position - the point to be nearest to
  5809. * @param {boolean} intersect - if true, only consider items that intersect the position
  5810. * @param {function} distanceMetric - function to provide the distance between points
  5811. * @return {ChartElement[]} the nearest items
  5812. */
  5813. function getNearestItems(chart, position, intersect, distanceMetric) {
  5814. var minDistance = Number.POSITIVE_INFINITY;
  5815. var nearestItems = [];
  5816. parseVisibleItems(chart, function(element) {
  5817. if (intersect && !element.inRange(position.x, position.y)) {
  5818. return;
  5819. }
  5820. var center = element.getCenterPoint();
  5821. var distance = distanceMetric(position, center);
  5822. if (distance < minDistance) {
  5823. nearestItems = [element];
  5824. minDistance = distance;
  5825. } else if (distance === minDistance) {
  5826. // Can have multiple items at the same distance in which case we sort by size
  5827. nearestItems.push(element);
  5828. }
  5829. });
  5830. return nearestItems;
  5831. }
  5832. /**
  5833. * Get a distance metric function for two points based on the
  5834. * axis mode setting
  5835. * @param {string} axis - the axis mode. x|y|xy
  5836. */
  5837. function getDistanceMetricForAxis(axis) {
  5838. var useX = axis.indexOf('x') !== -1;
  5839. var useY = axis.indexOf('y') !== -1;
  5840. return function(pt1, pt2) {
  5841. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5842. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5843. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5844. };
  5845. }
  5846. function indexMode(chart, e, options) {
  5847. var position = getRelativePosition(e, chart);
  5848. // Default axis for index mode is 'x' to match old behaviour
  5849. options.axis = options.axis || 'x';
  5850. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5851. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5852. var elements = [];
  5853. if (!items.length) {
  5854. return [];
  5855. }
  5856. chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
  5857. var element = meta.data[items[0]._index];
  5858. // don't count items that are skipped (null data)
  5859. if (element && !element._view.skip) {
  5860. elements.push(element);
  5861. }
  5862. });
  5863. return elements;
  5864. }
  5865. /**
  5866. * @interface IInteractionOptions
  5867. */
  5868. /**
  5869. * If true, only consider items that intersect the point
  5870. * @name IInterfaceOptions#boolean
  5871. * @type Boolean
  5872. */
  5873. /**
  5874. * Contains interaction related functions
  5875. * @namespace Chart.Interaction
  5876. */
  5877. var core_interaction = {
  5878. // Helper function for different modes
  5879. modes: {
  5880. single: function(chart, e) {
  5881. var position = getRelativePosition(e, chart);
  5882. var elements = [];
  5883. parseVisibleItems(chart, function(element) {
  5884. if (element.inRange(position.x, position.y)) {
  5885. elements.push(element);
  5886. return elements;
  5887. }
  5888. });
  5889. return elements.slice(0, 1);
  5890. },
  5891. /**
  5892. * @function Chart.Interaction.modes.label
  5893. * @deprecated since version 2.4.0
  5894. * @todo remove at version 3
  5895. * @private
  5896. */
  5897. label: indexMode,
  5898. /**
  5899. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5900. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5901. * @function Chart.Interaction.modes.index
  5902. * @since v2.4.0
  5903. * @param {Chart} chart - the chart we are returning items from
  5904. * @param {Event} e - the event we are find things at
  5905. * @param {IInteractionOptions} options - options to use during interaction
  5906. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5907. */
  5908. index: indexMode,
  5909. /**
  5910. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5911. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5912. * @function Chart.Interaction.modes.dataset
  5913. * @param {Chart} chart - the chart we are returning items from
  5914. * @param {Event} e - the event we are find things at
  5915. * @param {IInteractionOptions} options - options to use during interaction
  5916. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5917. */
  5918. dataset: function(chart, e, options) {
  5919. var position = getRelativePosition(e, chart);
  5920. options.axis = options.axis || 'xy';
  5921. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5922. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5923. if (items.length > 0) {
  5924. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5925. }
  5926. return items;
  5927. },
  5928. /**
  5929. * @function Chart.Interaction.modes.x-axis
  5930. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5931. * @todo remove at version 3
  5932. * @private
  5933. */
  5934. 'x-axis': function(chart, e) {
  5935. return indexMode(chart, e, {intersect: false});
  5936. },
  5937. /**
  5938. * Point mode returns all elements that hit test based on the event position
  5939. * of the event
  5940. * @function Chart.Interaction.modes.intersect
  5941. * @param {Chart} chart - the chart we are returning items from
  5942. * @param {Event} e - the event we are find things at
  5943. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5944. */
  5945. point: function(chart, e) {
  5946. var position = getRelativePosition(e, chart);
  5947. return getIntersectItems(chart, position);
  5948. },
  5949. /**
  5950. * nearest mode returns the element closest to the point
  5951. * @function Chart.Interaction.modes.intersect
  5952. * @param {Chart} chart - the chart we are returning items from
  5953. * @param {Event} e - the event we are find things at
  5954. * @param {IInteractionOptions} options - options to use
  5955. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5956. */
  5957. nearest: function(chart, e, options) {
  5958. var position = getRelativePosition(e, chart);
  5959. options.axis = options.axis || 'xy';
  5960. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5961. return getNearestItems(chart, position, options.intersect, distanceMetric);
  5962. },
  5963. /**
  5964. * x mode returns the elements that hit-test at the current x coordinate
  5965. * @function Chart.Interaction.modes.x
  5966. * @param {Chart} chart - the chart we are returning items from
  5967. * @param {Event} e - the event we are find things at
  5968. * @param {IInteractionOptions} options - options to use
  5969. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5970. */
  5971. x: function(chart, e, options) {
  5972. var position = getRelativePosition(e, chart);
  5973. var items = [];
  5974. var intersectsItem = false;
  5975. parseVisibleItems(chart, function(element) {
  5976. if (element.inXRange(position.x)) {
  5977. items.push(element);
  5978. }
  5979. if (element.inRange(position.x, position.y)) {
  5980. intersectsItem = true;
  5981. }
  5982. });
  5983. // If we want to trigger on an intersect and we don't have any items
  5984. // that intersect the position, return nothing
  5985. if (options.intersect && !intersectsItem) {
  5986. items = [];
  5987. }
  5988. return items;
  5989. },
  5990. /**
  5991. * y mode returns the elements that hit-test at the current y coordinate
  5992. * @function Chart.Interaction.modes.y
  5993. * @param {Chart} chart - the chart we are returning items from
  5994. * @param {Event} e - the event we are find things at
  5995. * @param {IInteractionOptions} options - options to use
  5996. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5997. */
  5998. y: function(chart, e, options) {
  5999. var position = getRelativePosition(e, chart);
  6000. var items = [];
  6001. var intersectsItem = false;
  6002. parseVisibleItems(chart, function(element) {
  6003. if (element.inYRange(position.y)) {
  6004. items.push(element);
  6005. }
  6006. if (element.inRange(position.x, position.y)) {
  6007. intersectsItem = true;
  6008. }
  6009. });
  6010. // If we want to trigger on an intersect and we don't have any items
  6011. // that intersect the position, return nothing
  6012. if (options.intersect && !intersectsItem) {
  6013. items = [];
  6014. }
  6015. return items;
  6016. }
  6017. }
  6018. };
  6019. var extend = helpers$1.extend;
  6020. function filterByPosition(array, position) {
  6021. return helpers$1.where(array, function(v) {
  6022. return v.pos === position;
  6023. });
  6024. }
  6025. function sortByWeight(array, reverse) {
  6026. return array.sort(function(a, b) {
  6027. var v0 = reverse ? b : a;
  6028. var v1 = reverse ? a : b;
  6029. return v0.weight === v1.weight ?
  6030. v0.index - v1.index :
  6031. v0.weight - v1.weight;
  6032. });
  6033. }
  6034. function wrapBoxes(boxes) {
  6035. var layoutBoxes = [];
  6036. var i, ilen, box;
  6037. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  6038. box = boxes[i];
  6039. layoutBoxes.push({
  6040. index: i,
  6041. box: box,
  6042. pos: box.position,
  6043. horizontal: box.isHorizontal(),
  6044. weight: box.weight
  6045. });
  6046. }
  6047. return layoutBoxes;
  6048. }
  6049. function setLayoutDims(layouts, params) {
  6050. var i, ilen, layout;
  6051. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  6052. layout = layouts[i];
  6053. // store width used instead of chartArea.w in fitBoxes
  6054. layout.width = layout.horizontal
  6055. ? layout.box.fullWidth && params.availableWidth
  6056. : params.vBoxMaxWidth;
  6057. // store height used instead of chartArea.h in fitBoxes
  6058. layout.height = layout.horizontal && params.hBoxMaxHeight;
  6059. }
  6060. }
  6061. function buildLayoutBoxes(boxes) {
  6062. var layoutBoxes = wrapBoxes(boxes);
  6063. var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  6064. var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  6065. var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  6066. var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  6067. return {
  6068. leftAndTop: left.concat(top),
  6069. rightAndBottom: right.concat(bottom),
  6070. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  6071. vertical: left.concat(right),
  6072. horizontal: top.concat(bottom)
  6073. };
  6074. }
  6075. function getCombinedMax(maxPadding, chartArea, a, b) {
  6076. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  6077. }
  6078. function updateDims(chartArea, params, layout) {
  6079. var box = layout.box;
  6080. var maxPadding = chartArea.maxPadding;
  6081. var newWidth, newHeight;
  6082. if (layout.size) {
  6083. // this layout was already counted for, lets first reduce old size
  6084. chartArea[layout.pos] -= layout.size;
  6085. }
  6086. layout.size = layout.horizontal ? box.height : box.width;
  6087. chartArea[layout.pos] += layout.size;
  6088. if (box.getPadding) {
  6089. var boxPadding = box.getPadding();
  6090. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  6091. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  6092. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  6093. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  6094. }
  6095. newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
  6096. newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
  6097. if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
  6098. chartArea.w = newWidth;
  6099. chartArea.h = newHeight;
  6100. // return true if chart area changed in layout's direction
  6101. var sizes = layout.horizontal ? [newWidth, chartArea.w] : [newHeight, chartArea.h];
  6102. return sizes[0] !== sizes[1] && (!isNaN(sizes[0]) || !isNaN(sizes[1]));
  6103. }
  6104. }
  6105. function handleMaxPadding(chartArea) {
  6106. var maxPadding = chartArea.maxPadding;
  6107. function updatePos(pos) {
  6108. var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  6109. chartArea[pos] += change;
  6110. return change;
  6111. }
  6112. chartArea.y += updatePos('top');
  6113. chartArea.x += updatePos('left');
  6114. updatePos('right');
  6115. updatePos('bottom');
  6116. }
  6117. function getMargins(horizontal, chartArea) {
  6118. var maxPadding = chartArea.maxPadding;
  6119. function marginForPositions(positions) {
  6120. var margin = {left: 0, top: 0, right: 0, bottom: 0};
  6121. positions.forEach(function(pos) {
  6122. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  6123. });
  6124. return margin;
  6125. }
  6126. return horizontal
  6127. ? marginForPositions(['left', 'right'])
  6128. : marginForPositions(['top', 'bottom']);
  6129. }
  6130. function fitBoxes(boxes, chartArea, params) {
  6131. var refitBoxes = [];
  6132. var i, ilen, layout, box, refit, changed;
  6133. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6134. layout = boxes[i];
  6135. box = layout.box;
  6136. box.update(
  6137. layout.width || chartArea.w,
  6138. layout.height || chartArea.h,
  6139. getMargins(layout.horizontal, chartArea)
  6140. );
  6141. if (updateDims(chartArea, params, layout)) {
  6142. changed = true;
  6143. if (refitBoxes.length) {
  6144. // Dimensions changed and there were non full width boxes before this
  6145. // -> we have to refit those
  6146. refit = true;
  6147. }
  6148. }
  6149. if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case
  6150. refitBoxes.push(layout);
  6151. }
  6152. }
  6153. return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;
  6154. }
  6155. function placeBoxes(boxes, chartArea, params) {
  6156. var userPadding = params.padding;
  6157. var x = chartArea.x;
  6158. var y = chartArea.y;
  6159. var i, ilen, layout, box;
  6160. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6161. layout = boxes[i];
  6162. box = layout.box;
  6163. if (layout.horizontal) {
  6164. box.left = box.fullWidth ? userPadding.left : chartArea.left;
  6165. box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  6166. box.top = y;
  6167. box.bottom = y + box.height;
  6168. box.width = box.right - box.left;
  6169. y = box.bottom;
  6170. } else {
  6171. box.left = x;
  6172. box.right = x + box.width;
  6173. box.top = chartArea.top;
  6174. box.bottom = chartArea.top + chartArea.h;
  6175. box.height = box.bottom - box.top;
  6176. x = box.right;
  6177. }
  6178. }
  6179. chartArea.x = x;
  6180. chartArea.y = y;
  6181. }
  6182. core_defaults._set('global', {
  6183. layout: {
  6184. padding: {
  6185. top: 0,
  6186. right: 0,
  6187. bottom: 0,
  6188. left: 0
  6189. }
  6190. }
  6191. });
  6192. /**
  6193. * @interface ILayoutItem
  6194. * @prop {string} position - The position of the item in the chart layout. Possible values are
  6195. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  6196. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  6197. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  6198. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  6199. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  6200. * @prop {function} getPadding - Returns an object with padding on the edges
  6201. * @prop {number} width - Width of item. Must be valid after update()
  6202. * @prop {number} height - Height of item. Must be valid after update()
  6203. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  6204. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  6205. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  6206. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  6207. */
  6208. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  6209. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  6210. // It is this service's responsibility of carrying out that layout.
  6211. var core_layouts = {
  6212. defaults: {},
  6213. /**
  6214. * Register a box to a chart.
  6215. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  6216. * @param {Chart} chart - the chart to use
  6217. * @param {ILayoutItem} item - the item to add to be layed out
  6218. */
  6219. addBox: function(chart, item) {
  6220. if (!chart.boxes) {
  6221. chart.boxes = [];
  6222. }
  6223. // initialize item with default values
  6224. item.fullWidth = item.fullWidth || false;
  6225. item.position = item.position || 'top';
  6226. item.weight = item.weight || 0;
  6227. item._layers = item._layers || function() {
  6228. return [{
  6229. z: 0,
  6230. draw: function() {
  6231. item.draw.apply(item, arguments);
  6232. }
  6233. }];
  6234. };
  6235. chart.boxes.push(item);
  6236. },
  6237. /**
  6238. * Remove a layoutItem from a chart
  6239. * @param {Chart} chart - the chart to remove the box from
  6240. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  6241. */
  6242. removeBox: function(chart, layoutItem) {
  6243. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  6244. if (index !== -1) {
  6245. chart.boxes.splice(index, 1);
  6246. }
  6247. },
  6248. /**
  6249. * Sets (or updates) options on the given `item`.
  6250. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  6251. * @param {ILayoutItem} item - the item to configure with the given options
  6252. * @param {object} options - the new item options.
  6253. */
  6254. configure: function(chart, item, options) {
  6255. var props = ['fullWidth', 'position', 'weight'];
  6256. var ilen = props.length;
  6257. var i = 0;
  6258. var prop;
  6259. for (; i < ilen; ++i) {
  6260. prop = props[i];
  6261. if (options.hasOwnProperty(prop)) {
  6262. item[prop] = options[prop];
  6263. }
  6264. }
  6265. },
  6266. /**
  6267. * Fits boxes of the given chart into the given size by having each box measure itself
  6268. * then running a fitting algorithm
  6269. * @param {Chart} chart - the chart
  6270. * @param {number} width - the width to fit into
  6271. * @param {number} height - the height to fit into
  6272. */
  6273. update: function(chart, width, height) {
  6274. if (!chart) {
  6275. return;
  6276. }
  6277. var layoutOptions = chart.options.layout || {};
  6278. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  6279. var availableWidth = width - padding.width;
  6280. var availableHeight = height - padding.height;
  6281. var boxes = buildLayoutBoxes(chart.boxes);
  6282. var verticalBoxes = boxes.vertical;
  6283. var horizontalBoxes = boxes.horizontal;
  6284. // Essentially we now have any number of boxes on each of the 4 sides.
  6285. // Our canvas looks like the following.
  6286. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  6287. // B1 is the bottom axis
  6288. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  6289. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  6290. // an error will be thrown.
  6291. //
  6292. // |----------------------------------------------------|
  6293. // | T1 (Full Width) |
  6294. // |----------------------------------------------------|
  6295. // | | | T2 | |
  6296. // | |----|-------------------------------------|----|
  6297. // | | | C1 | | C2 | |
  6298. // | | |----| |----| |
  6299. // | | | | |
  6300. // | L1 | L2 | ChartArea (C0) | R1 |
  6301. // | | | | |
  6302. // | | |----| |----| |
  6303. // | | | C3 | | C4 | |
  6304. // | |----|-------------------------------------|----|
  6305. // | | | B1 | |
  6306. // |----------------------------------------------------|
  6307. // | B2 (Full Width) |
  6308. // |----------------------------------------------------|
  6309. //
  6310. var params = Object.freeze({
  6311. outerWidth: width,
  6312. outerHeight: height,
  6313. padding: padding,
  6314. availableWidth: availableWidth,
  6315. vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
  6316. hBoxMaxHeight: availableHeight / 2
  6317. });
  6318. var chartArea = extend({
  6319. maxPadding: extend({}, padding),
  6320. w: availableWidth,
  6321. h: availableHeight,
  6322. x: padding.left,
  6323. y: padding.top
  6324. }, padding);
  6325. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  6326. // First fit vertical boxes
  6327. fitBoxes(verticalBoxes, chartArea, params);
  6328. // Then fit horizontal boxes
  6329. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  6330. // if the area changed, re-fit vertical boxes
  6331. fitBoxes(verticalBoxes, chartArea, params);
  6332. }
  6333. handleMaxPadding(chartArea);
  6334. // Finally place the boxes to correct coordinates
  6335. placeBoxes(boxes.leftAndTop, chartArea, params);
  6336. // Move to opposite side of chart
  6337. chartArea.x += chartArea.w;
  6338. chartArea.y += chartArea.h;
  6339. placeBoxes(boxes.rightAndBottom, chartArea, params);
  6340. chart.chartArea = {
  6341. left: chartArea.left,
  6342. top: chartArea.top,
  6343. right: chartArea.left + chartArea.w,
  6344. bottom: chartArea.top + chartArea.h
  6345. };
  6346. // Finally update boxes in chartArea (radial scale for example)
  6347. helpers$1.each(boxes.chartArea, function(layout) {
  6348. var box = layout.box;
  6349. extend(box, chart.chartArea);
  6350. box.update(chartArea.w, chartArea.h);
  6351. });
  6352. }
  6353. };
  6354. /**
  6355. * Platform fallback implementation (minimal).
  6356. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  6357. */
  6358. var platform_basic = {
  6359. acquireContext: function(item) {
  6360. if (item && item.canvas) {
  6361. // Support for any object associated to a canvas (including a context2d)
  6362. item = item.canvas;
  6363. }
  6364. return item && item.getContext('2d') || null;
  6365. }
  6366. };
  6367. var platform_dom = "/*\r\n * DOM element rendering detection\r\n * https://davidwalsh.name/detect-node-insertion\r\n */\r\n@keyframes chartjs-render-animation {\r\n\tfrom { opacity: 0.99; }\r\n\tto { opacity: 1; }\r\n}\r\n\r\n.chartjs-render-monitor {\r\n\tanimation: chartjs-render-animation 0.001s;\r\n}\r\n\r\n/*\r\n * DOM element resizing detection\r\n * https://github.com/marcj/css-element-queries\r\n */\r\n.chartjs-size-monitor,\r\n.chartjs-size-monitor-expand,\r\n.chartjs-size-monitor-shrink {\r\n\tposition: absolute;\r\n\tdirection: ltr;\r\n\tleft: 0;\r\n\ttop: 0;\r\n\tright: 0;\r\n\tbottom: 0;\r\n\toverflow: hidden;\r\n\tpointer-events: none;\r\n\tvisibility: hidden;\r\n\tz-index: -1;\r\n}\r\n\r\n.chartjs-size-monitor-expand > div {\r\n\tposition: absolute;\r\n\twidth: 1000000px;\r\n\theight: 1000000px;\r\n\tleft: 0;\r\n\ttop: 0;\r\n}\r\n\r\n.chartjs-size-monitor-shrink > div {\r\n\tposition: absolute;\r\n\twidth: 200%;\r\n\theight: 200%;\r\n\tleft: 0;\r\n\ttop: 0;\r\n}\r\n";
  6368. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  6369. __proto__: null,
  6370. 'default': platform_dom
  6371. });
  6372. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  6373. var EXPANDO_KEY = '$chartjs';
  6374. var CSS_PREFIX = 'chartjs-';
  6375. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  6376. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  6377. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  6378. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  6379. /**
  6380. * DOM event types -> Chart.js event types.
  6381. * Note: only events with different types are mapped.
  6382. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  6383. */
  6384. var EVENT_TYPES = {
  6385. touchstart: 'mousedown',
  6386. touchmove: 'mousemove',
  6387. touchend: 'mouseup',
  6388. pointerenter: 'mouseenter',
  6389. pointerdown: 'mousedown',
  6390. pointermove: 'mousemove',
  6391. pointerup: 'mouseup',
  6392. pointerleave: 'mouseout',
  6393. pointerout: 'mouseout'
  6394. };
  6395. /**
  6396. * The "used" size is the final value of a dimension property after all calculations have
  6397. * been performed. This method uses the computed style of `element` but returns undefined
  6398. * if the computed style is not expressed in pixels. That can happen in some cases where
  6399. * `element` has a size relative to its parent and this last one is not yet displayed,
  6400. * for example because of `display: none` on a parent node.
  6401. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  6402. * @returns {number} Size in pixels or undefined if unknown.
  6403. */
  6404. function readUsedSize(element, property) {
  6405. var value = helpers$1.getStyle(element, property);
  6406. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  6407. return matches ? Number(matches[1]) : undefined;
  6408. }
  6409. /**
  6410. * Initializes the canvas style and render size without modifying the canvas display size,
  6411. * since responsiveness is handled by the controller.resize() method. The config is used
  6412. * to determine the aspect ratio to apply in case no explicit height has been specified.
  6413. */
  6414. function initCanvas(canvas, config) {
  6415. var style = canvas.style;
  6416. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  6417. // returns null or '' if no explicit value has been set to the canvas attribute.
  6418. var renderHeight = canvas.getAttribute('height');
  6419. var renderWidth = canvas.getAttribute('width');
  6420. // Chart.js modifies some canvas values that we want to restore on destroy
  6421. canvas[EXPANDO_KEY] = {
  6422. initial: {
  6423. height: renderHeight,
  6424. width: renderWidth,
  6425. style: {
  6426. display: style.display,
  6427. height: style.height,
  6428. width: style.width
  6429. }
  6430. }
  6431. };
  6432. // Force canvas to display as block to avoid extra space caused by inline
  6433. // elements, which would interfere with the responsive resize process.
  6434. // https://github.com/chartjs/Chart.js/issues/2538
  6435. style.display = style.display || 'block';
  6436. if (renderWidth === null || renderWidth === '') {
  6437. var displayWidth = readUsedSize(canvas, 'width');
  6438. if (displayWidth !== undefined) {
  6439. canvas.width = displayWidth;
  6440. }
  6441. }
  6442. if (renderHeight === null || renderHeight === '') {
  6443. if (canvas.style.height === '') {
  6444. // If no explicit render height and style height, let's apply the aspect ratio,
  6445. // which one can be specified by the user but also by charts as default option
  6446. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  6447. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  6448. } else {
  6449. var displayHeight = readUsedSize(canvas, 'height');
  6450. if (displayWidth !== undefined) {
  6451. canvas.height = displayHeight;
  6452. }
  6453. }
  6454. }
  6455. return canvas;
  6456. }
  6457. /**
  6458. * Detects support for options object argument in addEventListener.
  6459. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  6460. * @private
  6461. */
  6462. var supportsEventListenerOptions = (function() {
  6463. var supports = false;
  6464. try {
  6465. var options = Object.defineProperty({}, 'passive', {
  6466. // eslint-disable-next-line getter-return
  6467. get: function() {
  6468. supports = true;
  6469. }
  6470. });
  6471. window.addEventListener('e', null, options);
  6472. } catch (e) {
  6473. // continue regardless of error
  6474. }
  6475. return supports;
  6476. }());
  6477. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  6478. // https://github.com/chartjs/Chart.js/issues/4287
  6479. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  6480. function addListener(node, type, listener) {
  6481. node.addEventListener(type, listener, eventListenerOptions);
  6482. }
  6483. function removeListener(node, type, listener) {
  6484. node.removeEventListener(type, listener, eventListenerOptions);
  6485. }
  6486. function createEvent(type, chart, x, y, nativeEvent) {
  6487. return {
  6488. type: type,
  6489. chart: chart,
  6490. native: nativeEvent || null,
  6491. x: x !== undefined ? x : null,
  6492. y: y !== undefined ? y : null,
  6493. };
  6494. }
  6495. function fromNativeEvent(event, chart) {
  6496. var type = EVENT_TYPES[event.type] || event.type;
  6497. var pos = helpers$1.getRelativePosition(event, chart);
  6498. return createEvent(type, chart, pos.x, pos.y, event);
  6499. }
  6500. function throttled(fn, thisArg) {
  6501. var ticking = false;
  6502. var args = [];
  6503. return function() {
  6504. args = Array.prototype.slice.call(arguments);
  6505. thisArg = thisArg || this;
  6506. if (!ticking) {
  6507. ticking = true;
  6508. helpers$1.requestAnimFrame.call(window, function() {
  6509. ticking = false;
  6510. fn.apply(thisArg, args);
  6511. });
  6512. }
  6513. };
  6514. }
  6515. function createDiv(cls) {
  6516. var el = document.createElement('div');
  6517. el.className = cls || '';
  6518. return el;
  6519. }
  6520. // Implementation based on https://github.com/marcj/css-element-queries
  6521. function createResizer(handler) {
  6522. var maxSize = 1000000;
  6523. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  6524. // https://github.com/chartjs/Chart.js/issues/5902
  6525. var resizer = createDiv(CSS_SIZE_MONITOR);
  6526. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  6527. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  6528. expand.appendChild(createDiv());
  6529. shrink.appendChild(createDiv());
  6530. resizer.appendChild(expand);
  6531. resizer.appendChild(shrink);
  6532. resizer._reset = function() {
  6533. expand.scrollLeft = maxSize;
  6534. expand.scrollTop = maxSize;
  6535. shrink.scrollLeft = maxSize;
  6536. shrink.scrollTop = maxSize;
  6537. };
  6538. var onScroll = function() {
  6539. resizer._reset();
  6540. handler();
  6541. };
  6542. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  6543. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  6544. return resizer;
  6545. }
  6546. // https://davidwalsh.name/detect-node-insertion
  6547. function watchForRender(node, handler) {
  6548. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6549. var proxy = expando.renderProxy = function(e) {
  6550. if (e.animationName === CSS_RENDER_ANIMATION) {
  6551. handler();
  6552. }
  6553. };
  6554. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6555. addListener(node, type, proxy);
  6556. });
  6557. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  6558. // is removed then added back immediately (same animation frame?). Accessing the
  6559. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  6560. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  6561. // https://github.com/chartjs/Chart.js/issues/4737
  6562. expando.reflow = !!node.offsetParent;
  6563. node.classList.add(CSS_RENDER_MONITOR);
  6564. }
  6565. function unwatchForRender(node) {
  6566. var expando = node[EXPANDO_KEY] || {};
  6567. var proxy = expando.renderProxy;
  6568. if (proxy) {
  6569. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6570. removeListener(node, type, proxy);
  6571. });
  6572. delete expando.renderProxy;
  6573. }
  6574. node.classList.remove(CSS_RENDER_MONITOR);
  6575. }
  6576. function addResizeListener(node, listener, chart) {
  6577. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6578. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  6579. var resizer = expando.resizer = createResizer(throttled(function() {
  6580. if (expando.resizer) {
  6581. var container = chart.options.maintainAspectRatio && node.parentNode;
  6582. var w = container ? container.clientWidth : 0;
  6583. listener(createEvent('resize', chart));
  6584. if (container && container.clientWidth < w && chart.canvas) {
  6585. // If the container size shrank during chart resize, let's assume
  6586. // scrollbar appeared. So we resize again with the scrollbar visible -
  6587. // effectively making chart smaller and the scrollbar hidden again.
  6588. // Because we are inside `throttled`, and currently `ticking`, scroll
  6589. // events are ignored during this whole 2 resize process.
  6590. // If we assumed wrong and something else happened, we are resizing
  6591. // twice in a frame (potential performance issue)
  6592. listener(createEvent('resize', chart));
  6593. }
  6594. }
  6595. }));
  6596. // The resizer needs to be attached to the node parent, so we first need to be
  6597. // sure that `node` is attached to the DOM before injecting the resizer element.
  6598. watchForRender(node, function() {
  6599. if (expando.resizer) {
  6600. var container = node.parentNode;
  6601. if (container && container !== resizer.parentNode) {
  6602. container.insertBefore(resizer, container.firstChild);
  6603. }
  6604. // The container size might have changed, let's reset the resizer state.
  6605. resizer._reset();
  6606. }
  6607. });
  6608. }
  6609. function removeResizeListener(node) {
  6610. var expando = node[EXPANDO_KEY] || {};
  6611. var resizer = expando.resizer;
  6612. delete expando.resizer;
  6613. unwatchForRender(node);
  6614. if (resizer && resizer.parentNode) {
  6615. resizer.parentNode.removeChild(resizer);
  6616. }
  6617. }
  6618. /**
  6619. * Injects CSS styles inline if the styles are not already present.
  6620. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.
  6621. * @param {string} css - the CSS to be injected.
  6622. */
  6623. function injectCSS(rootNode, css) {
  6624. // https://stackoverflow.com/q/3922139
  6625. var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});
  6626. if (!expando.containsStyles) {
  6627. expando.containsStyles = true;
  6628. css = '/* Chart.js */\n' + css;
  6629. var style = document.createElement('style');
  6630. style.setAttribute('type', 'text/css');
  6631. style.appendChild(document.createTextNode(css));
  6632. rootNode.appendChild(style);
  6633. }
  6634. }
  6635. var platform_dom$2 = {
  6636. /**
  6637. * When `true`, prevents the automatic injection of the stylesheet required to
  6638. * correctly detect when the chart is added to the DOM and then resized. This
  6639. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  6640. * to be manually imported to make this library compatible with any CSP.
  6641. * See https://github.com/chartjs/Chart.js/issues/5208
  6642. */
  6643. disableCSSInjection: false,
  6644. /**
  6645. * This property holds whether this platform is enabled for the current environment.
  6646. * Currently used by platform.js to select the proper implementation.
  6647. * @private
  6648. */
  6649. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  6650. /**
  6651. * Initializes resources that depend on platform options.
  6652. * @param {HTMLCanvasElement} canvas - The Canvas element.
  6653. * @private
  6654. */
  6655. _ensureLoaded: function(canvas) {
  6656. if (!this.disableCSSInjection) {
  6657. // If the canvas is in a shadow DOM, then the styles must also be inserted
  6658. // into the same shadow DOM.
  6659. // https://github.com/chartjs/Chart.js/issues/5763
  6660. var root = canvas.getRootNode ? canvas.getRootNode() : document;
  6661. var targetNode = root.host ? root : document.head;
  6662. injectCSS(targetNode, stylesheet);
  6663. }
  6664. },
  6665. acquireContext: function(item, config) {
  6666. if (typeof item === 'string') {
  6667. item = document.getElementById(item);
  6668. } else if (item.length) {
  6669. // Support for array based queries (such as jQuery)
  6670. item = item[0];
  6671. }
  6672. if (item && item.canvas) {
  6673. // Support for any object associated to a canvas (including a context2d)
  6674. item = item.canvas;
  6675. }
  6676. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  6677. // method, for example: https://github.com/kkapsner/CanvasBlocker
  6678. // https://github.com/chartjs/Chart.js/issues/2807
  6679. var context = item && item.getContext && item.getContext('2d');
  6680. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  6681. // inside an iframe or when running in a protected environment. We could guess the
  6682. // types from their toString() value but let's keep things flexible and assume it's
  6683. // a sufficient condition if the item has a context2D which has item as `canvas`.
  6684. // https://github.com/chartjs/Chart.js/issues/3887
  6685. // https://github.com/chartjs/Chart.js/issues/4102
  6686. // https://github.com/chartjs/Chart.js/issues/4152
  6687. if (context && context.canvas === item) {
  6688. // Load platform resources on first chart creation, to make it possible to
  6689. // import the library before setting platform options.
  6690. this._ensureLoaded(item);
  6691. initCanvas(item, config);
  6692. return context;
  6693. }
  6694. return null;
  6695. },
  6696. releaseContext: function(context) {
  6697. var canvas = context.canvas;
  6698. if (!canvas[EXPANDO_KEY]) {
  6699. return;
  6700. }
  6701. var initial = canvas[EXPANDO_KEY].initial;
  6702. ['height', 'width'].forEach(function(prop) {
  6703. var value = initial[prop];
  6704. if (helpers$1.isNullOrUndef(value)) {
  6705. canvas.removeAttribute(prop);
  6706. } else {
  6707. canvas.setAttribute(prop, value);
  6708. }
  6709. });
  6710. helpers$1.each(initial.style || {}, function(value, key) {
  6711. canvas.style[key] = value;
  6712. });
  6713. // The canvas render size might have been changed (and thus the state stack discarded),
  6714. // we can't use save() and restore() to restore the initial state. So make sure that at
  6715. // least the canvas context is reset to the default state by setting the canvas width.
  6716. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  6717. // eslint-disable-next-line no-self-assign
  6718. canvas.width = canvas.width;
  6719. delete canvas[EXPANDO_KEY];
  6720. },
  6721. addEventListener: function(chart, type, listener) {
  6722. var canvas = chart.canvas;
  6723. if (type === 'resize') {
  6724. // Note: the resize event is not supported on all browsers.
  6725. addResizeListener(canvas, listener, chart);
  6726. return;
  6727. }
  6728. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  6729. var proxies = expando.proxies || (expando.proxies = {});
  6730. var proxy = proxies[chart.id + '_' + type] = function(event) {
  6731. listener(fromNativeEvent(event, chart));
  6732. };
  6733. addListener(canvas, type, proxy);
  6734. },
  6735. removeEventListener: function(chart, type, listener) {
  6736. var canvas = chart.canvas;
  6737. if (type === 'resize') {
  6738. // Note: the resize event is not supported on all browsers.
  6739. removeResizeListener(canvas);
  6740. return;
  6741. }
  6742. var expando = listener[EXPANDO_KEY] || {};
  6743. var proxies = expando.proxies || {};
  6744. var proxy = proxies[chart.id + '_' + type];
  6745. if (!proxy) {
  6746. return;
  6747. }
  6748. removeListener(canvas, type, proxy);
  6749. }
  6750. };
  6751. // DEPRECATIONS
  6752. /**
  6753. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6754. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6755. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6756. * @function Chart.helpers.addEvent
  6757. * @deprecated since version 2.7.0
  6758. * @todo remove at version 3
  6759. * @private
  6760. */
  6761. helpers$1.addEvent = addListener;
  6762. /**
  6763. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6764. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6765. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6766. * @function Chart.helpers.removeEvent
  6767. * @deprecated since version 2.7.0
  6768. * @todo remove at version 3
  6769. * @private
  6770. */
  6771. helpers$1.removeEvent = removeListener;
  6772. // @TODO Make possible to select another platform at build time.
  6773. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6774. /**
  6775. * @namespace Chart.platform
  6776. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6777. * @since 2.4.0
  6778. */
  6779. var platform = helpers$1.extend({
  6780. /**
  6781. * @since 2.7.0
  6782. */
  6783. initialize: function() {},
  6784. /**
  6785. * Called at chart construction time, returns a context2d instance implementing
  6786. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6787. * @param {*} item - The native item from which to acquire context (platform specific)
  6788. * @param {object} options - The chart options
  6789. * @returns {CanvasRenderingContext2D} context2d instance
  6790. */
  6791. acquireContext: function() {},
  6792. /**
  6793. * Called at chart destruction time, releases any resources associated to the context
  6794. * previously returned by the acquireContext() method.
  6795. * @param {CanvasRenderingContext2D} context - The context2d instance
  6796. * @returns {boolean} true if the method succeeded, else false
  6797. */
  6798. releaseContext: function() {},
  6799. /**
  6800. * Registers the specified listener on the given chart.
  6801. * @param {Chart} chart - Chart from which to listen for event
  6802. * @param {string} type - The ({@link IEvent}) type to listen for
  6803. * @param {function} listener - Receives a notification (an object that implements
  6804. * the {@link IEvent} interface) when an event of the specified type occurs.
  6805. */
  6806. addEventListener: function() {},
  6807. /**
  6808. * Removes the specified listener previously registered with addEventListener.
  6809. * @param {Chart} chart - Chart from which to remove the listener
  6810. * @param {string} type - The ({@link IEvent}) type to remove
  6811. * @param {function} listener - The listener function to remove from the event target.
  6812. */
  6813. removeEventListener: function() {}
  6814. }, implementation);
  6815. core_defaults._set('global', {
  6816. plugins: {}
  6817. });
  6818. /**
  6819. * The plugin service singleton
  6820. * @namespace Chart.plugins
  6821. * @since 2.1.0
  6822. */
  6823. var core_plugins = {
  6824. /**
  6825. * Globally registered plugins.
  6826. * @private
  6827. */
  6828. _plugins: [],
  6829. /**
  6830. * This identifier is used to invalidate the descriptors cache attached to each chart
  6831. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6832. * incremented and descriptors are regenerated during following API calls.
  6833. * @private
  6834. */
  6835. _cacheId: 0,
  6836. /**
  6837. * Registers the given plugin(s) if not already registered.
  6838. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6839. */
  6840. register: function(plugins) {
  6841. var p = this._plugins;
  6842. ([]).concat(plugins).forEach(function(plugin) {
  6843. if (p.indexOf(plugin) === -1) {
  6844. p.push(plugin);
  6845. }
  6846. });
  6847. this._cacheId++;
  6848. },
  6849. /**
  6850. * Unregisters the given plugin(s) only if registered.
  6851. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6852. */
  6853. unregister: function(plugins) {
  6854. var p = this._plugins;
  6855. ([]).concat(plugins).forEach(function(plugin) {
  6856. var idx = p.indexOf(plugin);
  6857. if (idx !== -1) {
  6858. p.splice(idx, 1);
  6859. }
  6860. });
  6861. this._cacheId++;
  6862. },
  6863. /**
  6864. * Remove all registered plugins.
  6865. * @since 2.1.5
  6866. */
  6867. clear: function() {
  6868. this._plugins = [];
  6869. this._cacheId++;
  6870. },
  6871. /**
  6872. * Returns the number of registered plugins?
  6873. * @returns {number}
  6874. * @since 2.1.5
  6875. */
  6876. count: function() {
  6877. return this._plugins.length;
  6878. },
  6879. /**
  6880. * Returns all registered plugin instances.
  6881. * @returns {IPlugin[]} array of plugin objects.
  6882. * @since 2.1.5
  6883. */
  6884. getAll: function() {
  6885. return this._plugins;
  6886. },
  6887. /**
  6888. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6889. * This method immediately returns as soon as a plugin explicitly returns false. The
  6890. * returned value can be used, for instance, to interrupt the current action.
  6891. * @param {Chart} chart - The chart instance for which plugins should be called.
  6892. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6893. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6894. * @returns {boolean} false if any of the plugins return false, else returns true.
  6895. */
  6896. notify: function(chart, hook, args) {
  6897. var descriptors = this.descriptors(chart);
  6898. var ilen = descriptors.length;
  6899. var i, descriptor, plugin, params, method;
  6900. for (i = 0; i < ilen; ++i) {
  6901. descriptor = descriptors[i];
  6902. plugin = descriptor.plugin;
  6903. method = plugin[hook];
  6904. if (typeof method === 'function') {
  6905. params = [chart].concat(args || []);
  6906. params.push(descriptor.options);
  6907. if (method.apply(plugin, params) === false) {
  6908. return false;
  6909. }
  6910. }
  6911. }
  6912. return true;
  6913. },
  6914. /**
  6915. * Returns descriptors of enabled plugins for the given chart.
  6916. * @returns {object[]} [{ plugin, options }]
  6917. * @private
  6918. */
  6919. descriptors: function(chart) {
  6920. var cache = chart.$plugins || (chart.$plugins = {});
  6921. if (cache.id === this._cacheId) {
  6922. return cache.descriptors;
  6923. }
  6924. var plugins = [];
  6925. var descriptors = [];
  6926. var config = (chart && chart.config) || {};
  6927. var options = (config.options && config.options.plugins) || {};
  6928. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  6929. var idx = plugins.indexOf(plugin);
  6930. if (idx !== -1) {
  6931. return;
  6932. }
  6933. var id = plugin.id;
  6934. var opts = options[id];
  6935. if (opts === false) {
  6936. return;
  6937. }
  6938. if (opts === true) {
  6939. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6940. }
  6941. plugins.push(plugin);
  6942. descriptors.push({
  6943. plugin: plugin,
  6944. options: opts || {}
  6945. });
  6946. });
  6947. cache.descriptors = descriptors;
  6948. cache.id = this._cacheId;
  6949. return descriptors;
  6950. },
  6951. /**
  6952. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  6953. * but in some cases, this reference can be changed by the user when updating options.
  6954. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  6955. * @private
  6956. */
  6957. _invalidate: function(chart) {
  6958. delete chart.$plugins;
  6959. }
  6960. };
  6961. var core_scaleService = {
  6962. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  6963. // use the new chart options to grab the correct scale
  6964. constructors: {},
  6965. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  6966. // old browsers
  6967. // Scale config defaults
  6968. defaults: {},
  6969. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  6970. this.constructors[type] = scaleConstructor;
  6971. this.defaults[type] = helpers$1.clone(scaleDefaults);
  6972. },
  6973. getScaleConstructor: function(type) {
  6974. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  6975. },
  6976. getScaleDefaults: function(type) {
  6977. // Return the scale defaults merged with the global settings so that we always use the latest ones
  6978. return this.defaults.hasOwnProperty(type) ? helpers$1.merge(Object.create(null), [core_defaults.scale, this.defaults[type]]) : {};
  6979. },
  6980. updateScaleDefaults: function(type, additions) {
  6981. var me = this;
  6982. if (me.defaults.hasOwnProperty(type)) {
  6983. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  6984. }
  6985. },
  6986. addScalesToLayout: function(chart) {
  6987. // Adds each scale to the chart.boxes array to be sized accordingly
  6988. helpers$1.each(chart.scales, function(scale) {
  6989. // Set ILayoutItem parameters for backwards compatibility
  6990. scale.fullWidth = scale.options.fullWidth;
  6991. scale.position = scale.options.position;
  6992. scale.weight = scale.options.weight;
  6993. core_layouts.addBox(chart, scale);
  6994. });
  6995. }
  6996. };
  6997. var valueOrDefault$8 = helpers$1.valueOrDefault;
  6998. var getRtlHelper = helpers$1.rtl.getRtlAdapter;
  6999. core_defaults._set('global', {
  7000. tooltips: {
  7001. enabled: true,
  7002. custom: null,
  7003. mode: 'nearest',
  7004. position: 'average',
  7005. intersect: true,
  7006. backgroundColor: 'rgba(0,0,0,0.8)',
  7007. titleFontStyle: 'bold',
  7008. titleSpacing: 2,
  7009. titleMarginBottom: 6,
  7010. titleFontColor: '#fff',
  7011. titleAlign: 'left',
  7012. bodySpacing: 2,
  7013. bodyFontColor: '#fff',
  7014. bodyAlign: 'left',
  7015. footerFontStyle: 'bold',
  7016. footerSpacing: 2,
  7017. footerMarginTop: 6,
  7018. footerFontColor: '#fff',
  7019. footerAlign: 'left',
  7020. yPadding: 6,
  7021. xPadding: 6,
  7022. caretPadding: 2,
  7023. caretSize: 5,
  7024. cornerRadius: 6,
  7025. multiKeyBackground: '#fff',
  7026. displayColors: true,
  7027. borderColor: 'rgba(0,0,0,0)',
  7028. borderWidth: 0,
  7029. callbacks: {
  7030. // Args are: (tooltipItems, data)
  7031. beforeTitle: helpers$1.noop,
  7032. title: function(tooltipItems, data) {
  7033. var title = '';
  7034. var labels = data.labels;
  7035. var labelCount = labels ? labels.length : 0;
  7036. if (tooltipItems.length > 0) {
  7037. var item = tooltipItems[0];
  7038. if (item.label) {
  7039. title = item.label;
  7040. } else if (item.xLabel) {
  7041. title = item.xLabel;
  7042. } else if (labelCount > 0 && item.index < labelCount) {
  7043. title = labels[item.index];
  7044. }
  7045. }
  7046. return title;
  7047. },
  7048. afterTitle: helpers$1.noop,
  7049. // Args are: (tooltipItems, data)
  7050. beforeBody: helpers$1.noop,
  7051. // Args are: (tooltipItem, data)
  7052. beforeLabel: helpers$1.noop,
  7053. label: function(tooltipItem, data) {
  7054. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  7055. if (label) {
  7056. label += ': ';
  7057. }
  7058. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  7059. label += tooltipItem.value;
  7060. } else {
  7061. label += tooltipItem.yLabel;
  7062. }
  7063. return label;
  7064. },
  7065. labelColor: function(tooltipItem, chart) {
  7066. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  7067. var activeElement = meta.data[tooltipItem.index];
  7068. var view = activeElement._view;
  7069. return {
  7070. borderColor: view.borderColor,
  7071. backgroundColor: view.backgroundColor
  7072. };
  7073. },
  7074. labelTextColor: function() {
  7075. return this._options.bodyFontColor;
  7076. },
  7077. afterLabel: helpers$1.noop,
  7078. // Args are: (tooltipItems, data)
  7079. afterBody: helpers$1.noop,
  7080. // Args are: (tooltipItems, data)
  7081. beforeFooter: helpers$1.noop,
  7082. footer: helpers$1.noop,
  7083. afterFooter: helpers$1.noop
  7084. }
  7085. }
  7086. });
  7087. var positioners = {
  7088. /**
  7089. * Average mode places the tooltip at the average position of the elements shown
  7090. * @function Chart.Tooltip.positioners.average
  7091. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  7092. * @returns {object} tooltip position
  7093. */
  7094. average: function(elements) {
  7095. if (!elements.length) {
  7096. return false;
  7097. }
  7098. var i, len;
  7099. var x = 0;
  7100. var y = 0;
  7101. var count = 0;
  7102. for (i = 0, len = elements.length; i < len; ++i) {
  7103. var el = elements[i];
  7104. if (el && el.hasValue()) {
  7105. var pos = el.tooltipPosition();
  7106. x += pos.x;
  7107. y += pos.y;
  7108. ++count;
  7109. }
  7110. }
  7111. return {
  7112. x: x / count,
  7113. y: y / count
  7114. };
  7115. },
  7116. /**
  7117. * Gets the tooltip position nearest of the item nearest to the event position
  7118. * @function Chart.Tooltip.positioners.nearest
  7119. * @param elements {Chart.Element[]} the tooltip elements
  7120. * @param eventPosition {object} the position of the event in canvas coordinates
  7121. * @returns {object} the tooltip position
  7122. */
  7123. nearest: function(elements, eventPosition) {
  7124. var x = eventPosition.x;
  7125. var y = eventPosition.y;
  7126. var minDistance = Number.POSITIVE_INFINITY;
  7127. var i, len, nearestElement;
  7128. for (i = 0, len = elements.length; i < len; ++i) {
  7129. var el = elements[i];
  7130. if (el && el.hasValue()) {
  7131. var center = el.getCenterPoint();
  7132. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  7133. if (d < minDistance) {
  7134. minDistance = d;
  7135. nearestElement = el;
  7136. }
  7137. }
  7138. }
  7139. if (nearestElement) {
  7140. var tp = nearestElement.tooltipPosition();
  7141. x = tp.x;
  7142. y = tp.y;
  7143. }
  7144. return {
  7145. x: x,
  7146. y: y
  7147. };
  7148. }
  7149. };
  7150. // Helper to push or concat based on if the 2nd parameter is an array or not
  7151. function pushOrConcat(base, toPush) {
  7152. if (toPush) {
  7153. if (helpers$1.isArray(toPush)) {
  7154. // base = base.concat(toPush);
  7155. Array.prototype.push.apply(base, toPush);
  7156. } else {
  7157. base.push(toPush);
  7158. }
  7159. }
  7160. return base;
  7161. }
  7162. /**
  7163. * Returns array of strings split by newline
  7164. * @param {string} value - The value to split by newline.
  7165. * @returns {string[]} value if newline present - Returned from String split() method
  7166. * @function
  7167. */
  7168. function splitNewlines(str) {
  7169. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  7170. return str.split('\n');
  7171. }
  7172. return str;
  7173. }
  7174. /**
  7175. * Private helper to create a tooltip item model
  7176. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  7177. * @return new tooltip item
  7178. */
  7179. function createTooltipItem(element) {
  7180. var xScale = element._xScale;
  7181. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  7182. var index = element._index;
  7183. var datasetIndex = element._datasetIndex;
  7184. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  7185. var indexScale = controller._getIndexScale();
  7186. var valueScale = controller._getValueScale();
  7187. return {
  7188. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  7189. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  7190. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  7191. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  7192. index: index,
  7193. datasetIndex: datasetIndex,
  7194. x: element._model.x,
  7195. y: element._model.y
  7196. };
  7197. }
  7198. /**
  7199. * Helper to get the reset model for the tooltip
  7200. * @param tooltipOpts {object} the tooltip options
  7201. */
  7202. function getBaseModel(tooltipOpts) {
  7203. var globalDefaults = core_defaults.global;
  7204. return {
  7205. // Positioning
  7206. xPadding: tooltipOpts.xPadding,
  7207. yPadding: tooltipOpts.yPadding,
  7208. xAlign: tooltipOpts.xAlign,
  7209. yAlign: tooltipOpts.yAlign,
  7210. // Drawing direction and text direction
  7211. rtl: tooltipOpts.rtl,
  7212. textDirection: tooltipOpts.textDirection,
  7213. // Body
  7214. bodyFontColor: tooltipOpts.bodyFontColor,
  7215. _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  7216. _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  7217. _bodyAlign: tooltipOpts.bodyAlign,
  7218. bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  7219. bodySpacing: tooltipOpts.bodySpacing,
  7220. // Title
  7221. titleFontColor: tooltipOpts.titleFontColor,
  7222. _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  7223. _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  7224. titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  7225. _titleAlign: tooltipOpts.titleAlign,
  7226. titleSpacing: tooltipOpts.titleSpacing,
  7227. titleMarginBottom: tooltipOpts.titleMarginBottom,
  7228. // Footer
  7229. footerFontColor: tooltipOpts.footerFontColor,
  7230. _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  7231. _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  7232. footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  7233. _footerAlign: tooltipOpts.footerAlign,
  7234. footerSpacing: tooltipOpts.footerSpacing,
  7235. footerMarginTop: tooltipOpts.footerMarginTop,
  7236. // Appearance
  7237. caretSize: tooltipOpts.caretSize,
  7238. cornerRadius: tooltipOpts.cornerRadius,
  7239. backgroundColor: tooltipOpts.backgroundColor,
  7240. opacity: 0,
  7241. legendColorBackground: tooltipOpts.multiKeyBackground,
  7242. displayColors: tooltipOpts.displayColors,
  7243. borderColor: tooltipOpts.borderColor,
  7244. borderWidth: tooltipOpts.borderWidth
  7245. };
  7246. }
  7247. /**
  7248. * Get the size of the tooltip
  7249. */
  7250. function getTooltipSize(tooltip, model) {
  7251. var ctx = tooltip._chart.ctx;
  7252. var height = model.yPadding * 2; // Tooltip Padding
  7253. var width = 0;
  7254. // Count of all lines in the body
  7255. var body = model.body;
  7256. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  7257. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  7258. }, 0);
  7259. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  7260. var titleLineCount = model.title.length;
  7261. var footerLineCount = model.footer.length;
  7262. var titleFontSize = model.titleFontSize;
  7263. var bodyFontSize = model.bodyFontSize;
  7264. var footerFontSize = model.footerFontSize;
  7265. height += titleLineCount * titleFontSize; // Title Lines
  7266. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  7267. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  7268. height += combinedBodyLength * bodyFontSize; // Body Lines
  7269. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  7270. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  7271. height += footerLineCount * (footerFontSize); // Footer Lines
  7272. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  7273. // Title width
  7274. var widthPadding = 0;
  7275. var maxLineWidth = function(line) {
  7276. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  7277. };
  7278. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  7279. helpers$1.each(model.title, maxLineWidth);
  7280. // Body width
  7281. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  7282. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  7283. // Body lines may include some extra width due to the color box
  7284. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  7285. helpers$1.each(body, function(bodyItem) {
  7286. helpers$1.each(bodyItem.before, maxLineWidth);
  7287. helpers$1.each(bodyItem.lines, maxLineWidth);
  7288. helpers$1.each(bodyItem.after, maxLineWidth);
  7289. });
  7290. // Reset back to 0
  7291. widthPadding = 0;
  7292. // Footer width
  7293. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  7294. helpers$1.each(model.footer, maxLineWidth);
  7295. // Add padding
  7296. width += 2 * model.xPadding;
  7297. return {
  7298. width: width,
  7299. height: height
  7300. };
  7301. }
  7302. /**
  7303. * Helper to get the alignment of a tooltip given the size
  7304. */
  7305. function determineAlignment(tooltip, size) {
  7306. var model = tooltip._model;
  7307. var chart = tooltip._chart;
  7308. var chartArea = tooltip._chart.chartArea;
  7309. var xAlign = 'center';
  7310. var yAlign = 'center';
  7311. if (model.y < size.height) {
  7312. yAlign = 'top';
  7313. } else if (model.y > (chart.height - size.height)) {
  7314. yAlign = 'bottom';
  7315. }
  7316. var lf, rf; // functions to determine left, right alignment
  7317. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  7318. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  7319. var midX = (chartArea.left + chartArea.right) / 2;
  7320. var midY = (chartArea.top + chartArea.bottom) / 2;
  7321. if (yAlign === 'center') {
  7322. lf = function(x) {
  7323. return x <= midX;
  7324. };
  7325. rf = function(x) {
  7326. return x > midX;
  7327. };
  7328. } else {
  7329. lf = function(x) {
  7330. return x <= (size.width / 2);
  7331. };
  7332. rf = function(x) {
  7333. return x >= (chart.width - (size.width / 2));
  7334. };
  7335. }
  7336. olf = function(x) {
  7337. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  7338. };
  7339. orf = function(x) {
  7340. return x - size.width - model.caretSize - model.caretPadding < 0;
  7341. };
  7342. yf = function(y) {
  7343. return y <= midY ? 'top' : 'bottom';
  7344. };
  7345. if (lf(model.x)) {
  7346. xAlign = 'left';
  7347. // Is tooltip too wide and goes over the right side of the chart.?
  7348. if (olf(model.x)) {
  7349. xAlign = 'center';
  7350. yAlign = yf(model.y);
  7351. }
  7352. } else if (rf(model.x)) {
  7353. xAlign = 'right';
  7354. // Is tooltip too wide and goes outside left edge of canvas?
  7355. if (orf(model.x)) {
  7356. xAlign = 'center';
  7357. yAlign = yf(model.y);
  7358. }
  7359. }
  7360. var opts = tooltip._options;
  7361. return {
  7362. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  7363. yAlign: opts.yAlign ? opts.yAlign : yAlign
  7364. };
  7365. }
  7366. /**
  7367. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  7368. */
  7369. function getBackgroundPoint(vm, size, alignment, chart) {
  7370. // Background Position
  7371. var x = vm.x;
  7372. var y = vm.y;
  7373. var caretSize = vm.caretSize;
  7374. var caretPadding = vm.caretPadding;
  7375. var cornerRadius = vm.cornerRadius;
  7376. var xAlign = alignment.xAlign;
  7377. var yAlign = alignment.yAlign;
  7378. var paddingAndSize = caretSize + caretPadding;
  7379. var radiusAndPadding = cornerRadius + caretPadding;
  7380. if (xAlign === 'right') {
  7381. x -= size.width;
  7382. } else if (xAlign === 'center') {
  7383. x -= (size.width / 2);
  7384. if (x + size.width > chart.width) {
  7385. x = chart.width - size.width;
  7386. }
  7387. if (x < 0) {
  7388. x = 0;
  7389. }
  7390. }
  7391. if (yAlign === 'top') {
  7392. y += paddingAndSize;
  7393. } else if (yAlign === 'bottom') {
  7394. y -= size.height + paddingAndSize;
  7395. } else {
  7396. y -= (size.height / 2);
  7397. }
  7398. if (yAlign === 'center') {
  7399. if (xAlign === 'left') {
  7400. x += paddingAndSize;
  7401. } else if (xAlign === 'right') {
  7402. x -= paddingAndSize;
  7403. }
  7404. } else if (xAlign === 'left') {
  7405. x -= radiusAndPadding;
  7406. } else if (xAlign === 'right') {
  7407. x += radiusAndPadding;
  7408. }
  7409. return {
  7410. x: x,
  7411. y: y
  7412. };
  7413. }
  7414. function getAlignedX(vm, align) {
  7415. return align === 'center'
  7416. ? vm.x + vm.width / 2
  7417. : align === 'right'
  7418. ? vm.x + vm.width - vm.xPadding
  7419. : vm.x + vm.xPadding;
  7420. }
  7421. /**
  7422. * Helper to build before and after body lines
  7423. */
  7424. function getBeforeAfterBodyLines(callback) {
  7425. return pushOrConcat([], splitNewlines(callback));
  7426. }
  7427. var exports$4 = core_element.extend({
  7428. initialize: function() {
  7429. this._model = getBaseModel(this._options);
  7430. this._lastActive = [];
  7431. },
  7432. // Get the title
  7433. // Args are: (tooltipItem, data)
  7434. getTitle: function() {
  7435. var me = this;
  7436. var opts = me._options;
  7437. var callbacks = opts.callbacks;
  7438. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  7439. var title = callbacks.title.apply(me, arguments);
  7440. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  7441. var lines = [];
  7442. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  7443. lines = pushOrConcat(lines, splitNewlines(title));
  7444. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  7445. return lines;
  7446. },
  7447. // Args are: (tooltipItem, data)
  7448. getBeforeBody: function() {
  7449. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  7450. },
  7451. // Args are: (tooltipItem, data)
  7452. getBody: function(tooltipItems, data) {
  7453. var me = this;
  7454. var callbacks = me._options.callbacks;
  7455. var bodyItems = [];
  7456. helpers$1.each(tooltipItems, function(tooltipItem) {
  7457. var bodyItem = {
  7458. before: [],
  7459. lines: [],
  7460. after: []
  7461. };
  7462. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  7463. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  7464. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  7465. bodyItems.push(bodyItem);
  7466. });
  7467. return bodyItems;
  7468. },
  7469. // Args are: (tooltipItem, data)
  7470. getAfterBody: function() {
  7471. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  7472. },
  7473. // Get the footer and beforeFooter and afterFooter lines
  7474. // Args are: (tooltipItem, data)
  7475. getFooter: function() {
  7476. var me = this;
  7477. var callbacks = me._options.callbacks;
  7478. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  7479. var footer = callbacks.footer.apply(me, arguments);
  7480. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  7481. var lines = [];
  7482. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  7483. lines = pushOrConcat(lines, splitNewlines(footer));
  7484. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  7485. return lines;
  7486. },
  7487. update: function(changed) {
  7488. var me = this;
  7489. var opts = me._options;
  7490. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  7491. // 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
  7492. // which breaks any animations.
  7493. var existingModel = me._model;
  7494. var model = me._model = getBaseModel(opts);
  7495. var active = me._active;
  7496. var data = me._data;
  7497. // In the case where active.length === 0 we need to keep these at existing values for good animations
  7498. var alignment = {
  7499. xAlign: existingModel.xAlign,
  7500. yAlign: existingModel.yAlign
  7501. };
  7502. var backgroundPoint = {
  7503. x: existingModel.x,
  7504. y: existingModel.y
  7505. };
  7506. var tooltipSize = {
  7507. width: existingModel.width,
  7508. height: existingModel.height
  7509. };
  7510. var tooltipPosition = {
  7511. x: existingModel.caretX,
  7512. y: existingModel.caretY
  7513. };
  7514. var i, len;
  7515. if (active.length) {
  7516. model.opacity = 1;
  7517. var labelColors = [];
  7518. var labelTextColors = [];
  7519. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  7520. var tooltipItems = [];
  7521. for (i = 0, len = active.length; i < len; ++i) {
  7522. tooltipItems.push(createTooltipItem(active[i]));
  7523. }
  7524. // If the user provided a filter function, use it to modify the tooltip items
  7525. if (opts.filter) {
  7526. tooltipItems = tooltipItems.filter(function(a) {
  7527. return opts.filter(a, data);
  7528. });
  7529. }
  7530. // If the user provided a sorting function, use it to modify the tooltip items
  7531. if (opts.itemSort) {
  7532. tooltipItems = tooltipItems.sort(function(a, b) {
  7533. return opts.itemSort(a, b, data);
  7534. });
  7535. }
  7536. // Determine colors for boxes
  7537. helpers$1.each(tooltipItems, function(tooltipItem) {
  7538. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  7539. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  7540. });
  7541. // Build the Text Lines
  7542. model.title = me.getTitle(tooltipItems, data);
  7543. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  7544. model.body = me.getBody(tooltipItems, data);
  7545. model.afterBody = me.getAfterBody(tooltipItems, data);
  7546. model.footer = me.getFooter(tooltipItems, data);
  7547. // Initial positioning and colors
  7548. model.x = tooltipPosition.x;
  7549. model.y = tooltipPosition.y;
  7550. model.caretPadding = opts.caretPadding;
  7551. model.labelColors = labelColors;
  7552. model.labelTextColors = labelTextColors;
  7553. // data points
  7554. model.dataPoints = tooltipItems;
  7555. // We need to determine alignment of the tooltip
  7556. tooltipSize = getTooltipSize(this, model);
  7557. alignment = determineAlignment(this, tooltipSize);
  7558. // Final Size and Position
  7559. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  7560. } else {
  7561. model.opacity = 0;
  7562. }
  7563. model.xAlign = alignment.xAlign;
  7564. model.yAlign = alignment.yAlign;
  7565. model.x = backgroundPoint.x;
  7566. model.y = backgroundPoint.y;
  7567. model.width = tooltipSize.width;
  7568. model.height = tooltipSize.height;
  7569. // Point where the caret on the tooltip points to
  7570. model.caretX = tooltipPosition.x;
  7571. model.caretY = tooltipPosition.y;
  7572. me._model = model;
  7573. if (changed && opts.custom) {
  7574. opts.custom.call(me, model);
  7575. }
  7576. return me;
  7577. },
  7578. drawCaret: function(tooltipPoint, size) {
  7579. var ctx = this._chart.ctx;
  7580. var vm = this._view;
  7581. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  7582. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  7583. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  7584. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  7585. },
  7586. getCaretPosition: function(tooltipPoint, size, vm) {
  7587. var x1, x2, x3, y1, y2, y3;
  7588. var caretSize = vm.caretSize;
  7589. var cornerRadius = vm.cornerRadius;
  7590. var xAlign = vm.xAlign;
  7591. var yAlign = vm.yAlign;
  7592. var ptX = tooltipPoint.x;
  7593. var ptY = tooltipPoint.y;
  7594. var width = size.width;
  7595. var height = size.height;
  7596. if (yAlign === 'center') {
  7597. y2 = ptY + (height / 2);
  7598. if (xAlign === 'left') {
  7599. x1 = ptX;
  7600. x2 = x1 - caretSize;
  7601. x3 = x1;
  7602. y1 = y2 + caretSize;
  7603. y3 = y2 - caretSize;
  7604. } else {
  7605. x1 = ptX + width;
  7606. x2 = x1 + caretSize;
  7607. x3 = x1;
  7608. y1 = y2 - caretSize;
  7609. y3 = y2 + caretSize;
  7610. }
  7611. } else {
  7612. if (xAlign === 'left') {
  7613. x2 = ptX + cornerRadius + (caretSize);
  7614. x1 = x2 - caretSize;
  7615. x3 = x2 + caretSize;
  7616. } else if (xAlign === 'right') {
  7617. x2 = ptX + width - cornerRadius - caretSize;
  7618. x1 = x2 - caretSize;
  7619. x3 = x2 + caretSize;
  7620. } else {
  7621. x2 = vm.caretX;
  7622. x1 = x2 - caretSize;
  7623. x3 = x2 + caretSize;
  7624. }
  7625. if (yAlign === 'top') {
  7626. y1 = ptY;
  7627. y2 = y1 - caretSize;
  7628. y3 = y1;
  7629. } else {
  7630. y1 = ptY + height;
  7631. y2 = y1 + caretSize;
  7632. y3 = y1;
  7633. // invert drawing order
  7634. var tmp = x3;
  7635. x3 = x1;
  7636. x1 = tmp;
  7637. }
  7638. }
  7639. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  7640. },
  7641. drawTitle: function(pt, vm, ctx) {
  7642. var title = vm.title;
  7643. var length = title.length;
  7644. var titleFontSize, titleSpacing, i;
  7645. if (length) {
  7646. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7647. pt.x = getAlignedX(vm, vm._titleAlign);
  7648. ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);
  7649. ctx.textBaseline = 'middle';
  7650. titleFontSize = vm.titleFontSize;
  7651. titleSpacing = vm.titleSpacing;
  7652. ctx.fillStyle = vm.titleFontColor;
  7653. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  7654. for (i = 0; i < length; ++i) {
  7655. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);
  7656. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  7657. if (i + 1 === length) {
  7658. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  7659. }
  7660. }
  7661. }
  7662. },
  7663. drawBody: function(pt, vm, ctx) {
  7664. var bodyFontSize = vm.bodyFontSize;
  7665. var bodySpacing = vm.bodySpacing;
  7666. var bodyAlign = vm._bodyAlign;
  7667. var body = vm.body;
  7668. var drawColorBoxes = vm.displayColors;
  7669. var xLinePadding = 0;
  7670. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  7671. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7672. var fillLineOfText = function(line) {
  7673. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
  7674. pt.y += bodyFontSize + bodySpacing;
  7675. };
  7676. var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;
  7677. var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  7678. ctx.textAlign = bodyAlign;
  7679. ctx.textBaseline = 'middle';
  7680. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  7681. pt.x = getAlignedX(vm, bodyAlignForCalculation);
  7682. // Before body lines
  7683. ctx.fillStyle = vm.bodyFontColor;
  7684. helpers$1.each(vm.beforeBody, fillLineOfText);
  7685. xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'
  7686. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  7687. : 0;
  7688. // Draw body lines now
  7689. for (i = 0, ilen = body.length; i < ilen; ++i) {
  7690. bodyItem = body[i];
  7691. textColor = vm.labelTextColors[i];
  7692. labelColors = vm.labelColors[i];
  7693. ctx.fillStyle = textColor;
  7694. helpers$1.each(bodyItem.before, fillLineOfText);
  7695. lines = bodyItem.lines;
  7696. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  7697. // Draw Legend-like boxes if needed
  7698. if (drawColorBoxes) {
  7699. var rtlColorX = rtlHelper.x(colorX);
  7700. // Fill a white rect so that colours merge nicely if the opacity is < 1
  7701. ctx.fillStyle = vm.legendColorBackground;
  7702. ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7703. // Border
  7704. ctx.lineWidth = 1;
  7705. ctx.strokeStyle = labelColors.borderColor;
  7706. ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7707. // Inner square
  7708. ctx.fillStyle = labelColors.backgroundColor;
  7709. ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  7710. ctx.fillStyle = textColor;
  7711. }
  7712. fillLineOfText(lines[j]);
  7713. }
  7714. helpers$1.each(bodyItem.after, fillLineOfText);
  7715. }
  7716. // Reset back to 0 for after body
  7717. xLinePadding = 0;
  7718. // After body lines
  7719. helpers$1.each(vm.afterBody, fillLineOfText);
  7720. pt.y -= bodySpacing; // Remove last body spacing
  7721. },
  7722. drawFooter: function(pt, vm, ctx) {
  7723. var footer = vm.footer;
  7724. var length = footer.length;
  7725. var footerFontSize, i;
  7726. if (length) {
  7727. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7728. pt.x = getAlignedX(vm, vm._footerAlign);
  7729. pt.y += vm.footerMarginTop;
  7730. ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);
  7731. ctx.textBaseline = 'middle';
  7732. footerFontSize = vm.footerFontSize;
  7733. ctx.fillStyle = vm.footerFontColor;
  7734. ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  7735. for (i = 0; i < length; ++i) {
  7736. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);
  7737. pt.y += footerFontSize + vm.footerSpacing;
  7738. }
  7739. }
  7740. },
  7741. drawBackground: function(pt, vm, ctx, tooltipSize) {
  7742. ctx.fillStyle = vm.backgroundColor;
  7743. ctx.strokeStyle = vm.borderColor;
  7744. ctx.lineWidth = vm.borderWidth;
  7745. var xAlign = vm.xAlign;
  7746. var yAlign = vm.yAlign;
  7747. var x = pt.x;
  7748. var y = pt.y;
  7749. var width = tooltipSize.width;
  7750. var height = tooltipSize.height;
  7751. var radius = vm.cornerRadius;
  7752. ctx.beginPath();
  7753. ctx.moveTo(x + radius, y);
  7754. if (yAlign === 'top') {
  7755. this.drawCaret(pt, tooltipSize);
  7756. }
  7757. ctx.lineTo(x + width - radius, y);
  7758. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7759. if (yAlign === 'center' && xAlign === 'right') {
  7760. this.drawCaret(pt, tooltipSize);
  7761. }
  7762. ctx.lineTo(x + width, y + height - radius);
  7763. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7764. if (yAlign === 'bottom') {
  7765. this.drawCaret(pt, tooltipSize);
  7766. }
  7767. ctx.lineTo(x + radius, y + height);
  7768. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7769. if (yAlign === 'center' && xAlign === 'left') {
  7770. this.drawCaret(pt, tooltipSize);
  7771. }
  7772. ctx.lineTo(x, y + radius);
  7773. ctx.quadraticCurveTo(x, y, x + radius, y);
  7774. ctx.closePath();
  7775. ctx.fill();
  7776. if (vm.borderWidth > 0) {
  7777. ctx.stroke();
  7778. }
  7779. },
  7780. draw: function() {
  7781. var ctx = this._chart.ctx;
  7782. var vm = this._view;
  7783. if (vm.opacity === 0) {
  7784. return;
  7785. }
  7786. var tooltipSize = {
  7787. width: vm.width,
  7788. height: vm.height
  7789. };
  7790. var pt = {
  7791. x: vm.x,
  7792. y: vm.y
  7793. };
  7794. // IE11/Edge does not like very small opacities, so snap to 0
  7795. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7796. // Truthy/falsey value for empty tooltip
  7797. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7798. if (this._options.enabled && hasTooltipContent) {
  7799. ctx.save();
  7800. ctx.globalAlpha = opacity;
  7801. // Draw Background
  7802. this.drawBackground(pt, vm, ctx, tooltipSize);
  7803. // Draw Title, Body, and Footer
  7804. pt.y += vm.yPadding;
  7805. helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);
  7806. // Titles
  7807. this.drawTitle(pt, vm, ctx);
  7808. // Body
  7809. this.drawBody(pt, vm, ctx);
  7810. // Footer
  7811. this.drawFooter(pt, vm, ctx);
  7812. helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);
  7813. ctx.restore();
  7814. }
  7815. },
  7816. /**
  7817. * Handle an event
  7818. * @private
  7819. * @param {IEvent} event - The event to handle
  7820. * @returns {boolean} true if the tooltip changed
  7821. */
  7822. handleEvent: function(e) {
  7823. var me = this;
  7824. var options = me._options;
  7825. var changed = false;
  7826. me._lastActive = me._lastActive || [];
  7827. // Find Active Elements for tooltips
  7828. if (e.type === 'mouseout') {
  7829. me._active = [];
  7830. } else {
  7831. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7832. if (options.reverse) {
  7833. me._active.reverse();
  7834. }
  7835. }
  7836. // Remember Last Actives
  7837. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7838. // Only handle target event on tooltip change
  7839. if (changed) {
  7840. me._lastActive = me._active;
  7841. if (options.enabled || options.custom) {
  7842. me._eventPosition = {
  7843. x: e.x,
  7844. y: e.y
  7845. };
  7846. me.update(true);
  7847. me.pivot();
  7848. }
  7849. }
  7850. return changed;
  7851. }
  7852. });
  7853. /**
  7854. * @namespace Chart.Tooltip.positioners
  7855. */
  7856. var positioners_1 = positioners;
  7857. var core_tooltip = exports$4;
  7858. core_tooltip.positioners = positioners_1;
  7859. var valueOrDefault$9 = helpers$1.valueOrDefault;
  7860. core_defaults._set('global', {
  7861. elements: {},
  7862. events: [
  7863. 'mousemove',
  7864. 'mouseout',
  7865. 'click',
  7866. 'touchstart',
  7867. 'touchmove'
  7868. ],
  7869. hover: {
  7870. onHover: null,
  7871. mode: 'nearest',
  7872. intersect: true,
  7873. animationDuration: 400
  7874. },
  7875. onClick: null,
  7876. maintainAspectRatio: true,
  7877. responsive: true,
  7878. responsiveAnimationDuration: 0
  7879. });
  7880. /**
  7881. * Recursively merge the given config objects representing the `scales` option
  7882. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7883. * returns a deep copy of the result, thus doesn't alter inputs.
  7884. */
  7885. function mergeScaleConfig(/* config objects ... */) {
  7886. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  7887. merger: function(key, target, source, options) {
  7888. if (key === 'xAxes' || key === 'yAxes') {
  7889. var slen = source[key].length;
  7890. var i, type, scale;
  7891. if (!target[key]) {
  7892. target[key] = [];
  7893. }
  7894. for (i = 0; i < slen; ++i) {
  7895. scale = source[key][i];
  7896. type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7897. if (i >= target[key].length) {
  7898. target[key].push({});
  7899. }
  7900. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7901. // new/untyped scale or type changed: let's apply the new defaults
  7902. // then merge source scale to correctly overwrite the defaults.
  7903. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7904. } else {
  7905. // scales type are the same
  7906. helpers$1.merge(target[key][i], scale);
  7907. }
  7908. }
  7909. } else {
  7910. helpers$1._merger(key, target, source, options);
  7911. }
  7912. }
  7913. });
  7914. }
  7915. /**
  7916. * Recursively merge the given config objects as the root options by handling
  7917. * default scale options for the `scales` and `scale` properties, then returns
  7918. * a deep copy of the result, thus doesn't alter inputs.
  7919. */
  7920. function mergeConfig(/* config objects ... */) {
  7921. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  7922. merger: function(key, target, source, options) {
  7923. var tval = target[key] || Object.create(null);
  7924. var sval = source[key];
  7925. if (key === 'scales') {
  7926. // scale config merging is complex. Add our own function here for that
  7927. target[key] = mergeScaleConfig(tval, sval);
  7928. } else if (key === 'scale') {
  7929. // used in polar area & radar charts since there is only one scale
  7930. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7931. } else {
  7932. helpers$1._merger(key, target, source, options);
  7933. }
  7934. }
  7935. });
  7936. }
  7937. function initConfig(config) {
  7938. config = config || Object.create(null);
  7939. // Do NOT use mergeConfig for the data object because this method merges arrays
  7940. // and so would change references to labels and datasets, preventing data updates.
  7941. var data = config.data = config.data || {};
  7942. data.datasets = data.datasets || [];
  7943. data.labels = data.labels || [];
  7944. config.options = mergeConfig(
  7945. core_defaults.global,
  7946. core_defaults[config.type],
  7947. config.options || {});
  7948. return config;
  7949. }
  7950. function updateConfig(chart) {
  7951. var newOptions = chart.options;
  7952. helpers$1.each(chart.scales, function(scale) {
  7953. core_layouts.removeBox(chart, scale);
  7954. });
  7955. newOptions = mergeConfig(
  7956. core_defaults.global,
  7957. core_defaults[chart.config.type],
  7958. newOptions);
  7959. chart.options = chart.config.options = newOptions;
  7960. chart.ensureScalesHaveIDs();
  7961. chart.buildOrUpdateScales();
  7962. // Tooltip
  7963. chart.tooltip._options = newOptions.tooltips;
  7964. chart.tooltip.initialize();
  7965. }
  7966. function nextAvailableScaleId(axesOpts, prefix, index) {
  7967. var id;
  7968. var hasId = function(obj) {
  7969. return obj.id === id;
  7970. };
  7971. do {
  7972. id = prefix + index++;
  7973. } while (helpers$1.findIndex(axesOpts, hasId) >= 0);
  7974. return id;
  7975. }
  7976. function positionIsHorizontal(position) {
  7977. return position === 'top' || position === 'bottom';
  7978. }
  7979. function compare2Level(l1, l2) {
  7980. return function(a, b) {
  7981. return a[l1] === b[l1]
  7982. ? a[l2] - b[l2]
  7983. : a[l1] - b[l1];
  7984. };
  7985. }
  7986. var Chart = function(item, config) {
  7987. this.construct(item, config);
  7988. return this;
  7989. };
  7990. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  7991. /**
  7992. * @private
  7993. */
  7994. construct: function(item, config) {
  7995. var me = this;
  7996. config = initConfig(config);
  7997. var context = platform.acquireContext(item, config);
  7998. var canvas = context && context.canvas;
  7999. var height = canvas && canvas.height;
  8000. var width = canvas && canvas.width;
  8001. me.id = helpers$1.uid();
  8002. me.ctx = context;
  8003. me.canvas = canvas;
  8004. me.config = config;
  8005. me.width = width;
  8006. me.height = height;
  8007. me.aspectRatio = height ? width / height : null;
  8008. me.options = config.options;
  8009. me._bufferedRender = false;
  8010. me._layers = [];
  8011. /**
  8012. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  8013. * the "instance" still need to be defined since it might be called from plugins.
  8014. * @prop Chart#chart
  8015. * @deprecated since version 2.6.0
  8016. * @todo remove at version 3
  8017. * @private
  8018. */
  8019. me.chart = me;
  8020. me.controller = me; // chart.chart.controller #inception
  8021. // Add the chart instance to the global namespace
  8022. Chart.instances[me.id] = me;
  8023. // Define alias to the config data: `chart.data === chart.config.data`
  8024. Object.defineProperty(me, 'data', {
  8025. get: function() {
  8026. return me.config.data;
  8027. },
  8028. set: function(value) {
  8029. me.config.data = value;
  8030. }
  8031. });
  8032. if (!context || !canvas) {
  8033. // The given item is not a compatible context2d element, let's return before finalizing
  8034. // the chart initialization but after setting basic chart / controller properties that
  8035. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  8036. // https://github.com/chartjs/Chart.js/issues/2807
  8037. console.error("Failed to create chart: can't acquire context from the given item");
  8038. return;
  8039. }
  8040. me.initialize();
  8041. me.update();
  8042. },
  8043. /**
  8044. * @private
  8045. */
  8046. initialize: function() {
  8047. var me = this;
  8048. // Before init plugin notification
  8049. core_plugins.notify(me, 'beforeInit');
  8050. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  8051. me.bindEvents();
  8052. if (me.options.responsive) {
  8053. // Initial resize before chart draws (must be silent to preserve initial animations).
  8054. me.resize(true);
  8055. }
  8056. me.initToolTip();
  8057. // After init plugin notification
  8058. core_plugins.notify(me, 'afterInit');
  8059. return me;
  8060. },
  8061. clear: function() {
  8062. helpers$1.canvas.clear(this);
  8063. return this;
  8064. },
  8065. stop: function() {
  8066. // Stops any current animation loop occurring
  8067. core_animations.cancelAnimation(this);
  8068. return this;
  8069. },
  8070. resize: function(silent) {
  8071. var me = this;
  8072. var options = me.options;
  8073. var canvas = me.canvas;
  8074. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  8075. // the canvas render width and height will be casted to integers so make sure that
  8076. // the canvas display style uses the same integer values to avoid blurring effect.
  8077. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  8078. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  8079. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  8080. if (me.width === newWidth && me.height === newHeight) {
  8081. return;
  8082. }
  8083. canvas.width = me.width = newWidth;
  8084. canvas.height = me.height = newHeight;
  8085. canvas.style.width = newWidth + 'px';
  8086. canvas.style.height = newHeight + 'px';
  8087. helpers$1.retinaScale(me, options.devicePixelRatio);
  8088. if (!silent) {
  8089. // Notify any plugins about the resize
  8090. var newSize = {width: newWidth, height: newHeight};
  8091. core_plugins.notify(me, 'resize', [newSize]);
  8092. // Notify of resize
  8093. if (options.onResize) {
  8094. options.onResize(me, newSize);
  8095. }
  8096. me.stop();
  8097. me.update({
  8098. duration: options.responsiveAnimationDuration
  8099. });
  8100. }
  8101. },
  8102. ensureScalesHaveIDs: function() {
  8103. var options = this.options;
  8104. var scalesOptions = options.scales || {};
  8105. var scaleOptions = options.scale;
  8106. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  8107. if (!xAxisOptions.id) {
  8108. xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);
  8109. }
  8110. });
  8111. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  8112. if (!yAxisOptions.id) {
  8113. yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);
  8114. }
  8115. });
  8116. if (scaleOptions) {
  8117. scaleOptions.id = scaleOptions.id || 'scale';
  8118. }
  8119. },
  8120. /**
  8121. * Builds a map of scale ID to scale object for future lookup.
  8122. */
  8123. buildOrUpdateScales: function() {
  8124. var me = this;
  8125. var options = me.options;
  8126. var scales = me.scales || {};
  8127. var items = [];
  8128. var updated = Object.keys(scales).reduce(function(obj, id) {
  8129. obj[id] = false;
  8130. return obj;
  8131. }, {});
  8132. if (options.scales) {
  8133. items = items.concat(
  8134. (options.scales.xAxes || []).map(function(xAxisOptions) {
  8135. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  8136. }),
  8137. (options.scales.yAxes || []).map(function(yAxisOptions) {
  8138. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  8139. })
  8140. );
  8141. }
  8142. if (options.scale) {
  8143. items.push({
  8144. options: options.scale,
  8145. dtype: 'radialLinear',
  8146. isDefault: true,
  8147. dposition: 'chartArea'
  8148. });
  8149. }
  8150. helpers$1.each(items, function(item) {
  8151. var scaleOptions = item.options;
  8152. var id = scaleOptions.id;
  8153. var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);
  8154. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  8155. scaleOptions.position = item.dposition;
  8156. }
  8157. updated[id] = true;
  8158. var scale = null;
  8159. if (id in scales && scales[id].type === scaleType) {
  8160. scale = scales[id];
  8161. scale.options = scaleOptions;
  8162. scale.ctx = me.ctx;
  8163. scale.chart = me;
  8164. } else {
  8165. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  8166. if (!scaleClass) {
  8167. return;
  8168. }
  8169. scale = new scaleClass({
  8170. id: id,
  8171. type: scaleType,
  8172. options: scaleOptions,
  8173. ctx: me.ctx,
  8174. chart: me
  8175. });
  8176. scales[scale.id] = scale;
  8177. }
  8178. scale.mergeTicksOptions();
  8179. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  8180. // and consider it as a regular scale part of the "scales"" map only! This would
  8181. // make the logic easier and remove some useless? custom code.
  8182. if (item.isDefault) {
  8183. me.scale = scale;
  8184. }
  8185. });
  8186. // clear up discarded scales
  8187. helpers$1.each(updated, function(hasUpdated, id) {
  8188. if (!hasUpdated) {
  8189. delete scales[id];
  8190. }
  8191. });
  8192. me.scales = scales;
  8193. core_scaleService.addScalesToLayout(this);
  8194. },
  8195. buildOrUpdateControllers: function() {
  8196. var me = this;
  8197. var newControllers = [];
  8198. var datasets = me.data.datasets;
  8199. var i, ilen;
  8200. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  8201. var dataset = datasets[i];
  8202. var meta = me.getDatasetMeta(i);
  8203. var type = dataset.type || me.config.type;
  8204. if (meta.type && meta.type !== type) {
  8205. me.destroyDatasetMeta(i);
  8206. meta = me.getDatasetMeta(i);
  8207. }
  8208. meta.type = type;
  8209. meta.order = dataset.order || 0;
  8210. meta.index = i;
  8211. if (meta.controller) {
  8212. meta.controller.updateIndex(i);
  8213. meta.controller.linkScales();
  8214. } else {
  8215. var ControllerClass = controllers[meta.type];
  8216. if (ControllerClass === undefined) {
  8217. throw new Error('"' + meta.type + '" is not a chart type.');
  8218. }
  8219. meta.controller = new ControllerClass(me, i);
  8220. newControllers.push(meta.controller);
  8221. }
  8222. }
  8223. return newControllers;
  8224. },
  8225. /**
  8226. * Reset the elements of all datasets
  8227. * @private
  8228. */
  8229. resetElements: function() {
  8230. var me = this;
  8231. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  8232. me.getDatasetMeta(datasetIndex).controller.reset();
  8233. }, me);
  8234. },
  8235. /**
  8236. * Resets the chart back to it's state before the initial animation
  8237. */
  8238. reset: function() {
  8239. this.resetElements();
  8240. this.tooltip.initialize();
  8241. },
  8242. update: function(config) {
  8243. var me = this;
  8244. var i, ilen;
  8245. if (!config || typeof config !== 'object') {
  8246. // backwards compatibility
  8247. config = {
  8248. duration: config,
  8249. lazy: arguments[1]
  8250. };
  8251. }
  8252. updateConfig(me);
  8253. // plugins options references might have change, let's invalidate the cache
  8254. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  8255. core_plugins._invalidate(me);
  8256. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  8257. return;
  8258. }
  8259. // In case the entire data object changed
  8260. me.tooltip._data = me.data;
  8261. // Make sure dataset controllers are updated and new controllers are reset
  8262. var newControllers = me.buildOrUpdateControllers();
  8263. // Make sure all dataset controllers have correct meta data counts
  8264. for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  8265. me.getDatasetMeta(i).controller.buildOrUpdateElements();
  8266. }
  8267. me.updateLayout();
  8268. // Can only reset the new controllers after the scales have been updated
  8269. if (me.options.animation && me.options.animation.duration) {
  8270. helpers$1.each(newControllers, function(controller) {
  8271. controller.reset();
  8272. });
  8273. }
  8274. me.updateDatasets();
  8275. // Need to reset tooltip in case it is displayed with elements that are removed
  8276. // after update.
  8277. me.tooltip.initialize();
  8278. // Last active contains items that were previously in the tooltip.
  8279. // When we reset the tooltip, we need to clear it
  8280. me.lastActive = [];
  8281. // Do this before render so that any plugins that need final scale updates can use it
  8282. core_plugins.notify(me, 'afterUpdate');
  8283. me._layers.sort(compare2Level('z', '_idx'));
  8284. if (me._bufferedRender) {
  8285. me._bufferedRequest = {
  8286. duration: config.duration,
  8287. easing: config.easing,
  8288. lazy: config.lazy
  8289. };
  8290. } else {
  8291. me.render(config);
  8292. }
  8293. },
  8294. /**
  8295. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  8296. * hook, in which case, plugins will not be called on `afterLayout`.
  8297. * @private
  8298. */
  8299. updateLayout: function() {
  8300. var me = this;
  8301. if (core_plugins.notify(me, 'beforeLayout') === false) {
  8302. return;
  8303. }
  8304. core_layouts.update(this, this.width, this.height);
  8305. me._layers = [];
  8306. helpers$1.each(me.boxes, function(box) {
  8307. // _configure is called twice, once in core.scale.update and once here.
  8308. // Here the boxes are fully updated and at their final positions.
  8309. if (box._configure) {
  8310. box._configure();
  8311. }
  8312. me._layers.push.apply(me._layers, box._layers());
  8313. }, me);
  8314. me._layers.forEach(function(item, index) {
  8315. item._idx = index;
  8316. });
  8317. /**
  8318. * Provided for backward compatibility, use `afterLayout` instead.
  8319. * @method IPlugin#afterScaleUpdate
  8320. * @deprecated since version 2.5.0
  8321. * @todo remove at version 3
  8322. * @private
  8323. */
  8324. core_plugins.notify(me, 'afterScaleUpdate');
  8325. core_plugins.notify(me, 'afterLayout');
  8326. },
  8327. /**
  8328. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  8329. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  8330. * @private
  8331. */
  8332. updateDatasets: function() {
  8333. var me = this;
  8334. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  8335. return;
  8336. }
  8337. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8338. me.updateDataset(i);
  8339. }
  8340. core_plugins.notify(me, 'afterDatasetsUpdate');
  8341. },
  8342. /**
  8343. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  8344. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  8345. * @private
  8346. */
  8347. updateDataset: function(index) {
  8348. var me = this;
  8349. var meta = me.getDatasetMeta(index);
  8350. var args = {
  8351. meta: meta,
  8352. index: index
  8353. };
  8354. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  8355. return;
  8356. }
  8357. meta.controller._update();
  8358. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  8359. },
  8360. render: function(config) {
  8361. var me = this;
  8362. if (!config || typeof config !== 'object') {
  8363. // backwards compatibility
  8364. config = {
  8365. duration: config,
  8366. lazy: arguments[1]
  8367. };
  8368. }
  8369. var animationOptions = me.options.animation;
  8370. var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);
  8371. var lazy = config.lazy;
  8372. if (core_plugins.notify(me, 'beforeRender') === false) {
  8373. return;
  8374. }
  8375. var onComplete = function(animation) {
  8376. core_plugins.notify(me, 'afterRender');
  8377. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  8378. };
  8379. if (animationOptions && duration) {
  8380. var animation = new core_animation({
  8381. numSteps: duration / 16.66, // 60 fps
  8382. easing: config.easing || animationOptions.easing,
  8383. render: function(chart, animationObject) {
  8384. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  8385. var currentStep = animationObject.currentStep;
  8386. var stepDecimal = currentStep / animationObject.numSteps;
  8387. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  8388. },
  8389. onAnimationProgress: animationOptions.onProgress,
  8390. onAnimationComplete: onComplete
  8391. });
  8392. core_animations.addAnimation(me, animation, duration, lazy);
  8393. } else {
  8394. me.draw();
  8395. // See https://github.com/chartjs/Chart.js/issues/3781
  8396. onComplete(new core_animation({numSteps: 0, chart: me}));
  8397. }
  8398. return me;
  8399. },
  8400. draw: function(easingValue) {
  8401. var me = this;
  8402. var i, layers;
  8403. me.clear();
  8404. if (helpers$1.isNullOrUndef(easingValue)) {
  8405. easingValue = 1;
  8406. }
  8407. me.transition(easingValue);
  8408. if (me.width <= 0 || me.height <= 0) {
  8409. return;
  8410. }
  8411. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  8412. return;
  8413. }
  8414. // Because of plugin hooks (before/afterDatasetsDraw), datasets can't
  8415. // currently be part of layers. Instead, we draw
  8416. // layers <= 0 before(default, backward compat), and the rest after
  8417. layers = me._layers;
  8418. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  8419. layers[i].draw(me.chartArea);
  8420. }
  8421. me.drawDatasets(easingValue);
  8422. // Rest of layers
  8423. for (; i < layers.length; ++i) {
  8424. layers[i].draw(me.chartArea);
  8425. }
  8426. me._drawTooltip(easingValue);
  8427. core_plugins.notify(me, 'afterDraw', [easingValue]);
  8428. },
  8429. /**
  8430. * @private
  8431. */
  8432. transition: function(easingValue) {
  8433. var me = this;
  8434. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  8435. if (me.isDatasetVisible(i)) {
  8436. me.getDatasetMeta(i).controller.transition(easingValue);
  8437. }
  8438. }
  8439. me.tooltip.transition(easingValue);
  8440. },
  8441. /**
  8442. * @private
  8443. */
  8444. _getSortedDatasetMetas: function(filterVisible) {
  8445. var me = this;
  8446. var datasets = me.data.datasets || [];
  8447. var result = [];
  8448. var i, ilen;
  8449. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  8450. if (!filterVisible || me.isDatasetVisible(i)) {
  8451. result.push(me.getDatasetMeta(i));
  8452. }
  8453. }
  8454. result.sort(compare2Level('order', 'index'));
  8455. return result;
  8456. },
  8457. /**
  8458. * @private
  8459. */
  8460. _getSortedVisibleDatasetMetas: function() {
  8461. return this._getSortedDatasetMetas(true);
  8462. },
  8463. /**
  8464. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  8465. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  8466. * @private
  8467. */
  8468. drawDatasets: function(easingValue) {
  8469. var me = this;
  8470. var metasets, i;
  8471. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  8472. return;
  8473. }
  8474. metasets = me._getSortedVisibleDatasetMetas();
  8475. for (i = metasets.length - 1; i >= 0; --i) {
  8476. me.drawDataset(metasets[i], easingValue);
  8477. }
  8478. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  8479. },
  8480. /**
  8481. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  8482. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  8483. * @private
  8484. */
  8485. drawDataset: function(meta, easingValue) {
  8486. var me = this;
  8487. var args = {
  8488. meta: meta,
  8489. index: meta.index,
  8490. easingValue: easingValue
  8491. };
  8492. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  8493. return;
  8494. }
  8495. meta.controller.draw(easingValue);
  8496. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  8497. },
  8498. /**
  8499. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  8500. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  8501. * @private
  8502. */
  8503. _drawTooltip: function(easingValue) {
  8504. var me = this;
  8505. var tooltip = me.tooltip;
  8506. var args = {
  8507. tooltip: tooltip,
  8508. easingValue: easingValue
  8509. };
  8510. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  8511. return;
  8512. }
  8513. tooltip.draw();
  8514. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  8515. },
  8516. /**
  8517. * Get the single element that was clicked on
  8518. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  8519. */
  8520. getElementAtEvent: function(e) {
  8521. return core_interaction.modes.single(this, e);
  8522. },
  8523. getElementsAtEvent: function(e) {
  8524. return core_interaction.modes.label(this, e, {intersect: true});
  8525. },
  8526. getElementsAtXAxis: function(e) {
  8527. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  8528. },
  8529. getElementsAtEventForMode: function(e, mode, options) {
  8530. var method = core_interaction.modes[mode];
  8531. if (typeof method === 'function') {
  8532. return method(this, e, options);
  8533. }
  8534. return [];
  8535. },
  8536. getDatasetAtEvent: function(e) {
  8537. return core_interaction.modes.dataset(this, e, {intersect: true});
  8538. },
  8539. getDatasetMeta: function(datasetIndex) {
  8540. var me = this;
  8541. var dataset = me.data.datasets[datasetIndex];
  8542. if (!dataset._meta) {
  8543. dataset._meta = {};
  8544. }
  8545. var meta = dataset._meta[me.id];
  8546. if (!meta) {
  8547. meta = dataset._meta[me.id] = {
  8548. type: null,
  8549. data: [],
  8550. dataset: null,
  8551. controller: null,
  8552. hidden: null, // See isDatasetVisible() comment
  8553. xAxisID: null,
  8554. yAxisID: null,
  8555. order: dataset.order || 0,
  8556. index: datasetIndex
  8557. };
  8558. }
  8559. return meta;
  8560. },
  8561. getVisibleDatasetCount: function() {
  8562. var count = 0;
  8563. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  8564. if (this.isDatasetVisible(i)) {
  8565. count++;
  8566. }
  8567. }
  8568. return count;
  8569. },
  8570. isDatasetVisible: function(datasetIndex) {
  8571. var meta = this.getDatasetMeta(datasetIndex);
  8572. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  8573. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  8574. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  8575. },
  8576. generateLegend: function() {
  8577. return this.options.legendCallback(this);
  8578. },
  8579. /**
  8580. * @private
  8581. */
  8582. destroyDatasetMeta: function(datasetIndex) {
  8583. var id = this.id;
  8584. var dataset = this.data.datasets[datasetIndex];
  8585. var meta = dataset._meta && dataset._meta[id];
  8586. if (meta) {
  8587. meta.controller.destroy();
  8588. delete dataset._meta[id];
  8589. }
  8590. },
  8591. destroy: function() {
  8592. var me = this;
  8593. var canvas = me.canvas;
  8594. var i, ilen;
  8595. me.stop();
  8596. // dataset controllers need to cleanup associated data
  8597. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8598. me.destroyDatasetMeta(i);
  8599. }
  8600. if (canvas) {
  8601. me.unbindEvents();
  8602. helpers$1.canvas.clear(me);
  8603. platform.releaseContext(me.ctx);
  8604. me.canvas = null;
  8605. me.ctx = null;
  8606. }
  8607. core_plugins.notify(me, 'destroy');
  8608. delete Chart.instances[me.id];
  8609. },
  8610. toBase64Image: function() {
  8611. return this.canvas.toDataURL.apply(this.canvas, arguments);
  8612. },
  8613. initToolTip: function() {
  8614. var me = this;
  8615. me.tooltip = new core_tooltip({
  8616. _chart: me,
  8617. _chartInstance: me, // deprecated, backward compatibility
  8618. _data: me.data,
  8619. _options: me.options.tooltips
  8620. }, me);
  8621. },
  8622. /**
  8623. * @private
  8624. */
  8625. bindEvents: function() {
  8626. var me = this;
  8627. var listeners = me._listeners = {};
  8628. var listener = function() {
  8629. me.eventHandler.apply(me, arguments);
  8630. };
  8631. helpers$1.each(me.options.events, function(type) {
  8632. platform.addEventListener(me, type, listener);
  8633. listeners[type] = listener;
  8634. });
  8635. // Elements used to detect size change should not be injected for non responsive charts.
  8636. // See https://github.com/chartjs/Chart.js/issues/2210
  8637. if (me.options.responsive) {
  8638. listener = function() {
  8639. me.resize();
  8640. };
  8641. platform.addEventListener(me, 'resize', listener);
  8642. listeners.resize = listener;
  8643. }
  8644. },
  8645. /**
  8646. * @private
  8647. */
  8648. unbindEvents: function() {
  8649. var me = this;
  8650. var listeners = me._listeners;
  8651. if (!listeners) {
  8652. return;
  8653. }
  8654. delete me._listeners;
  8655. helpers$1.each(listeners, function(listener, type) {
  8656. platform.removeEventListener(me, type, listener);
  8657. });
  8658. },
  8659. updateHoverStyle: function(elements, mode, enabled) {
  8660. var prefix = enabled ? 'set' : 'remove';
  8661. var element, i, ilen;
  8662. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  8663. element = elements[i];
  8664. if (element) {
  8665. this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);
  8666. }
  8667. }
  8668. if (mode === 'dataset') {
  8669. this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();
  8670. }
  8671. },
  8672. /**
  8673. * @private
  8674. */
  8675. eventHandler: function(e) {
  8676. var me = this;
  8677. var tooltip = me.tooltip;
  8678. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  8679. return;
  8680. }
  8681. // Buffer any update calls so that renders do not occur
  8682. me._bufferedRender = true;
  8683. me._bufferedRequest = null;
  8684. var changed = me.handleEvent(e);
  8685. // for smooth tooltip animations issue #4989
  8686. // the tooltip should be the source of change
  8687. // Animation check workaround:
  8688. // tooltip._start will be null when tooltip isn't animating
  8689. if (tooltip) {
  8690. changed = tooltip._start
  8691. ? tooltip.handleEvent(e)
  8692. : changed | tooltip.handleEvent(e);
  8693. }
  8694. core_plugins.notify(me, 'afterEvent', [e]);
  8695. var bufferedRequest = me._bufferedRequest;
  8696. if (bufferedRequest) {
  8697. // If we have an update that was triggered, we need to do a normal render
  8698. me.render(bufferedRequest);
  8699. } else if (changed && !me.animating) {
  8700. // If entering, leaving, or changing elements, animate the change via pivot
  8701. me.stop();
  8702. // We only need to render at this point. Updating will cause scales to be
  8703. // recomputed generating flicker & using more memory than necessary.
  8704. me.render({
  8705. duration: me.options.hover.animationDuration,
  8706. lazy: true
  8707. });
  8708. }
  8709. me._bufferedRender = false;
  8710. me._bufferedRequest = null;
  8711. return me;
  8712. },
  8713. /**
  8714. * Handle an event
  8715. * @private
  8716. * @param {IEvent} event the event to handle
  8717. * @return {boolean} true if the chart needs to re-render
  8718. */
  8719. handleEvent: function(e) {
  8720. var me = this;
  8721. var options = me.options || {};
  8722. var hoverOptions = options.hover;
  8723. var changed = false;
  8724. me.lastActive = me.lastActive || [];
  8725. // Find Active Elements for hover and tooltips
  8726. if (e.type === 'mouseout') {
  8727. me.active = [];
  8728. } else {
  8729. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  8730. }
  8731. // Invoke onHover hook
  8732. // Need to call with native event here to not break backwards compatibility
  8733. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  8734. if (e.type === 'mouseup' || e.type === 'click') {
  8735. if (options.onClick) {
  8736. // Use e.native here for backwards compatibility
  8737. options.onClick.call(me, e.native, me.active);
  8738. }
  8739. }
  8740. // Remove styling for last active (even if it may still be active)
  8741. if (me.lastActive.length) {
  8742. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  8743. }
  8744. // Built in hover styling
  8745. if (me.active.length && hoverOptions.mode) {
  8746. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  8747. }
  8748. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  8749. // Remember Last Actives
  8750. me.lastActive = me.active;
  8751. return changed;
  8752. }
  8753. });
  8754. /**
  8755. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  8756. * for backward compatibility. Though, it can still be useful for plugins that
  8757. * would need to work on multiple charts?!
  8758. */
  8759. Chart.instances = {};
  8760. var core_controller = Chart;
  8761. // DEPRECATIONS
  8762. /**
  8763. * Provided for backward compatibility, use Chart instead.
  8764. * @class Chart.Controller
  8765. * @deprecated since version 2.6
  8766. * @todo remove at version 3
  8767. * @private
  8768. */
  8769. Chart.Controller = Chart;
  8770. /**
  8771. * Provided for backward compatibility, not available anymore.
  8772. * @namespace Chart
  8773. * @deprecated since version 2.8
  8774. * @todo remove at version 3
  8775. * @private
  8776. */
  8777. Chart.types = {};
  8778. /**
  8779. * Provided for backward compatibility, not available anymore.
  8780. * @namespace Chart.helpers.configMerge
  8781. * @deprecated since version 2.8.0
  8782. * @todo remove at version 3
  8783. * @private
  8784. */
  8785. helpers$1.configMerge = mergeConfig;
  8786. /**
  8787. * Provided for backward compatibility, not available anymore.
  8788. * @namespace Chart.helpers.scaleMerge
  8789. * @deprecated since version 2.8.0
  8790. * @todo remove at version 3
  8791. * @private
  8792. */
  8793. helpers$1.scaleMerge = mergeScaleConfig;
  8794. var core_helpers = function() {
  8795. // -- Basic js utility methods
  8796. helpers$1.where = function(collection, filterCallback) {
  8797. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  8798. return collection.filter(filterCallback);
  8799. }
  8800. var filtered = [];
  8801. helpers$1.each(collection, function(item) {
  8802. if (filterCallback(item)) {
  8803. filtered.push(item);
  8804. }
  8805. });
  8806. return filtered;
  8807. };
  8808. helpers$1.findIndex = Array.prototype.findIndex ?
  8809. function(array, callback, scope) {
  8810. return array.findIndex(callback, scope);
  8811. } :
  8812. function(array, callback, scope) {
  8813. scope = scope === undefined ? array : scope;
  8814. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  8815. if (callback.call(scope, array[i], i, array)) {
  8816. return i;
  8817. }
  8818. }
  8819. return -1;
  8820. };
  8821. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  8822. // Default to start of the array
  8823. if (helpers$1.isNullOrUndef(startIndex)) {
  8824. startIndex = -1;
  8825. }
  8826. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8827. var currentItem = arrayToSearch[i];
  8828. if (filterCallback(currentItem)) {
  8829. return currentItem;
  8830. }
  8831. }
  8832. };
  8833. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8834. // Default to end of the array
  8835. if (helpers$1.isNullOrUndef(startIndex)) {
  8836. startIndex = arrayToSearch.length;
  8837. }
  8838. for (var i = startIndex - 1; i >= 0; i--) {
  8839. var currentItem = arrayToSearch[i];
  8840. if (filterCallback(currentItem)) {
  8841. return currentItem;
  8842. }
  8843. }
  8844. };
  8845. // -- Math methods
  8846. helpers$1.isNumber = function(n) {
  8847. return !isNaN(parseFloat(n)) && isFinite(n);
  8848. };
  8849. helpers$1.almostEquals = function(x, y, epsilon) {
  8850. return Math.abs(x - y) < epsilon;
  8851. };
  8852. helpers$1.almostWhole = function(x, epsilon) {
  8853. var rounded = Math.round(x);
  8854. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  8855. };
  8856. helpers$1.max = function(array) {
  8857. return array.reduce(function(max, value) {
  8858. if (!isNaN(value)) {
  8859. return Math.max(max, value);
  8860. }
  8861. return max;
  8862. }, Number.NEGATIVE_INFINITY);
  8863. };
  8864. helpers$1.min = function(array) {
  8865. return array.reduce(function(min, value) {
  8866. if (!isNaN(value)) {
  8867. return Math.min(min, value);
  8868. }
  8869. return min;
  8870. }, Number.POSITIVE_INFINITY);
  8871. };
  8872. helpers$1.sign = Math.sign ?
  8873. function(x) {
  8874. return Math.sign(x);
  8875. } :
  8876. function(x) {
  8877. x = +x; // convert to a number
  8878. if (x === 0 || isNaN(x)) {
  8879. return x;
  8880. }
  8881. return x > 0 ? 1 : -1;
  8882. };
  8883. helpers$1.toRadians = function(degrees) {
  8884. return degrees * (Math.PI / 180);
  8885. };
  8886. helpers$1.toDegrees = function(radians) {
  8887. return radians * (180 / Math.PI);
  8888. };
  8889. /**
  8890. * Returns the number of decimal places
  8891. * i.e. the number of digits after the decimal point, of the value of this Number.
  8892. * @param {number} x - A number.
  8893. * @returns {number} The number of decimal places.
  8894. * @private
  8895. */
  8896. helpers$1._decimalPlaces = function(x) {
  8897. if (!helpers$1.isFinite(x)) {
  8898. return;
  8899. }
  8900. var e = 1;
  8901. var p = 0;
  8902. while (Math.round(x * e) / e !== x) {
  8903. e *= 10;
  8904. p++;
  8905. }
  8906. return p;
  8907. };
  8908. // Gets the angle from vertical upright to the point about a centre.
  8909. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  8910. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8911. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8912. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8913. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8914. if (angle < (-0.5 * Math.PI)) {
  8915. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8916. }
  8917. return {
  8918. angle: angle,
  8919. distance: radialDistanceFromCenter
  8920. };
  8921. };
  8922. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  8923. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8924. };
  8925. /**
  8926. * Provided for backward compatibility, not available anymore
  8927. * @function Chart.helpers.aliasPixel
  8928. * @deprecated since version 2.8.0
  8929. * @todo remove at version 3
  8930. */
  8931. helpers$1.aliasPixel = function(pixelWidth) {
  8932. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8933. };
  8934. /**
  8935. * Returns the aligned pixel value to avoid anti-aliasing blur
  8936. * @param {Chart} chart - The chart instance.
  8937. * @param {number} pixel - A pixel value.
  8938. * @param {number} width - The width of the element.
  8939. * @returns {number} The aligned pixel value.
  8940. * @private
  8941. */
  8942. helpers$1._alignPixel = function(chart, pixel, width) {
  8943. var devicePixelRatio = chart.currentDevicePixelRatio;
  8944. var halfWidth = width / 2;
  8945. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8946. };
  8947. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8948. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8949. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8950. // This function must also respect "skipped" points
  8951. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8952. var current = middlePoint;
  8953. var next = afterPoint.skip ? middlePoint : afterPoint;
  8954. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8955. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8956. var s01 = d01 / (d01 + d12);
  8957. var s12 = d12 / (d01 + d12);
  8958. // If all points are the same, s01 & s02 will be inf
  8959. s01 = isNaN(s01) ? 0 : s01;
  8960. s12 = isNaN(s12) ? 0 : s12;
  8961. var fa = t * s01; // scaling factor for triangle Ta
  8962. var fb = t * s12;
  8963. return {
  8964. previous: {
  8965. x: current.x - fa * (next.x - previous.x),
  8966. y: current.y - fa * (next.y - previous.y)
  8967. },
  8968. next: {
  8969. x: current.x + fb * (next.x - previous.x),
  8970. y: current.y + fb * (next.y - previous.y)
  8971. }
  8972. };
  8973. };
  8974. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  8975. helpers$1.splineCurveMonotone = function(points) {
  8976. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8977. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8978. // between the dataset discrete points due to the interpolation.
  8979. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8980. var pointsWithTangents = (points || []).map(function(point) {
  8981. return {
  8982. model: point._model,
  8983. deltaK: 0,
  8984. mK: 0
  8985. };
  8986. });
  8987. // Calculate slopes (deltaK) and initialize tangents (mK)
  8988. var pointsLen = pointsWithTangents.length;
  8989. var i, pointBefore, pointCurrent, pointAfter;
  8990. for (i = 0; i < pointsLen; ++i) {
  8991. pointCurrent = pointsWithTangents[i];
  8992. if (pointCurrent.model.skip) {
  8993. continue;
  8994. }
  8995. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8996. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8997. if (pointAfter && !pointAfter.model.skip) {
  8998. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8999. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  9000. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  9001. }
  9002. if (!pointBefore || pointBefore.model.skip) {
  9003. pointCurrent.mK = pointCurrent.deltaK;
  9004. } else if (!pointAfter || pointAfter.model.skip) {
  9005. pointCurrent.mK = pointBefore.deltaK;
  9006. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  9007. pointCurrent.mK = 0;
  9008. } else {
  9009. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  9010. }
  9011. }
  9012. // Adjust tangents to ensure monotonic properties
  9013. var alphaK, betaK, tauK, squaredMagnitude;
  9014. for (i = 0; i < pointsLen - 1; ++i) {
  9015. pointCurrent = pointsWithTangents[i];
  9016. pointAfter = pointsWithTangents[i + 1];
  9017. if (pointCurrent.model.skip || pointAfter.model.skip) {
  9018. continue;
  9019. }
  9020. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  9021. pointCurrent.mK = pointAfter.mK = 0;
  9022. continue;
  9023. }
  9024. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  9025. betaK = pointAfter.mK / pointCurrent.deltaK;
  9026. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  9027. if (squaredMagnitude <= 9) {
  9028. continue;
  9029. }
  9030. tauK = 3 / Math.sqrt(squaredMagnitude);
  9031. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  9032. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  9033. }
  9034. // Compute control points
  9035. var deltaX;
  9036. for (i = 0; i < pointsLen; ++i) {
  9037. pointCurrent = pointsWithTangents[i];
  9038. if (pointCurrent.model.skip) {
  9039. continue;
  9040. }
  9041. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  9042. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  9043. if (pointBefore && !pointBefore.model.skip) {
  9044. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  9045. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  9046. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  9047. }
  9048. if (pointAfter && !pointAfter.model.skip) {
  9049. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  9050. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  9051. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  9052. }
  9053. }
  9054. };
  9055. helpers$1.nextItem = function(collection, index, loop) {
  9056. if (loop) {
  9057. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  9058. }
  9059. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  9060. };
  9061. helpers$1.previousItem = function(collection, index, loop) {
  9062. if (loop) {
  9063. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  9064. }
  9065. return index <= 0 ? collection[0] : collection[index - 1];
  9066. };
  9067. // Implementation of the nice number algorithm used in determining where axis labels will go
  9068. helpers$1.niceNum = function(range, round) {
  9069. var exponent = Math.floor(helpers$1.log10(range));
  9070. var fraction = range / Math.pow(10, exponent);
  9071. var niceFraction;
  9072. if (round) {
  9073. if (fraction < 1.5) {
  9074. niceFraction = 1;
  9075. } else if (fraction < 3) {
  9076. niceFraction = 2;
  9077. } else if (fraction < 7) {
  9078. niceFraction = 5;
  9079. } else {
  9080. niceFraction = 10;
  9081. }
  9082. } else if (fraction <= 1.0) {
  9083. niceFraction = 1;
  9084. } else if (fraction <= 2) {
  9085. niceFraction = 2;
  9086. } else if (fraction <= 5) {
  9087. niceFraction = 5;
  9088. } else {
  9089. niceFraction = 10;
  9090. }
  9091. return niceFraction * Math.pow(10, exponent);
  9092. };
  9093. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  9094. helpers$1.requestAnimFrame = (function() {
  9095. if (typeof window === 'undefined') {
  9096. return function(callback) {
  9097. callback();
  9098. };
  9099. }
  9100. return window.requestAnimationFrame ||
  9101. window.webkitRequestAnimationFrame ||
  9102. window.mozRequestAnimationFrame ||
  9103. window.oRequestAnimationFrame ||
  9104. window.msRequestAnimationFrame ||
  9105. function(callback) {
  9106. return window.setTimeout(callback, 1000 / 60);
  9107. };
  9108. }());
  9109. // -- DOM methods
  9110. helpers$1.getRelativePosition = function(evt, chart) {
  9111. var mouseX, mouseY;
  9112. var e = evt.originalEvent || evt;
  9113. var canvas = evt.target || evt.srcElement;
  9114. var boundingRect = canvas.getBoundingClientRect();
  9115. var touches = e.touches;
  9116. if (touches && touches.length > 0) {
  9117. mouseX = touches[0].clientX;
  9118. mouseY = touches[0].clientY;
  9119. } else {
  9120. mouseX = e.clientX;
  9121. mouseY = e.clientY;
  9122. }
  9123. // Scale mouse coordinates into canvas coordinates
  9124. // by following the pattern laid out by 'jerryj' in the comments of
  9125. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  9126. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  9127. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  9128. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  9129. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  9130. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  9131. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  9132. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  9133. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  9134. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  9135. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  9136. return {
  9137. x: mouseX,
  9138. y: mouseY
  9139. };
  9140. };
  9141. // Private helper function to convert max-width/max-height values that may be percentages into a number
  9142. function parseMaxStyle(styleValue, node, parentProperty) {
  9143. var valueInPixels;
  9144. if (typeof styleValue === 'string') {
  9145. valueInPixels = parseInt(styleValue, 10);
  9146. if (styleValue.indexOf('%') !== -1) {
  9147. // percentage * size in dimension
  9148. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  9149. }
  9150. } else {
  9151. valueInPixels = styleValue;
  9152. }
  9153. return valueInPixels;
  9154. }
  9155. /**
  9156. * Returns if the given value contains an effective constraint.
  9157. * @private
  9158. */
  9159. function isConstrainedValue(value) {
  9160. return value !== undefined && value !== null && value !== 'none';
  9161. }
  9162. /**
  9163. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  9164. * @param {HTMLElement} domNode - the node to check the constraint on
  9165. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  9166. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  9167. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  9168. */
  9169. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  9170. var view = document.defaultView;
  9171. var parentNode = helpers$1._getParentNode(domNode);
  9172. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  9173. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  9174. var hasCNode = isConstrainedValue(constrainedNode);
  9175. var hasCContainer = isConstrainedValue(constrainedContainer);
  9176. var infinity = Number.POSITIVE_INFINITY;
  9177. if (hasCNode || hasCContainer) {
  9178. return Math.min(
  9179. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  9180. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  9181. }
  9182. return 'none';
  9183. }
  9184. // returns Number or undefined if no constraint
  9185. helpers$1.getConstraintWidth = function(domNode) {
  9186. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  9187. };
  9188. // returns Number or undefined if no constraint
  9189. helpers$1.getConstraintHeight = function(domNode) {
  9190. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  9191. };
  9192. /**
  9193. * @private
  9194. */
  9195. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  9196. padding = helpers$1.getStyle(container, padding);
  9197. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  9198. };
  9199. /**
  9200. * @private
  9201. */
  9202. helpers$1._getParentNode = function(domNode) {
  9203. var parent = domNode.parentNode;
  9204. if (parent && parent.toString() === '[object ShadowRoot]') {
  9205. parent = parent.host;
  9206. }
  9207. return parent;
  9208. };
  9209. helpers$1.getMaximumWidth = function(domNode) {
  9210. var container = helpers$1._getParentNode(domNode);
  9211. if (!container) {
  9212. return domNode.clientWidth;
  9213. }
  9214. var clientWidth = container.clientWidth;
  9215. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  9216. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  9217. var w = clientWidth - paddingLeft - paddingRight;
  9218. var cw = helpers$1.getConstraintWidth(domNode);
  9219. return isNaN(cw) ? w : Math.min(w, cw);
  9220. };
  9221. helpers$1.getMaximumHeight = function(domNode) {
  9222. var container = helpers$1._getParentNode(domNode);
  9223. if (!container) {
  9224. return domNode.clientHeight;
  9225. }
  9226. var clientHeight = container.clientHeight;
  9227. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  9228. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  9229. var h = clientHeight - paddingTop - paddingBottom;
  9230. var ch = helpers$1.getConstraintHeight(domNode);
  9231. return isNaN(ch) ? h : Math.min(h, ch);
  9232. };
  9233. helpers$1.getStyle = function(el, property) {
  9234. return el.currentStyle ?
  9235. el.currentStyle[property] :
  9236. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  9237. };
  9238. helpers$1.retinaScale = function(chart, forceRatio) {
  9239. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  9240. if (pixelRatio === 1) {
  9241. return;
  9242. }
  9243. var canvas = chart.canvas;
  9244. var height = chart.height;
  9245. var width = chart.width;
  9246. canvas.height = height * pixelRatio;
  9247. canvas.width = width * pixelRatio;
  9248. chart.ctx.scale(pixelRatio, pixelRatio);
  9249. // If no style has been set on the canvas, the render size is used as display size,
  9250. // making the chart visually bigger, so let's enforce it to the "correct" values.
  9251. // See https://github.com/chartjs/Chart.js/issues/3575
  9252. if (!canvas.style.height && !canvas.style.width) {
  9253. canvas.style.height = height + 'px';
  9254. canvas.style.width = width + 'px';
  9255. }
  9256. };
  9257. // -- Canvas methods
  9258. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  9259. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  9260. };
  9261. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  9262. cache = cache || {};
  9263. var data = cache.data = cache.data || {};
  9264. var gc = cache.garbageCollect = cache.garbageCollect || [];
  9265. if (cache.font !== font) {
  9266. data = cache.data = {};
  9267. gc = cache.garbageCollect = [];
  9268. cache.font = font;
  9269. }
  9270. ctx.font = font;
  9271. var longest = 0;
  9272. var ilen = arrayOfThings.length;
  9273. var i, j, jlen, thing, nestedThing;
  9274. for (i = 0; i < ilen; i++) {
  9275. thing = arrayOfThings[i];
  9276. // Undefined strings and arrays should not be measured
  9277. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  9278. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  9279. } else if (helpers$1.isArray(thing)) {
  9280. // if it is an array lets measure each element
  9281. // to do maybe simplify this function a bit so we can do this more recursively?
  9282. for (j = 0, jlen = thing.length; j < jlen; j++) {
  9283. nestedThing = thing[j];
  9284. // Undefined strings and arrays should not be measured
  9285. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  9286. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  9287. }
  9288. }
  9289. }
  9290. }
  9291. var gcLen = gc.length / 2;
  9292. if (gcLen > arrayOfThings.length) {
  9293. for (i = 0; i < gcLen; i++) {
  9294. delete data[gc[i]];
  9295. }
  9296. gc.splice(0, gcLen);
  9297. }
  9298. return longest;
  9299. };
  9300. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  9301. var textWidth = data[string];
  9302. if (!textWidth) {
  9303. textWidth = data[string] = ctx.measureText(string).width;
  9304. gc.push(string);
  9305. }
  9306. if (textWidth > longest) {
  9307. longest = textWidth;
  9308. }
  9309. return longest;
  9310. };
  9311. /**
  9312. * @deprecated
  9313. */
  9314. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  9315. var numberOfLines = 1;
  9316. helpers$1.each(arrayOfThings, function(thing) {
  9317. if (helpers$1.isArray(thing)) {
  9318. if (thing.length > numberOfLines) {
  9319. numberOfLines = thing.length;
  9320. }
  9321. }
  9322. });
  9323. return numberOfLines;
  9324. };
  9325. helpers$1.color = !chartjsColor ?
  9326. function(value) {
  9327. console.error('Color.js not found!');
  9328. return value;
  9329. } :
  9330. function(value) {
  9331. /* global CanvasGradient */
  9332. if (value instanceof CanvasGradient) {
  9333. value = core_defaults.global.defaultColor;
  9334. }
  9335. return chartjsColor(value);
  9336. };
  9337. helpers$1.getHoverColor = function(colorValue) {
  9338. /* global CanvasPattern */
  9339. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  9340. colorValue :
  9341. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  9342. };
  9343. };
  9344. function abstract() {
  9345. throw new Error(
  9346. 'This method is not implemented: either no adapter can ' +
  9347. 'be found or an incomplete integration was provided.'
  9348. );
  9349. }
  9350. /**
  9351. * Date adapter (current used by the time scale)
  9352. * @namespace Chart._adapters._date
  9353. * @memberof Chart._adapters
  9354. * @private
  9355. */
  9356. /**
  9357. * Currently supported unit string values.
  9358. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  9359. * @memberof Chart._adapters._date
  9360. * @name Unit
  9361. */
  9362. /**
  9363. * @class
  9364. */
  9365. function DateAdapter(options) {
  9366. this.options = options || {};
  9367. }
  9368. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  9369. /**
  9370. * Returns a map of time formats for the supported formatting units defined
  9371. * in Unit as well as 'datetime' representing a detailed date/time string.
  9372. * @returns {{string: string}}
  9373. */
  9374. formats: abstract,
  9375. /**
  9376. * Parses the given `value` and return the associated timestamp.
  9377. * @param {any} value - the value to parse (usually comes from the data)
  9378. * @param {string} [format] - the expected data format
  9379. * @returns {(number|null)}
  9380. * @function
  9381. */
  9382. parse: abstract,
  9383. /**
  9384. * Returns the formatted date in the specified `format` for a given `timestamp`.
  9385. * @param {number} timestamp - the timestamp to format
  9386. * @param {string} format - the date/time token
  9387. * @return {string}
  9388. * @function
  9389. */
  9390. format: abstract,
  9391. /**
  9392. * Adds the specified `amount` of `unit` to the given `timestamp`.
  9393. * @param {number} timestamp - the input timestamp
  9394. * @param {number} amount - the amount to add
  9395. * @param {Unit} unit - the unit as string
  9396. * @return {number}
  9397. * @function
  9398. */
  9399. add: abstract,
  9400. /**
  9401. * Returns the number of `unit` between the given timestamps.
  9402. * @param {number} max - the input timestamp (reference)
  9403. * @param {number} min - the timestamp to substract
  9404. * @param {Unit} unit - the unit as string
  9405. * @return {number}
  9406. * @function
  9407. */
  9408. diff: abstract,
  9409. /**
  9410. * Returns start of `unit` for the given `timestamp`.
  9411. * @param {number} timestamp - the input timestamp
  9412. * @param {Unit} unit - the unit as string
  9413. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  9414. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  9415. * @function
  9416. */
  9417. startOf: abstract,
  9418. /**
  9419. * Returns end of `unit` for the given `timestamp`.
  9420. * @param {number} timestamp - the input timestamp
  9421. * @param {Unit} unit - the unit as string
  9422. * @function
  9423. */
  9424. endOf: abstract,
  9425. // DEPRECATIONS
  9426. /**
  9427. * Provided for backward compatibility for scale.getValueForPixel(),
  9428. * this method should be overridden only by the moment adapter.
  9429. * @deprecated since version 2.8.0
  9430. * @todo remove at version 3
  9431. * @private
  9432. */
  9433. _create: function(value) {
  9434. return value;
  9435. }
  9436. });
  9437. DateAdapter.override = function(members) {
  9438. helpers$1.extend(DateAdapter.prototype, members);
  9439. };
  9440. var _date = DateAdapter;
  9441. var core_adapters = {
  9442. _date: _date
  9443. };
  9444. /**
  9445. * Namespace to hold static tick generation functions
  9446. * @namespace Chart.Ticks
  9447. */
  9448. var core_ticks = {
  9449. /**
  9450. * Namespace to hold formatters for different types of ticks
  9451. * @namespace Chart.Ticks.formatters
  9452. */
  9453. formatters: {
  9454. /**
  9455. * Formatter for value labels
  9456. * @method Chart.Ticks.formatters.values
  9457. * @param value the value to display
  9458. * @return {string|string[]} the label to display
  9459. */
  9460. values: function(value) {
  9461. return helpers$1.isArray(value) ? value : '' + value;
  9462. },
  9463. /**
  9464. * Formatter for linear numeric ticks
  9465. * @method Chart.Ticks.formatters.linear
  9466. * @param tickValue {number} the value to be formatted
  9467. * @param index {number} the position of the tickValue parameter in the ticks array
  9468. * @param ticks {number[]} the list of ticks being converted
  9469. * @return {string} string representation of the tickValue parameter
  9470. */
  9471. linear: function(tickValue, index, ticks) {
  9472. // If we have lots of ticks, don't use the ones
  9473. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  9474. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  9475. if (Math.abs(delta) > 1) {
  9476. if (tickValue !== Math.floor(tickValue)) {
  9477. // not an integer
  9478. delta = tickValue - Math.floor(tickValue);
  9479. }
  9480. }
  9481. var logDelta = helpers$1.log10(Math.abs(delta));
  9482. var tickString = '';
  9483. if (tickValue !== 0) {
  9484. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  9485. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  9486. var logTick = helpers$1.log10(Math.abs(tickValue));
  9487. var numExponential = Math.floor(logTick) - Math.floor(logDelta);
  9488. numExponential = Math.max(Math.min(numExponential, 20), 0);
  9489. tickString = tickValue.toExponential(numExponential);
  9490. } else {
  9491. var numDecimal = -1 * Math.floor(logDelta);
  9492. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  9493. tickString = tickValue.toFixed(numDecimal);
  9494. }
  9495. } else {
  9496. tickString = '0'; // never show decimal places for 0
  9497. }
  9498. return tickString;
  9499. },
  9500. logarithmic: function(tickValue, index, ticks) {
  9501. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  9502. if (tickValue === 0) {
  9503. return '0';
  9504. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  9505. return tickValue.toExponential();
  9506. }
  9507. return '';
  9508. }
  9509. }
  9510. };
  9511. var isArray = helpers$1.isArray;
  9512. var isNullOrUndef = helpers$1.isNullOrUndef;
  9513. var valueOrDefault$a = helpers$1.valueOrDefault;
  9514. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  9515. core_defaults._set('scale', {
  9516. display: true,
  9517. position: 'left',
  9518. offset: false,
  9519. // grid line settings
  9520. gridLines: {
  9521. display: true,
  9522. color: 'rgba(0,0,0,0.1)',
  9523. lineWidth: 1,
  9524. drawBorder: true,
  9525. drawOnChartArea: true,
  9526. drawTicks: true,
  9527. tickMarkLength: 10,
  9528. zeroLineWidth: 1,
  9529. zeroLineColor: 'rgba(0,0,0,0.25)',
  9530. zeroLineBorderDash: [],
  9531. zeroLineBorderDashOffset: 0.0,
  9532. offsetGridLines: false,
  9533. borderDash: [],
  9534. borderDashOffset: 0.0
  9535. },
  9536. // scale label
  9537. scaleLabel: {
  9538. // display property
  9539. display: false,
  9540. // actual label
  9541. labelString: '',
  9542. // top/bottom padding
  9543. padding: {
  9544. top: 4,
  9545. bottom: 4
  9546. }
  9547. },
  9548. // label settings
  9549. ticks: {
  9550. beginAtZero: false,
  9551. minRotation: 0,
  9552. maxRotation: 50,
  9553. mirror: false,
  9554. padding: 0,
  9555. reverse: false,
  9556. display: true,
  9557. autoSkip: true,
  9558. autoSkipPadding: 0,
  9559. labelOffset: 0,
  9560. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  9561. callback: core_ticks.formatters.values,
  9562. minor: {},
  9563. major: {}
  9564. }
  9565. });
  9566. /** Returns a new array containing numItems from arr */
  9567. function sample(arr, numItems) {
  9568. var result = [];
  9569. var increment = arr.length / numItems;
  9570. var i = 0;
  9571. var len = arr.length;
  9572. for (; i < len; i += increment) {
  9573. result.push(arr[Math.floor(i)]);
  9574. }
  9575. return result;
  9576. }
  9577. function getPixelForGridLine(scale, index, offsetGridLines) {
  9578. var length = scale.getTicks().length;
  9579. var validIndex = Math.min(index, length - 1);
  9580. var lineValue = scale.getPixelForTick(validIndex);
  9581. var start = scale._startPixel;
  9582. var end = scale._endPixel;
  9583. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  9584. var offset;
  9585. if (offsetGridLines) {
  9586. if (length === 1) {
  9587. offset = Math.max(lineValue - start, end - lineValue);
  9588. } else if (index === 0) {
  9589. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  9590. } else {
  9591. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  9592. }
  9593. lineValue += validIndex < index ? offset : -offset;
  9594. // Return undefined if the pixel is out of the range
  9595. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  9596. return;
  9597. }
  9598. }
  9599. return lineValue;
  9600. }
  9601. function garbageCollect(caches, length) {
  9602. helpers$1.each(caches, function(cache) {
  9603. var gc = cache.gc;
  9604. var gcLen = gc.length / 2;
  9605. var i;
  9606. if (gcLen > length) {
  9607. for (i = 0; i < gcLen; ++i) {
  9608. delete cache.data[gc[i]];
  9609. }
  9610. gc.splice(0, gcLen);
  9611. }
  9612. });
  9613. }
  9614. /**
  9615. * Returns {width, height, offset} objects for the first, last, widest, highest tick
  9616. * labels where offset indicates the anchor point offset from the top in pixels.
  9617. */
  9618. function computeLabelSizes(ctx, tickFonts, ticks, caches) {
  9619. var length = ticks.length;
  9620. var widths = [];
  9621. var heights = [];
  9622. var offsets = [];
  9623. var widestLabelSize = 0;
  9624. var highestLabelSize = 0;
  9625. var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
  9626. for (i = 0; i < length; ++i) {
  9627. label = ticks[i].label;
  9628. tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
  9629. ctx.font = fontString = tickFont.string;
  9630. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  9631. lineHeight = tickFont.lineHeight;
  9632. width = height = 0;
  9633. // Undefined labels and arrays should not be measured
  9634. if (!isNullOrUndef(label) && !isArray(label)) {
  9635. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);
  9636. height = lineHeight;
  9637. } else if (isArray(label)) {
  9638. // if it is an array let's measure each element
  9639. for (j = 0, jlen = label.length; j < jlen; ++j) {
  9640. nestedLabel = label[j];
  9641. // Undefined labels and arrays should not be measured
  9642. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  9643. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  9644. height += lineHeight;
  9645. }
  9646. }
  9647. }
  9648. widths.push(width);
  9649. heights.push(height);
  9650. offsets.push(lineHeight / 2);
  9651. widestLabelSize = Math.max(width, widestLabelSize);
  9652. highestLabelSize = Math.max(height, highestLabelSize);
  9653. }
  9654. garbageCollect(caches, length);
  9655. widest = widths.indexOf(widestLabelSize);
  9656. highest = heights.indexOf(highestLabelSize);
  9657. function valueAt(idx) {
  9658. return {
  9659. width: widths[idx] || 0,
  9660. height: heights[idx] || 0,
  9661. offset: offsets[idx] || 0
  9662. };
  9663. }
  9664. return {
  9665. first: valueAt(0),
  9666. last: valueAt(length - 1),
  9667. widest: valueAt(widest),
  9668. highest: valueAt(highest)
  9669. };
  9670. }
  9671. function getTickMarkLength(options) {
  9672. return options.drawTicks ? options.tickMarkLength : 0;
  9673. }
  9674. function getScaleLabelHeight(options) {
  9675. var font, padding;
  9676. if (!options.display) {
  9677. return 0;
  9678. }
  9679. font = helpers$1.options._parseFont(options);
  9680. padding = helpers$1.options.toPadding(options.padding);
  9681. return font.lineHeight + padding.height;
  9682. }
  9683. function parseFontOptions(options, nestedOpts) {
  9684. return helpers$1.extend(helpers$1.options._parseFont({
  9685. fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),
  9686. fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),
  9687. fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),
  9688. lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)
  9689. }), {
  9690. color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])
  9691. });
  9692. }
  9693. function parseTickFontOptions(options) {
  9694. var minor = parseFontOptions(options, options.minor);
  9695. var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
  9696. return {minor: minor, major: major};
  9697. }
  9698. function nonSkipped(ticksToFilter) {
  9699. var filtered = [];
  9700. var item, index, len;
  9701. for (index = 0, len = ticksToFilter.length; index < len; ++index) {
  9702. item = ticksToFilter[index];
  9703. if (typeof item._index !== 'undefined') {
  9704. filtered.push(item);
  9705. }
  9706. }
  9707. return filtered;
  9708. }
  9709. function getEvenSpacing(arr) {
  9710. var len = arr.length;
  9711. var i, diff;
  9712. if (len < 2) {
  9713. return false;
  9714. }
  9715. for (diff = arr[0], i = 1; i < len; ++i) {
  9716. if (arr[i] - arr[i - 1] !== diff) {
  9717. return false;
  9718. }
  9719. }
  9720. return diff;
  9721. }
  9722. function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
  9723. var evenMajorSpacing = getEvenSpacing(majorIndices);
  9724. var spacing = (ticks.length - 1) / ticksLimit;
  9725. var factors, factor, i, ilen;
  9726. // If the major ticks are evenly spaced apart, place the minor ticks
  9727. // so that they divide the major ticks into even chunks
  9728. if (!evenMajorSpacing) {
  9729. return Math.max(spacing, 1);
  9730. }
  9731. factors = helpers$1.math._factorize(evenMajorSpacing);
  9732. for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
  9733. factor = factors[i];
  9734. if (factor > spacing) {
  9735. return factor;
  9736. }
  9737. }
  9738. return Math.max(spacing, 1);
  9739. }
  9740. function getMajorIndices(ticks) {
  9741. var result = [];
  9742. var i, ilen;
  9743. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  9744. if (ticks[i].major) {
  9745. result.push(i);
  9746. }
  9747. }
  9748. return result;
  9749. }
  9750. function skipMajors(ticks, majorIndices, spacing) {
  9751. var count = 0;
  9752. var next = majorIndices[0];
  9753. var i, tick;
  9754. spacing = Math.ceil(spacing);
  9755. for (i = 0; i < ticks.length; i++) {
  9756. tick = ticks[i];
  9757. if (i === next) {
  9758. tick._index = i;
  9759. count++;
  9760. next = majorIndices[count * spacing];
  9761. } else {
  9762. delete tick.label;
  9763. }
  9764. }
  9765. }
  9766. function skip(ticks, spacing, majorStart, majorEnd) {
  9767. var start = valueOrDefault$a(majorStart, 0);
  9768. var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);
  9769. var count = 0;
  9770. var length, i, tick, next;
  9771. spacing = Math.ceil(spacing);
  9772. if (majorEnd) {
  9773. length = majorEnd - majorStart;
  9774. spacing = length / Math.floor(length / spacing);
  9775. }
  9776. next = start;
  9777. while (next < 0) {
  9778. count++;
  9779. next = Math.round(start + count * spacing);
  9780. }
  9781. for (i = Math.max(start, 0); i < end; i++) {
  9782. tick = ticks[i];
  9783. if (i === next) {
  9784. tick._index = i;
  9785. count++;
  9786. next = Math.round(start + count * spacing);
  9787. } else {
  9788. delete tick.label;
  9789. }
  9790. }
  9791. }
  9792. var Scale = core_element.extend({
  9793. zeroLineIndex: 0,
  9794. /**
  9795. * Get the padding needed for the scale
  9796. * @method getPadding
  9797. * @private
  9798. * @returns {Padding} the necessary padding
  9799. */
  9800. getPadding: function() {
  9801. var me = this;
  9802. return {
  9803. left: me.paddingLeft || 0,
  9804. top: me.paddingTop || 0,
  9805. right: me.paddingRight || 0,
  9806. bottom: me.paddingBottom || 0
  9807. };
  9808. },
  9809. /**
  9810. * Returns the scale tick objects ({label, major})
  9811. * @since 2.7
  9812. */
  9813. getTicks: function() {
  9814. return this._ticks;
  9815. },
  9816. /**
  9817. * @private
  9818. */
  9819. _getLabels: function() {
  9820. var data = this.chart.data;
  9821. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  9822. },
  9823. // These methods are ordered by lifecyle. Utilities then follow.
  9824. // Any function defined here is inherited by all scale types.
  9825. // Any function can be extended by the scale type
  9826. /**
  9827. * Provided for backward compatibility, not available anymore
  9828. * @function Chart.Scale.mergeTicksOptions
  9829. * @deprecated since version 2.8.0
  9830. * @todo remove at version 3
  9831. */
  9832. mergeTicksOptions: function() {
  9833. // noop
  9834. },
  9835. beforeUpdate: function() {
  9836. helpers$1.callback(this.options.beforeUpdate, [this]);
  9837. },
  9838. /**
  9839. * @param {number} maxWidth - the max width in pixels
  9840. * @param {number} maxHeight - the max height in pixels
  9841. * @param {object} margins - the space between the edge of the other scales and edge of the chart
  9842. * This space comes from two sources:
  9843. * - padding - space that's required to show the labels at the edges of the scale
  9844. * - thickness of scales or legends in another orientation
  9845. */
  9846. update: function(maxWidth, maxHeight, margins) {
  9847. var me = this;
  9848. var tickOpts = me.options.ticks;
  9849. var sampleSize = tickOpts.sampleSize;
  9850. var i, ilen, labels, ticks, samplingEnabled;
  9851. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  9852. me.beforeUpdate();
  9853. // Absorb the master measurements
  9854. me.maxWidth = maxWidth;
  9855. me.maxHeight = maxHeight;
  9856. me.margins = helpers$1.extend({
  9857. left: 0,
  9858. right: 0,
  9859. top: 0,
  9860. bottom: 0
  9861. }, margins);
  9862. me._ticks = null;
  9863. me.ticks = null;
  9864. me._labelSizes = null;
  9865. me._maxLabelLines = 0;
  9866. me.longestLabelWidth = 0;
  9867. me.longestTextCache = me.longestTextCache || {};
  9868. me._gridLineItems = null;
  9869. me._labelItems = null;
  9870. // Dimensions
  9871. me.beforeSetDimensions();
  9872. me.setDimensions();
  9873. me.afterSetDimensions();
  9874. // Data min/max
  9875. me.beforeDataLimits();
  9876. me.determineDataLimits();
  9877. me.afterDataLimits();
  9878. // Ticks - `this.ticks` is now DEPRECATED!
  9879. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  9880. // and must not be accessed directly from outside this class. `this.ticks` being
  9881. // around for long time and not marked as private, we can't change its structure
  9882. // without unexpected breaking changes. If you need to access the scale ticks,
  9883. // use scale.getTicks() instead.
  9884. me.beforeBuildTicks();
  9885. // New implementations should return an array of objects but for BACKWARD COMPAT,
  9886. // we still support no return (`this.ticks` internally set by calling this method).
  9887. ticks = me.buildTicks() || [];
  9888. // Allow modification of ticks in callback.
  9889. ticks = me.afterBuildTicks(ticks) || ticks;
  9890. // Ensure ticks contains ticks in new tick format
  9891. if ((!ticks || !ticks.length) && me.ticks) {
  9892. ticks = [];
  9893. for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
  9894. ticks.push({
  9895. value: me.ticks[i],
  9896. major: false
  9897. });
  9898. }
  9899. }
  9900. me._ticks = ticks;
  9901. // Compute tick rotation and fit using a sampled subset of labels
  9902. // We generally don't need to compute the size of every single label for determining scale size
  9903. samplingEnabled = sampleSize < ticks.length;
  9904. labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);
  9905. // _configure is called twice, once here, once from core.controller.updateLayout.
  9906. // Here we haven't been positioned yet, but dimensions are correct.
  9907. // Variables set in _configure are needed for calculateTickRotation, and
  9908. // it's ok that coordinates are not correct there, only dimensions matter.
  9909. me._configure();
  9910. // Tick Rotation
  9911. me.beforeCalculateTickRotation();
  9912. me.calculateTickRotation();
  9913. me.afterCalculateTickRotation();
  9914. me.beforeFit();
  9915. me.fit();
  9916. me.afterFit();
  9917. // Auto-skip
  9918. me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;
  9919. if (samplingEnabled) {
  9920. // Generate labels using all non-skipped ticks
  9921. labels = me._convertTicksToLabels(me._ticksToDraw);
  9922. }
  9923. me.ticks = labels; // BACKWARD COMPATIBILITY
  9924. // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
  9925. me.afterUpdate();
  9926. // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
  9927. // make maxWidth and maxHeight private
  9928. return me.minSize;
  9929. },
  9930. /**
  9931. * @private
  9932. */
  9933. _configure: function() {
  9934. var me = this;
  9935. var reversePixels = me.options.ticks.reverse;
  9936. var startPixel, endPixel;
  9937. if (me.isHorizontal()) {
  9938. startPixel = me.left;
  9939. endPixel = me.right;
  9940. } else {
  9941. startPixel = me.top;
  9942. endPixel = me.bottom;
  9943. // by default vertical scales are from bottom to top, so pixels are reversed
  9944. reversePixels = !reversePixels;
  9945. }
  9946. me._startPixel = startPixel;
  9947. me._endPixel = endPixel;
  9948. me._reversePixels = reversePixels;
  9949. me._length = endPixel - startPixel;
  9950. },
  9951. afterUpdate: function() {
  9952. helpers$1.callback(this.options.afterUpdate, [this]);
  9953. },
  9954. //
  9955. beforeSetDimensions: function() {
  9956. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  9957. },
  9958. setDimensions: function() {
  9959. var me = this;
  9960. // Set the unconstrained dimension before label rotation
  9961. if (me.isHorizontal()) {
  9962. // Reset position before calculating rotation
  9963. me.width = me.maxWidth;
  9964. me.left = 0;
  9965. me.right = me.width;
  9966. } else {
  9967. me.height = me.maxHeight;
  9968. // Reset position before calculating rotation
  9969. me.top = 0;
  9970. me.bottom = me.height;
  9971. }
  9972. // Reset padding
  9973. me.paddingLeft = 0;
  9974. me.paddingTop = 0;
  9975. me.paddingRight = 0;
  9976. me.paddingBottom = 0;
  9977. },
  9978. afterSetDimensions: function() {
  9979. helpers$1.callback(this.options.afterSetDimensions, [this]);
  9980. },
  9981. // Data limits
  9982. beforeDataLimits: function() {
  9983. helpers$1.callback(this.options.beforeDataLimits, [this]);
  9984. },
  9985. determineDataLimits: helpers$1.noop,
  9986. afterDataLimits: function() {
  9987. helpers$1.callback(this.options.afterDataLimits, [this]);
  9988. },
  9989. //
  9990. beforeBuildTicks: function() {
  9991. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  9992. },
  9993. buildTicks: helpers$1.noop,
  9994. afterBuildTicks: function(ticks) {
  9995. var me = this;
  9996. // ticks is empty for old axis implementations here
  9997. if (isArray(ticks) && ticks.length) {
  9998. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  9999. }
  10000. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  10001. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  10002. return ticks;
  10003. },
  10004. beforeTickToLabelConversion: function() {
  10005. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  10006. },
  10007. convertTicksToLabels: function() {
  10008. var me = this;
  10009. // Convert ticks to strings
  10010. var tickOpts = me.options.ticks;
  10011. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  10012. },
  10013. afterTickToLabelConversion: function() {
  10014. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  10015. },
  10016. //
  10017. beforeCalculateTickRotation: function() {
  10018. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  10019. },
  10020. calculateTickRotation: function() {
  10021. var me = this;
  10022. var options = me.options;
  10023. var tickOpts = options.ticks;
  10024. var numTicks = me.getTicks().length;
  10025. var minRotation = tickOpts.minRotation || 0;
  10026. var maxRotation = tickOpts.maxRotation;
  10027. var labelRotation = minRotation;
  10028. var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
  10029. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  10030. me.labelRotation = minRotation;
  10031. return;
  10032. }
  10033. labelSizes = me._getLabelSizes();
  10034. maxLabelWidth = labelSizes.widest.width;
  10035. maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
  10036. // Estimate the width of each grid based on the canvas width, the maximum
  10037. // label width and the number of tick intervals
  10038. maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
  10039. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  10040. // Allow 3 pixels x2 padding either side for label readability
  10041. if (maxLabelWidth + 6 > tickWidth) {
  10042. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  10043. maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
  10044. - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
  10045. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  10046. labelRotation = helpers$1.toDegrees(Math.min(
  10047. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  10048. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  10049. ));
  10050. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  10051. }
  10052. me.labelRotation = labelRotation;
  10053. },
  10054. afterCalculateTickRotation: function() {
  10055. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  10056. },
  10057. //
  10058. beforeFit: function() {
  10059. helpers$1.callback(this.options.beforeFit, [this]);
  10060. },
  10061. fit: function() {
  10062. var me = this;
  10063. // Reset
  10064. var minSize = me.minSize = {
  10065. width: 0,
  10066. height: 0
  10067. };
  10068. var chart = me.chart;
  10069. var opts = me.options;
  10070. var tickOpts = opts.ticks;
  10071. var scaleLabelOpts = opts.scaleLabel;
  10072. var gridLineOpts = opts.gridLines;
  10073. var display = me._isVisible();
  10074. var isBottom = opts.position === 'bottom';
  10075. var isHorizontal = me.isHorizontal();
  10076. // Width
  10077. if (isHorizontal) {
  10078. minSize.width = me.maxWidth;
  10079. } else if (display) {
  10080. minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10081. }
  10082. // height
  10083. if (!isHorizontal) {
  10084. minSize.height = me.maxHeight; // fill all the height
  10085. } else if (display) {
  10086. minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10087. }
  10088. // Don't bother fitting the ticks if we are not showing the labels
  10089. if (tickOpts.display && display) {
  10090. var tickFonts = parseTickFontOptions(tickOpts);
  10091. var labelSizes = me._getLabelSizes();
  10092. var firstLabelSize = labelSizes.first;
  10093. var lastLabelSize = labelSizes.last;
  10094. var widestLabelSize = labelSizes.widest;
  10095. var highestLabelSize = labelSizes.highest;
  10096. var lineSpace = tickFonts.minor.lineHeight * 0.4;
  10097. var tickPadding = tickOpts.padding;
  10098. if (isHorizontal) {
  10099. // A horizontal axis is more constrained by the height.
  10100. var isRotated = me.labelRotation !== 0;
  10101. var angleRadians = helpers$1.toRadians(me.labelRotation);
  10102. var cosRotation = Math.cos(angleRadians);
  10103. var sinRotation = Math.sin(angleRadians);
  10104. var labelHeight = sinRotation * widestLabelSize.width
  10105. + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
  10106. + (isRotated ? 0 : lineSpace); // padding
  10107. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  10108. var offsetLeft = me.getPixelForTick(0) - me.left;
  10109. var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
  10110. var paddingLeft, paddingRight;
  10111. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  10112. // which means that the right padding is dominated by the font height
  10113. if (isRotated) {
  10114. paddingLeft = isBottom ?
  10115. cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
  10116. sinRotation * (firstLabelSize.height - firstLabelSize.offset);
  10117. paddingRight = isBottom ?
  10118. sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
  10119. cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
  10120. } else {
  10121. paddingLeft = firstLabelSize.width / 2;
  10122. paddingRight = lastLabelSize.width / 2;
  10123. }
  10124. // Adjust padding taking into account changes in offsets
  10125. // and add 3 px to move away from canvas edges
  10126. me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
  10127. me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
  10128. } else {
  10129. // A vertical axis is more constrained by the width. Labels are the
  10130. // dominant factor here, so get that length first and account for padding
  10131. var labelWidth = tickOpts.mirror ? 0 :
  10132. // use lineSpace for consistency with horizontal axis
  10133. // tickPadding is not implemented for horizontal
  10134. widestLabelSize.width + tickPadding + lineSpace;
  10135. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
  10136. me.paddingTop = firstLabelSize.height / 2;
  10137. me.paddingBottom = lastLabelSize.height / 2;
  10138. }
  10139. }
  10140. me.handleMargins();
  10141. if (isHorizontal) {
  10142. me.width = me._length = chart.width - me.margins.left - me.margins.right;
  10143. me.height = minSize.height;
  10144. } else {
  10145. me.width = minSize.width;
  10146. me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
  10147. }
  10148. },
  10149. /**
  10150. * Handle margins and padding interactions
  10151. * @private
  10152. */
  10153. handleMargins: function() {
  10154. var me = this;
  10155. if (me.margins) {
  10156. me.margins.left = Math.max(me.paddingLeft, me.margins.left);
  10157. me.margins.top = Math.max(me.paddingTop, me.margins.top);
  10158. me.margins.right = Math.max(me.paddingRight, me.margins.right);
  10159. me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
  10160. }
  10161. },
  10162. afterFit: function() {
  10163. helpers$1.callback(this.options.afterFit, [this]);
  10164. },
  10165. // Shared Methods
  10166. isHorizontal: function() {
  10167. var pos = this.options.position;
  10168. return pos === 'top' || pos === 'bottom';
  10169. },
  10170. isFullWidth: function() {
  10171. return this.options.fullWidth;
  10172. },
  10173. // 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
  10174. getRightValue: function(rawValue) {
  10175. // Null and undefined values first
  10176. if (isNullOrUndef(rawValue)) {
  10177. return NaN;
  10178. }
  10179. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  10180. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  10181. return NaN;
  10182. }
  10183. // If it is in fact an object, dive in one more level
  10184. if (rawValue) {
  10185. if (this.isHorizontal()) {
  10186. if (rawValue.x !== undefined) {
  10187. return this.getRightValue(rawValue.x);
  10188. }
  10189. } else if (rawValue.y !== undefined) {
  10190. return this.getRightValue(rawValue.y);
  10191. }
  10192. }
  10193. // Value is good, return it
  10194. return rawValue;
  10195. },
  10196. _convertTicksToLabels: function(ticks) {
  10197. var me = this;
  10198. var labels, i, ilen;
  10199. me.ticks = ticks.map(function(tick) {
  10200. return tick.value;
  10201. });
  10202. me.beforeTickToLabelConversion();
  10203. // New implementations should return the formatted tick labels but for BACKWARD
  10204. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  10205. // this method and supposed to contain only string values).
  10206. labels = me.convertTicksToLabels(ticks) || me.ticks;
  10207. me.afterTickToLabelConversion();
  10208. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  10209. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10210. ticks[i].label = labels[i];
  10211. }
  10212. return labels;
  10213. },
  10214. /**
  10215. * @private
  10216. */
  10217. _getLabelSizes: function() {
  10218. var me = this;
  10219. var labelSizes = me._labelSizes;
  10220. if (!labelSizes) {
  10221. me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
  10222. me.longestLabelWidth = labelSizes.widest.width;
  10223. }
  10224. return labelSizes;
  10225. },
  10226. /**
  10227. * @private
  10228. */
  10229. _parseValue: function(value) {
  10230. var start, end, min, max;
  10231. if (isArray(value)) {
  10232. start = +this.getRightValue(value[0]);
  10233. end = +this.getRightValue(value[1]);
  10234. min = Math.min(start, end);
  10235. max = Math.max(start, end);
  10236. } else {
  10237. value = +this.getRightValue(value);
  10238. start = undefined;
  10239. end = value;
  10240. min = value;
  10241. max = value;
  10242. }
  10243. return {
  10244. min: min,
  10245. max: max,
  10246. start: start,
  10247. end: end
  10248. };
  10249. },
  10250. /**
  10251. * @private
  10252. */
  10253. _getScaleLabel: function(rawValue) {
  10254. var v = this._parseValue(rawValue);
  10255. if (v.start !== undefined) {
  10256. return '[' + v.start + ', ' + v.end + ']';
  10257. }
  10258. return +this.getRightValue(rawValue);
  10259. },
  10260. /**
  10261. * Used to get the value to display in the tooltip for the data at the given index
  10262. * @param index
  10263. * @param datasetIndex
  10264. */
  10265. getLabelForIndex: helpers$1.noop,
  10266. /**
  10267. * Returns the location of the given data point. Value can either be an index or a numerical value
  10268. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10269. * @param value
  10270. * @param index
  10271. * @param datasetIndex
  10272. */
  10273. getPixelForValue: helpers$1.noop,
  10274. /**
  10275. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  10276. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10277. * @param pixel
  10278. */
  10279. getValueForPixel: helpers$1.noop,
  10280. /**
  10281. * Returns the location of the tick at the given index
  10282. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10283. */
  10284. getPixelForTick: function(index) {
  10285. var me = this;
  10286. var offset = me.options.offset;
  10287. var numTicks = me._ticks.length;
  10288. var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
  10289. return index < 0 || index > numTicks - 1
  10290. ? null
  10291. : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
  10292. },
  10293. /**
  10294. * Utility for getting the pixel location of a percentage of scale
  10295. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10296. */
  10297. getPixelForDecimal: function(decimal) {
  10298. var me = this;
  10299. if (me._reversePixels) {
  10300. decimal = 1 - decimal;
  10301. }
  10302. return me._startPixel + decimal * me._length;
  10303. },
  10304. getDecimalForPixel: function(pixel) {
  10305. var decimal = (pixel - this._startPixel) / this._length;
  10306. return this._reversePixels ? 1 - decimal : decimal;
  10307. },
  10308. /**
  10309. * Returns the pixel for the minimum chart value
  10310. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10311. */
  10312. getBasePixel: function() {
  10313. return this.getPixelForValue(this.getBaseValue());
  10314. },
  10315. getBaseValue: function() {
  10316. var me = this;
  10317. var min = me.min;
  10318. var max = me.max;
  10319. return me.beginAtZero ? 0 :
  10320. min < 0 && max < 0 ? max :
  10321. min > 0 && max > 0 ? min :
  10322. 0;
  10323. },
  10324. /**
  10325. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  10326. * @private
  10327. */
  10328. _autoSkip: function(ticks) {
  10329. var me = this;
  10330. var tickOpts = me.options.ticks;
  10331. var axisLength = me._length;
  10332. var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;
  10333. var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  10334. var numMajorIndices = majorIndices.length;
  10335. var first = majorIndices[0];
  10336. var last = majorIndices[numMajorIndices - 1];
  10337. var i, ilen, spacing, avgMajorSpacing;
  10338. // If there are too many major ticks to display them all
  10339. if (numMajorIndices > ticksLimit) {
  10340. skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);
  10341. return nonSkipped(ticks);
  10342. }
  10343. spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
  10344. if (numMajorIndices > 0) {
  10345. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  10346. skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);
  10347. }
  10348. avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;
  10349. skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  10350. skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  10351. return nonSkipped(ticks);
  10352. }
  10353. skip(ticks, spacing);
  10354. return nonSkipped(ticks);
  10355. },
  10356. /**
  10357. * @private
  10358. */
  10359. _tickSize: function() {
  10360. var me = this;
  10361. var optionTicks = me.options.ticks;
  10362. // Calculate space needed by label in axis direction.
  10363. var rot = helpers$1.toRadians(me.labelRotation);
  10364. var cos = Math.abs(Math.cos(rot));
  10365. var sin = Math.abs(Math.sin(rot));
  10366. var labelSizes = me._getLabelSizes();
  10367. var padding = optionTicks.autoSkipPadding || 0;
  10368. var w = labelSizes ? labelSizes.widest.width + padding : 0;
  10369. var h = labelSizes ? labelSizes.highest.height + padding : 0;
  10370. // Calculate space needed for 1 tick in axis direction.
  10371. return me.isHorizontal()
  10372. ? h * cos > w * sin ? w / cos : h / sin
  10373. : h * sin < w * cos ? h / cos : w / sin;
  10374. },
  10375. /**
  10376. * @private
  10377. */
  10378. _isVisible: function() {
  10379. var me = this;
  10380. var chart = me.chart;
  10381. var display = me.options.display;
  10382. var i, ilen, meta;
  10383. if (display !== 'auto') {
  10384. return !!display;
  10385. }
  10386. // When 'auto', the scale is visible if at least one associated dataset is visible.
  10387. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  10388. if (chart.isDatasetVisible(i)) {
  10389. meta = chart.getDatasetMeta(i);
  10390. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  10391. return true;
  10392. }
  10393. }
  10394. }
  10395. return false;
  10396. },
  10397. /**
  10398. * @private
  10399. */
  10400. _computeGridLineItems: function(chartArea) {
  10401. var me = this;
  10402. var chart = me.chart;
  10403. var options = me.options;
  10404. var gridLines = options.gridLines;
  10405. var position = options.position;
  10406. var offsetGridLines = gridLines.offsetGridLines;
  10407. var isHorizontal = me.isHorizontal();
  10408. var ticks = me._ticksToDraw;
  10409. var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
  10410. var tl = getTickMarkLength(gridLines);
  10411. var items = [];
  10412. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10413. var axisHalfWidth = axisWidth / 2;
  10414. var alignPixel = helpers$1._alignPixel;
  10415. var alignBorderValue = function(pixel) {
  10416. return alignPixel(chart, pixel, axisWidth);
  10417. };
  10418. var borderValue, i, tick, lineValue, alignedLineValue;
  10419. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
  10420. if (position === 'top') {
  10421. borderValue = alignBorderValue(me.bottom);
  10422. ty1 = me.bottom - tl;
  10423. ty2 = borderValue - axisHalfWidth;
  10424. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  10425. y2 = chartArea.bottom;
  10426. } else if (position === 'bottom') {
  10427. borderValue = alignBorderValue(me.top);
  10428. y1 = chartArea.top;
  10429. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  10430. ty1 = borderValue + axisHalfWidth;
  10431. ty2 = me.top + tl;
  10432. } else if (position === 'left') {
  10433. borderValue = alignBorderValue(me.right);
  10434. tx1 = me.right - tl;
  10435. tx2 = borderValue - axisHalfWidth;
  10436. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  10437. x2 = chartArea.right;
  10438. } else {
  10439. borderValue = alignBorderValue(me.left);
  10440. x1 = chartArea.left;
  10441. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  10442. tx1 = borderValue + axisHalfWidth;
  10443. tx2 = me.left + tl;
  10444. }
  10445. for (i = 0; i < ticksLength; ++i) {
  10446. tick = ticks[i] || {};
  10447. // autoskipper skipped this tick (#4635)
  10448. if (isNullOrUndef(tick.label) && i < ticks.length) {
  10449. continue;
  10450. }
  10451. if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
  10452. // Draw the first index specially
  10453. lineWidth = gridLines.zeroLineWidth;
  10454. lineColor = gridLines.zeroLineColor;
  10455. borderDash = gridLines.zeroLineBorderDash || [];
  10456. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  10457. } else {
  10458. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);
  10459. lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');
  10460. borderDash = gridLines.borderDash || [];
  10461. borderDashOffset = gridLines.borderDashOffset || 0.0;
  10462. }
  10463. lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
  10464. // Skip if the pixel is out of the range
  10465. if (lineValue === undefined) {
  10466. continue;
  10467. }
  10468. alignedLineValue = alignPixel(chart, lineValue, lineWidth);
  10469. if (isHorizontal) {
  10470. tx1 = tx2 = x1 = x2 = alignedLineValue;
  10471. } else {
  10472. ty1 = ty2 = y1 = y2 = alignedLineValue;
  10473. }
  10474. items.push({
  10475. tx1: tx1,
  10476. ty1: ty1,
  10477. tx2: tx2,
  10478. ty2: ty2,
  10479. x1: x1,
  10480. y1: y1,
  10481. x2: x2,
  10482. y2: y2,
  10483. width: lineWidth,
  10484. color: lineColor,
  10485. borderDash: borderDash,
  10486. borderDashOffset: borderDashOffset,
  10487. });
  10488. }
  10489. items.ticksLength = ticksLength;
  10490. items.borderValue = borderValue;
  10491. return items;
  10492. },
  10493. /**
  10494. * @private
  10495. */
  10496. _computeLabelItems: function() {
  10497. var me = this;
  10498. var options = me.options;
  10499. var optionTicks = options.ticks;
  10500. var position = options.position;
  10501. var isMirrored = optionTicks.mirror;
  10502. var isHorizontal = me.isHorizontal();
  10503. var ticks = me._ticksToDraw;
  10504. var fonts = parseTickFontOptions(optionTicks);
  10505. var tickPadding = optionTicks.padding;
  10506. var tl = getTickMarkLength(options.gridLines);
  10507. var rotation = -helpers$1.toRadians(me.labelRotation);
  10508. var items = [];
  10509. var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  10510. if (position === 'top') {
  10511. y = me.bottom - tl - tickPadding;
  10512. textAlign = !rotation ? 'center' : 'left';
  10513. } else if (position === 'bottom') {
  10514. y = me.top + tl + tickPadding;
  10515. textAlign = !rotation ? 'center' : 'right';
  10516. } else if (position === 'left') {
  10517. x = me.right - (isMirrored ? 0 : tl) - tickPadding;
  10518. textAlign = isMirrored ? 'left' : 'right';
  10519. } else {
  10520. x = me.left + (isMirrored ? 0 : tl) + tickPadding;
  10521. textAlign = isMirrored ? 'right' : 'left';
  10522. }
  10523. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10524. tick = ticks[i];
  10525. label = tick.label;
  10526. // autoskipper skipped this tick (#4635)
  10527. if (isNullOrUndef(label)) {
  10528. continue;
  10529. }
  10530. pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
  10531. font = tick.major ? fonts.major : fonts.minor;
  10532. lineHeight = font.lineHeight;
  10533. lineCount = isArray(label) ? label.length : 1;
  10534. if (isHorizontal) {
  10535. x = pixel;
  10536. textOffset = position === 'top'
  10537. ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight
  10538. : (!rotation ? 0.5 : 0) * lineHeight;
  10539. } else {
  10540. y = pixel;
  10541. textOffset = (1 - lineCount) * lineHeight / 2;
  10542. }
  10543. items.push({
  10544. x: x,
  10545. y: y,
  10546. rotation: rotation,
  10547. label: label,
  10548. font: font,
  10549. textOffset: textOffset,
  10550. textAlign: textAlign
  10551. });
  10552. }
  10553. return items;
  10554. },
  10555. /**
  10556. * @private
  10557. */
  10558. _drawGrid: function(chartArea) {
  10559. var me = this;
  10560. var gridLines = me.options.gridLines;
  10561. if (!gridLines.display) {
  10562. return;
  10563. }
  10564. var ctx = me.ctx;
  10565. var chart = me.chart;
  10566. var alignPixel = helpers$1._alignPixel;
  10567. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10568. var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  10569. var width, color, i, ilen, item;
  10570. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10571. item = items[i];
  10572. width = item.width;
  10573. color = item.color;
  10574. if (width && color) {
  10575. ctx.save();
  10576. ctx.lineWidth = width;
  10577. ctx.strokeStyle = color;
  10578. if (ctx.setLineDash) {
  10579. ctx.setLineDash(item.borderDash);
  10580. ctx.lineDashOffset = item.borderDashOffset;
  10581. }
  10582. ctx.beginPath();
  10583. if (gridLines.drawTicks) {
  10584. ctx.moveTo(item.tx1, item.ty1);
  10585. ctx.lineTo(item.tx2, item.ty2);
  10586. }
  10587. if (gridLines.drawOnChartArea) {
  10588. ctx.moveTo(item.x1, item.y1);
  10589. ctx.lineTo(item.x2, item.y2);
  10590. }
  10591. ctx.stroke();
  10592. ctx.restore();
  10593. }
  10594. }
  10595. if (axisWidth) {
  10596. // Draw the line at the edge of the axis
  10597. var firstLineWidth = axisWidth;
  10598. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);
  10599. var borderValue = items.borderValue;
  10600. var x1, x2, y1, y2;
  10601. if (me.isHorizontal()) {
  10602. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  10603. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  10604. y1 = y2 = borderValue;
  10605. } else {
  10606. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  10607. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  10608. x1 = x2 = borderValue;
  10609. }
  10610. ctx.lineWidth = axisWidth;
  10611. ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  10612. ctx.beginPath();
  10613. ctx.moveTo(x1, y1);
  10614. ctx.lineTo(x2, y2);
  10615. ctx.stroke();
  10616. }
  10617. },
  10618. /**
  10619. * @private
  10620. */
  10621. _drawLabels: function() {
  10622. var me = this;
  10623. var optionTicks = me.options.ticks;
  10624. if (!optionTicks.display) {
  10625. return;
  10626. }
  10627. var ctx = me.ctx;
  10628. var items = me._labelItems || (me._labelItems = me._computeLabelItems());
  10629. var i, j, ilen, jlen, item, tickFont, label, y;
  10630. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10631. item = items[i];
  10632. tickFont = item.font;
  10633. // Make sure we draw text in the correct color and font
  10634. ctx.save();
  10635. ctx.translate(item.x, item.y);
  10636. ctx.rotate(item.rotation);
  10637. ctx.font = tickFont.string;
  10638. ctx.fillStyle = tickFont.color;
  10639. ctx.textBaseline = 'middle';
  10640. ctx.textAlign = item.textAlign;
  10641. label = item.label;
  10642. y = item.textOffset;
  10643. if (isArray(label)) {
  10644. for (j = 0, jlen = label.length; j < jlen; ++j) {
  10645. // We just make sure the multiline element is a string here..
  10646. ctx.fillText('' + label[j], 0, y);
  10647. y += tickFont.lineHeight;
  10648. }
  10649. } else {
  10650. ctx.fillText(label, 0, y);
  10651. }
  10652. ctx.restore();
  10653. }
  10654. },
  10655. /**
  10656. * @private
  10657. */
  10658. _drawTitle: function() {
  10659. var me = this;
  10660. var ctx = me.ctx;
  10661. var options = me.options;
  10662. var scaleLabel = options.scaleLabel;
  10663. if (!scaleLabel.display) {
  10664. return;
  10665. }
  10666. var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);
  10667. var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);
  10668. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  10669. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  10670. var position = options.position;
  10671. var rotation = 0;
  10672. var scaleLabelX, scaleLabelY;
  10673. if (me.isHorizontal()) {
  10674. scaleLabelX = me.left + me.width / 2; // midpoint of the width
  10675. scaleLabelY = position === 'bottom'
  10676. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  10677. : me.top + halfLineHeight + scaleLabelPadding.top;
  10678. } else {
  10679. var isLeft = position === 'left';
  10680. scaleLabelX = isLeft
  10681. ? me.left + halfLineHeight + scaleLabelPadding.top
  10682. : me.right - halfLineHeight - scaleLabelPadding.top;
  10683. scaleLabelY = me.top + me.height / 2;
  10684. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  10685. }
  10686. ctx.save();
  10687. ctx.translate(scaleLabelX, scaleLabelY);
  10688. ctx.rotate(rotation);
  10689. ctx.textAlign = 'center';
  10690. ctx.textBaseline = 'middle';
  10691. ctx.fillStyle = scaleLabelFontColor; // render in correct colour
  10692. ctx.font = scaleLabelFont.string;
  10693. ctx.fillText(scaleLabel.labelString, 0, 0);
  10694. ctx.restore();
  10695. },
  10696. draw: function(chartArea) {
  10697. var me = this;
  10698. if (!me._isVisible()) {
  10699. return;
  10700. }
  10701. me._drawGrid(chartArea);
  10702. me._drawTitle();
  10703. me._drawLabels();
  10704. },
  10705. /**
  10706. * @private
  10707. */
  10708. _layers: function() {
  10709. var me = this;
  10710. var opts = me.options;
  10711. var tz = opts.ticks && opts.ticks.z || 0;
  10712. var gz = opts.gridLines && opts.gridLines.z || 0;
  10713. if (!me._isVisible() || tz === gz || me.draw !== me._draw) {
  10714. // backward compatibility: draw has been overridden by custom scale
  10715. return [{
  10716. z: tz,
  10717. draw: function() {
  10718. me.draw.apply(me, arguments);
  10719. }
  10720. }];
  10721. }
  10722. return [{
  10723. z: gz,
  10724. draw: function() {
  10725. me._drawGrid.apply(me, arguments);
  10726. me._drawTitle.apply(me, arguments);
  10727. }
  10728. }, {
  10729. z: tz,
  10730. draw: function() {
  10731. me._drawLabels.apply(me, arguments);
  10732. }
  10733. }];
  10734. },
  10735. /**
  10736. * @private
  10737. */
  10738. _getMatchingVisibleMetas: function(type) {
  10739. var me = this;
  10740. var isHorizontal = me.isHorizontal();
  10741. return me.chart._getSortedVisibleDatasetMetas()
  10742. .filter(function(meta) {
  10743. return (!type || meta.type === type)
  10744. && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);
  10745. });
  10746. }
  10747. });
  10748. Scale.prototype._draw = Scale.prototype.draw;
  10749. var core_scale = Scale;
  10750. var isNullOrUndef$1 = helpers$1.isNullOrUndef;
  10751. var defaultConfig = {
  10752. position: 'bottom'
  10753. };
  10754. var scale_category = core_scale.extend({
  10755. determineDataLimits: function() {
  10756. var me = this;
  10757. var labels = me._getLabels();
  10758. var ticksOpts = me.options.ticks;
  10759. var min = ticksOpts.min;
  10760. var max = ticksOpts.max;
  10761. var minIndex = 0;
  10762. var maxIndex = labels.length - 1;
  10763. var findIndex;
  10764. if (min !== undefined) {
  10765. // user specified min value
  10766. findIndex = labels.indexOf(min);
  10767. if (findIndex >= 0) {
  10768. minIndex = findIndex;
  10769. }
  10770. }
  10771. if (max !== undefined) {
  10772. // user specified max value
  10773. findIndex = labels.indexOf(max);
  10774. if (findIndex >= 0) {
  10775. maxIndex = findIndex;
  10776. }
  10777. }
  10778. me.minIndex = minIndex;
  10779. me.maxIndex = maxIndex;
  10780. me.min = labels[minIndex];
  10781. me.max = labels[maxIndex];
  10782. },
  10783. buildTicks: function() {
  10784. var me = this;
  10785. var labels = me._getLabels();
  10786. var minIndex = me.minIndex;
  10787. var maxIndex = me.maxIndex;
  10788. // If we are viewing some subset of labels, slice the original array
  10789. me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);
  10790. },
  10791. getLabelForIndex: function(index, datasetIndex) {
  10792. var me = this;
  10793. var chart = me.chart;
  10794. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  10795. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  10796. }
  10797. return me._getLabels()[index];
  10798. },
  10799. _configure: function() {
  10800. var me = this;
  10801. var offset = me.options.offset;
  10802. var ticks = me.ticks;
  10803. core_scale.prototype._configure.call(me);
  10804. if (!me.isHorizontal()) {
  10805. // For backward compatibility, vertical category scale reverse is inverted.
  10806. me._reversePixels = !me._reversePixels;
  10807. }
  10808. if (!ticks) {
  10809. return;
  10810. }
  10811. me._startValue = me.minIndex - (offset ? 0.5 : 0);
  10812. me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);
  10813. },
  10814. // Used to get data value locations. Value can either be an index or a numerical value
  10815. getPixelForValue: function(value, index, datasetIndex) {
  10816. var me = this;
  10817. var valueCategory, labels, idx;
  10818. if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {
  10819. value = me.chart.data.datasets[datasetIndex].data[index];
  10820. }
  10821. // If value is a data object, then index is the index in the data array,
  10822. // not the index of the scale. We need to change that.
  10823. if (!isNullOrUndef$1(value)) {
  10824. valueCategory = me.isHorizontal() ? value.x : value.y;
  10825. }
  10826. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  10827. labels = me._getLabels();
  10828. value = helpers$1.valueOrDefault(valueCategory, value);
  10829. idx = labels.indexOf(value);
  10830. index = idx !== -1 ? idx : index;
  10831. if (isNaN(index)) {
  10832. index = value;
  10833. }
  10834. }
  10835. return me.getPixelForDecimal((index - me._startValue) / me._valueRange);
  10836. },
  10837. getPixelForTick: function(index) {
  10838. var ticks = this.ticks;
  10839. return index < 0 || index > ticks.length - 1
  10840. ? null
  10841. : this.getPixelForValue(ticks[index], index + this.minIndex);
  10842. },
  10843. getValueForPixel: function(pixel) {
  10844. var me = this;
  10845. var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  10846. return Math.min(Math.max(value, 0), me.ticks.length - 1);
  10847. },
  10848. getBasePixel: function() {
  10849. return this.bottom;
  10850. }
  10851. });
  10852. // INTERNAL: static default options, registered in src/index.js
  10853. var _defaults = defaultConfig;
  10854. scale_category._defaults = _defaults;
  10855. var noop = helpers$1.noop;
  10856. var isNullOrUndef$2 = helpers$1.isNullOrUndef;
  10857. /**
  10858. * Generate a set of linear ticks
  10859. * @param generationOptions the options used to generate the ticks
  10860. * @param dataRange the range of the data
  10861. * @returns {number[]} array of tick values
  10862. */
  10863. function generateTicks(generationOptions, dataRange) {
  10864. var ticks = [];
  10865. // To get a "nice" value for the tick spacing, we will use the appropriately named
  10866. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  10867. // for details.
  10868. var MIN_SPACING = 1e-14;
  10869. var stepSize = generationOptions.stepSize;
  10870. var unit = stepSize || 1;
  10871. var maxNumSpaces = generationOptions.maxTicks - 1;
  10872. var min = generationOptions.min;
  10873. var max = generationOptions.max;
  10874. var precision = generationOptions.precision;
  10875. var rmin = dataRange.min;
  10876. var rmax = dataRange.max;
  10877. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  10878. var factor, niceMin, niceMax, numSpaces;
  10879. // Beyond MIN_SPACING floating point numbers being to lose precision
  10880. // such that we can't do the math necessary to generate ticks
  10881. if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {
  10882. return [rmin, rmax];
  10883. }
  10884. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  10885. if (numSpaces > maxNumSpaces) {
  10886. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  10887. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  10888. }
  10889. if (stepSize || isNullOrUndef$2(precision)) {
  10890. // If a precision is not specified, calculate factor based on spacing
  10891. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  10892. } else {
  10893. // If the user specified a precision, round to that number of decimal places
  10894. factor = Math.pow(10, precision);
  10895. spacing = Math.ceil(spacing * factor) / factor;
  10896. }
  10897. niceMin = Math.floor(rmin / spacing) * spacing;
  10898. niceMax = Math.ceil(rmax / spacing) * spacing;
  10899. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  10900. if (stepSize) {
  10901. // If very close to our whole number, use it.
  10902. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  10903. niceMin = min;
  10904. }
  10905. if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  10906. niceMax = max;
  10907. }
  10908. }
  10909. numSpaces = (niceMax - niceMin) / spacing;
  10910. // If very close to our rounded value, use it.
  10911. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10912. numSpaces = Math.round(numSpaces);
  10913. } else {
  10914. numSpaces = Math.ceil(numSpaces);
  10915. }
  10916. niceMin = Math.round(niceMin * factor) / factor;
  10917. niceMax = Math.round(niceMax * factor) / factor;
  10918. ticks.push(isNullOrUndef$2(min) ? niceMin : min);
  10919. for (var j = 1; j < numSpaces; ++j) {
  10920. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  10921. }
  10922. ticks.push(isNullOrUndef$2(max) ? niceMax : max);
  10923. return ticks;
  10924. }
  10925. var scale_linearbase = core_scale.extend({
  10926. getRightValue: function(value) {
  10927. if (typeof value === 'string') {
  10928. return +value;
  10929. }
  10930. return core_scale.prototype.getRightValue.call(this, value);
  10931. },
  10932. handleTickRangeOptions: function() {
  10933. var me = this;
  10934. var opts = me.options;
  10935. var tickOpts = opts.ticks;
  10936. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  10937. // do nothing since that would make the chart weird. If the user really wants a weird chart
  10938. // axis, they can manually override it
  10939. if (tickOpts.beginAtZero) {
  10940. var minSign = helpers$1.sign(me.min);
  10941. var maxSign = helpers$1.sign(me.max);
  10942. if (minSign < 0 && maxSign < 0) {
  10943. // move the top up to 0
  10944. me.max = 0;
  10945. } else if (minSign > 0 && maxSign > 0) {
  10946. // move the bottom down to 0
  10947. me.min = 0;
  10948. }
  10949. }
  10950. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  10951. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  10952. if (tickOpts.min !== undefined) {
  10953. me.min = tickOpts.min;
  10954. } else if (tickOpts.suggestedMin !== undefined) {
  10955. if (me.min === null) {
  10956. me.min = tickOpts.suggestedMin;
  10957. } else {
  10958. me.min = Math.min(me.min, tickOpts.suggestedMin);
  10959. }
  10960. }
  10961. if (tickOpts.max !== undefined) {
  10962. me.max = tickOpts.max;
  10963. } else if (tickOpts.suggestedMax !== undefined) {
  10964. if (me.max === null) {
  10965. me.max = tickOpts.suggestedMax;
  10966. } else {
  10967. me.max = Math.max(me.max, tickOpts.suggestedMax);
  10968. }
  10969. }
  10970. if (setMin !== setMax) {
  10971. // We set the min or the max but not both.
  10972. // So ensure that our range is good
  10973. // Inverted or 0 length range can happen when
  10974. // ticks.min is set, and no datasets are visible
  10975. if (me.min >= me.max) {
  10976. if (setMin) {
  10977. me.max = me.min + 1;
  10978. } else {
  10979. me.min = me.max - 1;
  10980. }
  10981. }
  10982. }
  10983. if (me.min === me.max) {
  10984. me.max++;
  10985. if (!tickOpts.beginAtZero) {
  10986. me.min--;
  10987. }
  10988. }
  10989. },
  10990. getTickLimit: function() {
  10991. var me = this;
  10992. var tickOpts = me.options.ticks;
  10993. var stepSize = tickOpts.stepSize;
  10994. var maxTicksLimit = tickOpts.maxTicksLimit;
  10995. var maxTicks;
  10996. if (stepSize) {
  10997. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  10998. } else {
  10999. maxTicks = me._computeTickLimit();
  11000. maxTicksLimit = maxTicksLimit || 11;
  11001. }
  11002. if (maxTicksLimit) {
  11003. maxTicks = Math.min(maxTicksLimit, maxTicks);
  11004. }
  11005. return maxTicks;
  11006. },
  11007. _computeTickLimit: function() {
  11008. return Number.POSITIVE_INFINITY;
  11009. },
  11010. handleDirectionalChanges: noop,
  11011. buildTicks: function() {
  11012. var me = this;
  11013. var opts = me.options;
  11014. var tickOpts = opts.ticks;
  11015. // Figure out what the max number of ticks we can support it is based on the size of
  11016. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  11017. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  11018. // the graph. Make sure we always have at least 2 ticks
  11019. var maxTicks = me.getTickLimit();
  11020. maxTicks = Math.max(2, maxTicks);
  11021. var numericGeneratorOptions = {
  11022. maxTicks: maxTicks,
  11023. min: tickOpts.min,
  11024. max: tickOpts.max,
  11025. precision: tickOpts.precision,
  11026. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  11027. };
  11028. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  11029. me.handleDirectionalChanges();
  11030. // At this point, we need to update our max and min given the tick values since we have expanded the
  11031. // range of the scale
  11032. me.max = helpers$1.max(ticks);
  11033. me.min = helpers$1.min(ticks);
  11034. if (tickOpts.reverse) {
  11035. ticks.reverse();
  11036. me.start = me.max;
  11037. me.end = me.min;
  11038. } else {
  11039. me.start = me.min;
  11040. me.end = me.max;
  11041. }
  11042. },
  11043. convertTicksToLabels: function() {
  11044. var me = this;
  11045. me.ticksAsNumbers = me.ticks.slice();
  11046. me.zeroLineIndex = me.ticks.indexOf(0);
  11047. core_scale.prototype.convertTicksToLabels.call(me);
  11048. },
  11049. _configure: function() {
  11050. var me = this;
  11051. var ticks = me.getTicks();
  11052. var start = me.min;
  11053. var end = me.max;
  11054. var offset;
  11055. core_scale.prototype._configure.call(me);
  11056. if (me.options.offset && ticks.length) {
  11057. offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  11058. start -= offset;
  11059. end += offset;
  11060. }
  11061. me._startValue = start;
  11062. me._endValue = end;
  11063. me._valueRange = end - start;
  11064. }
  11065. });
  11066. var defaultConfig$1 = {
  11067. position: 'left',
  11068. ticks: {
  11069. callback: core_ticks.formatters.linear
  11070. }
  11071. };
  11072. var DEFAULT_MIN = 0;
  11073. var DEFAULT_MAX = 1;
  11074. function getOrCreateStack(stacks, stacked, meta) {
  11075. var key = [
  11076. meta.type,
  11077. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11078. stacked === undefined && meta.stack === undefined ? meta.index : '',
  11079. meta.stack
  11080. ].join('.');
  11081. if (stacks[key] === undefined) {
  11082. stacks[key] = {
  11083. pos: [],
  11084. neg: []
  11085. };
  11086. }
  11087. return stacks[key];
  11088. }
  11089. function stackData(scale, stacks, meta, data) {
  11090. var opts = scale.options;
  11091. var stacked = opts.stacked;
  11092. var stack = getOrCreateStack(stacks, stacked, meta);
  11093. var pos = stack.pos;
  11094. var neg = stack.neg;
  11095. var ilen = data.length;
  11096. var i, value;
  11097. for (i = 0; i < ilen; ++i) {
  11098. value = scale._parseValue(data[i]);
  11099. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11100. continue;
  11101. }
  11102. pos[i] = pos[i] || 0;
  11103. neg[i] = neg[i] || 0;
  11104. if (opts.relativePoints) {
  11105. pos[i] = 100;
  11106. } else if (value.min < 0 || value.max < 0) {
  11107. neg[i] += value.min;
  11108. } else {
  11109. pos[i] += value.max;
  11110. }
  11111. }
  11112. }
  11113. function updateMinMax(scale, meta, data) {
  11114. var ilen = data.length;
  11115. var i, value;
  11116. for (i = 0; i < ilen; ++i) {
  11117. value = scale._parseValue(data[i]);
  11118. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11119. continue;
  11120. }
  11121. scale.min = Math.min(scale.min, value.min);
  11122. scale.max = Math.max(scale.max, value.max);
  11123. }
  11124. }
  11125. var scale_linear = scale_linearbase.extend({
  11126. determineDataLimits: function() {
  11127. var me = this;
  11128. var opts = me.options;
  11129. var chart = me.chart;
  11130. var datasets = chart.data.datasets;
  11131. var metasets = me._getMatchingVisibleMetas();
  11132. var hasStacks = opts.stacked;
  11133. var stacks = {};
  11134. var ilen = metasets.length;
  11135. var i, meta, data, values;
  11136. me.min = Number.POSITIVE_INFINITY;
  11137. me.max = Number.NEGATIVE_INFINITY;
  11138. if (hasStacks === undefined) {
  11139. for (i = 0; !hasStacks && i < ilen; ++i) {
  11140. meta = metasets[i];
  11141. hasStacks = meta.stack !== undefined;
  11142. }
  11143. }
  11144. for (i = 0; i < ilen; ++i) {
  11145. meta = metasets[i];
  11146. data = datasets[meta.index].data;
  11147. if (hasStacks) {
  11148. stackData(me, stacks, meta, data);
  11149. } else {
  11150. updateMinMax(me, meta, data);
  11151. }
  11152. }
  11153. helpers$1.each(stacks, function(stackValues) {
  11154. values = stackValues.pos.concat(stackValues.neg);
  11155. me.min = Math.min(me.min, helpers$1.min(values));
  11156. me.max = Math.max(me.max, helpers$1.max(values));
  11157. });
  11158. me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  11159. me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  11160. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11161. me.handleTickRangeOptions();
  11162. },
  11163. // Returns the maximum number of ticks based on the scale dimension
  11164. _computeTickLimit: function() {
  11165. var me = this;
  11166. var tickFont;
  11167. if (me.isHorizontal()) {
  11168. return Math.ceil(me.width / 40);
  11169. }
  11170. tickFont = helpers$1.options._parseFont(me.options.ticks);
  11171. return Math.ceil(me.height / tickFont.lineHeight);
  11172. },
  11173. // Called after the ticks are built. We need
  11174. handleDirectionalChanges: function() {
  11175. if (!this.isHorizontal()) {
  11176. // We are in a vertical orientation. The top value is the highest. So reverse the array
  11177. this.ticks.reverse();
  11178. }
  11179. },
  11180. getLabelForIndex: function(index, datasetIndex) {
  11181. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11182. },
  11183. // Utils
  11184. getPixelForValue: function(value) {
  11185. var me = this;
  11186. return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);
  11187. },
  11188. getValueForPixel: function(pixel) {
  11189. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  11190. },
  11191. getPixelForTick: function(index) {
  11192. var ticks = this.ticksAsNumbers;
  11193. if (index < 0 || index > ticks.length - 1) {
  11194. return null;
  11195. }
  11196. return this.getPixelForValue(ticks[index]);
  11197. }
  11198. });
  11199. // INTERNAL: static default options, registered in src/index.js
  11200. var _defaults$1 = defaultConfig$1;
  11201. scale_linear._defaults = _defaults$1;
  11202. var valueOrDefault$b = helpers$1.valueOrDefault;
  11203. var log10 = helpers$1.math.log10;
  11204. /**
  11205. * Generate a set of logarithmic ticks
  11206. * @param generationOptions the options used to generate the ticks
  11207. * @param dataRange the range of the data
  11208. * @returns {number[]} array of tick values
  11209. */
  11210. function generateTicks$1(generationOptions, dataRange) {
  11211. var ticks = [];
  11212. var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  11213. var endExp = Math.floor(log10(dataRange.max));
  11214. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  11215. var exp, significand;
  11216. if (tickVal === 0) {
  11217. exp = Math.floor(log10(dataRange.minNotZero));
  11218. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  11219. ticks.push(tickVal);
  11220. tickVal = significand * Math.pow(10, exp);
  11221. } else {
  11222. exp = Math.floor(log10(tickVal));
  11223. significand = Math.floor(tickVal / Math.pow(10, exp));
  11224. }
  11225. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  11226. do {
  11227. ticks.push(tickVal);
  11228. ++significand;
  11229. if (significand === 10) {
  11230. significand = 1;
  11231. ++exp;
  11232. precision = exp >= 0 ? 1 : precision;
  11233. }
  11234. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  11235. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  11236. var lastTick = valueOrDefault$b(generationOptions.max, tickVal);
  11237. ticks.push(lastTick);
  11238. return ticks;
  11239. }
  11240. var defaultConfig$2 = {
  11241. position: 'left',
  11242. // label settings
  11243. ticks: {
  11244. callback: core_ticks.formatters.logarithmic
  11245. }
  11246. };
  11247. // TODO(v3): change this to positiveOrDefault
  11248. function nonNegativeOrDefault(value, defaultValue) {
  11249. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  11250. }
  11251. var scale_logarithmic = core_scale.extend({
  11252. determineDataLimits: function() {
  11253. var me = this;
  11254. var opts = me.options;
  11255. var chart = me.chart;
  11256. var datasets = chart.data.datasets;
  11257. var isHorizontal = me.isHorizontal();
  11258. function IDMatches(meta) {
  11259. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  11260. }
  11261. var datasetIndex, meta, value, data, i, ilen;
  11262. // Calculate Range
  11263. me.min = Number.POSITIVE_INFINITY;
  11264. me.max = Number.NEGATIVE_INFINITY;
  11265. me.minNotZero = Number.POSITIVE_INFINITY;
  11266. var hasStacks = opts.stacked;
  11267. if (hasStacks === undefined) {
  11268. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11269. meta = chart.getDatasetMeta(datasetIndex);
  11270. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  11271. meta.stack !== undefined) {
  11272. hasStacks = true;
  11273. break;
  11274. }
  11275. }
  11276. }
  11277. if (opts.stacked || hasStacks) {
  11278. var valuesPerStack = {};
  11279. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11280. meta = chart.getDatasetMeta(datasetIndex);
  11281. var key = [
  11282. meta.type,
  11283. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11284. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  11285. meta.stack
  11286. ].join('.');
  11287. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11288. if (valuesPerStack[key] === undefined) {
  11289. valuesPerStack[key] = [];
  11290. }
  11291. data = datasets[datasetIndex].data;
  11292. for (i = 0, ilen = data.length; i < ilen; i++) {
  11293. var values = valuesPerStack[key];
  11294. value = me._parseValue(data[i]);
  11295. // invalid, hidden and negative values are ignored
  11296. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11297. continue;
  11298. }
  11299. values[i] = values[i] || 0;
  11300. values[i] += value.max;
  11301. }
  11302. }
  11303. }
  11304. helpers$1.each(valuesPerStack, function(valuesForType) {
  11305. if (valuesForType.length > 0) {
  11306. var minVal = helpers$1.min(valuesForType);
  11307. var maxVal = helpers$1.max(valuesForType);
  11308. me.min = Math.min(me.min, minVal);
  11309. me.max = Math.max(me.max, maxVal);
  11310. }
  11311. });
  11312. } else {
  11313. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11314. meta = chart.getDatasetMeta(datasetIndex);
  11315. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11316. data = datasets[datasetIndex].data;
  11317. for (i = 0, ilen = data.length; i < ilen; i++) {
  11318. value = me._parseValue(data[i]);
  11319. // invalid, hidden and negative values are ignored
  11320. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11321. continue;
  11322. }
  11323. me.min = Math.min(value.min, me.min);
  11324. me.max = Math.max(value.max, me.max);
  11325. if (value.min !== 0) {
  11326. me.minNotZero = Math.min(value.min, me.minNotZero);
  11327. }
  11328. }
  11329. }
  11330. }
  11331. }
  11332. me.min = helpers$1.isFinite(me.min) ? me.min : null;
  11333. me.max = helpers$1.isFinite(me.max) ? me.max : null;
  11334. me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;
  11335. // Common base implementation to handle ticks.min, ticks.max
  11336. this.handleTickRangeOptions();
  11337. },
  11338. handleTickRangeOptions: function() {
  11339. var me = this;
  11340. var tickOpts = me.options.ticks;
  11341. var DEFAULT_MIN = 1;
  11342. var DEFAULT_MAX = 10;
  11343. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  11344. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  11345. if (me.min === me.max) {
  11346. if (me.min !== 0 && me.min !== null) {
  11347. me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);
  11348. me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);
  11349. } else {
  11350. me.min = DEFAULT_MIN;
  11351. me.max = DEFAULT_MAX;
  11352. }
  11353. }
  11354. if (me.min === null) {
  11355. me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);
  11356. }
  11357. if (me.max === null) {
  11358. me.max = me.min !== 0
  11359. ? Math.pow(10, Math.floor(log10(me.min)) + 1)
  11360. : DEFAULT_MAX;
  11361. }
  11362. if (me.minNotZero === null) {
  11363. if (me.min > 0) {
  11364. me.minNotZero = me.min;
  11365. } else if (me.max < 1) {
  11366. me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));
  11367. } else {
  11368. me.minNotZero = DEFAULT_MIN;
  11369. }
  11370. }
  11371. },
  11372. buildTicks: function() {
  11373. var me = this;
  11374. var tickOpts = me.options.ticks;
  11375. var reverse = !me.isHorizontal();
  11376. var generationOptions = {
  11377. min: nonNegativeOrDefault(tickOpts.min),
  11378. max: nonNegativeOrDefault(tickOpts.max)
  11379. };
  11380. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  11381. // At this point, we need to update our max and min given the tick values since we have expanded the
  11382. // range of the scale
  11383. me.max = helpers$1.max(ticks);
  11384. me.min = helpers$1.min(ticks);
  11385. if (tickOpts.reverse) {
  11386. reverse = !reverse;
  11387. me.start = me.max;
  11388. me.end = me.min;
  11389. } else {
  11390. me.start = me.min;
  11391. me.end = me.max;
  11392. }
  11393. if (reverse) {
  11394. ticks.reverse();
  11395. }
  11396. },
  11397. convertTicksToLabels: function() {
  11398. this.tickValues = this.ticks.slice();
  11399. core_scale.prototype.convertTicksToLabels.call(this);
  11400. },
  11401. // Get the correct tooltip label
  11402. getLabelForIndex: function(index, datasetIndex) {
  11403. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11404. },
  11405. getPixelForTick: function(index) {
  11406. var ticks = this.tickValues;
  11407. if (index < 0 || index > ticks.length - 1) {
  11408. return null;
  11409. }
  11410. return this.getPixelForValue(ticks[index]);
  11411. },
  11412. /**
  11413. * Returns the value of the first tick.
  11414. * @param {number} value - The minimum not zero value.
  11415. * @return {number} The first tick value.
  11416. * @private
  11417. */
  11418. _getFirstTickValue: function(value) {
  11419. var exp = Math.floor(log10(value));
  11420. var significand = Math.floor(value / Math.pow(10, exp));
  11421. return significand * Math.pow(10, exp);
  11422. },
  11423. _configure: function() {
  11424. var me = this;
  11425. var start = me.min;
  11426. var offset = 0;
  11427. core_scale.prototype._configure.call(me);
  11428. if (start === 0) {
  11429. start = me._getFirstTickValue(me.minNotZero);
  11430. offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;
  11431. }
  11432. me._startValue = log10(start);
  11433. me._valueOffset = offset;
  11434. me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);
  11435. },
  11436. getPixelForValue: function(value) {
  11437. var me = this;
  11438. var decimal = 0;
  11439. value = +me.getRightValue(value);
  11440. if (value > me.min && value > 0) {
  11441. decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;
  11442. }
  11443. return me.getPixelForDecimal(decimal);
  11444. },
  11445. getValueForPixel: function(pixel) {
  11446. var me = this;
  11447. var decimal = me.getDecimalForPixel(pixel);
  11448. return decimal === 0 && me.min === 0
  11449. ? 0
  11450. : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);
  11451. }
  11452. });
  11453. // INTERNAL: static default options, registered in src/index.js
  11454. var _defaults$2 = defaultConfig$2;
  11455. scale_logarithmic._defaults = _defaults$2;
  11456. var valueOrDefault$c = helpers$1.valueOrDefault;
  11457. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  11458. var resolve$4 = helpers$1.options.resolve;
  11459. var defaultConfig$3 = {
  11460. display: true,
  11461. // Boolean - Whether to animate scaling the chart from the centre
  11462. animate: true,
  11463. position: 'chartArea',
  11464. angleLines: {
  11465. display: true,
  11466. color: 'rgba(0,0,0,0.1)',
  11467. lineWidth: 1,
  11468. borderDash: [],
  11469. borderDashOffset: 0.0
  11470. },
  11471. gridLines: {
  11472. circular: false
  11473. },
  11474. // label settings
  11475. ticks: {
  11476. // Boolean - Show a backdrop to the scale label
  11477. showLabelBackdrop: true,
  11478. // String - The colour of the label backdrop
  11479. backdropColor: 'rgba(255,255,255,0.75)',
  11480. // Number - The backdrop padding above & below the label in pixels
  11481. backdropPaddingY: 2,
  11482. // Number - The backdrop padding to the side of the label in pixels
  11483. backdropPaddingX: 2,
  11484. callback: core_ticks.formatters.linear
  11485. },
  11486. pointLabels: {
  11487. // Boolean - if true, show point labels
  11488. display: true,
  11489. // Number - Point label font size in pixels
  11490. fontSize: 10,
  11491. // Function - Used to convert point labels
  11492. callback: function(label) {
  11493. return label;
  11494. }
  11495. }
  11496. };
  11497. function getTickBackdropHeight(opts) {
  11498. var tickOpts = opts.ticks;
  11499. if (tickOpts.display && opts.display) {
  11500. return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  11501. }
  11502. return 0;
  11503. }
  11504. function measureLabelSize(ctx, lineHeight, label) {
  11505. if (helpers$1.isArray(label)) {
  11506. return {
  11507. w: helpers$1.longestText(ctx, ctx.font, label),
  11508. h: label.length * lineHeight
  11509. };
  11510. }
  11511. return {
  11512. w: ctx.measureText(label).width,
  11513. h: lineHeight
  11514. };
  11515. }
  11516. function determineLimits(angle, pos, size, min, max) {
  11517. if (angle === min || angle === max) {
  11518. return {
  11519. start: pos - (size / 2),
  11520. end: pos + (size / 2)
  11521. };
  11522. } else if (angle < min || angle > max) {
  11523. return {
  11524. start: pos - size,
  11525. end: pos
  11526. };
  11527. }
  11528. return {
  11529. start: pos,
  11530. end: pos + size
  11531. };
  11532. }
  11533. /**
  11534. * Helper function to fit a radial linear scale with point labels
  11535. */
  11536. function fitWithPointLabels(scale) {
  11537. // Right, this is really confusing and there is a lot of maths going on here
  11538. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  11539. //
  11540. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  11541. //
  11542. // Solution:
  11543. //
  11544. // We assume the radius of the polygon is half the size of the canvas at first
  11545. // at each index we check if the text overlaps.
  11546. //
  11547. // Where it does, we store that angle and that index.
  11548. //
  11549. // After finding the largest index and angle we calculate how much we need to remove
  11550. // from the shape radius to move the point inwards by that x.
  11551. //
  11552. // We average the left and right distances to get the maximum shape radius that can fit in the box
  11553. // along with labels.
  11554. //
  11555. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  11556. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  11557. //
  11558. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  11559. // and position it in the most space efficient manner
  11560. //
  11561. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  11562. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  11563. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  11564. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  11565. var furthestLimits = {
  11566. l: 0,
  11567. r: scale.width,
  11568. t: 0,
  11569. b: scale.height - scale.paddingTop
  11570. };
  11571. var furthestAngles = {};
  11572. var i, textSize, pointPosition;
  11573. scale.ctx.font = plFont.string;
  11574. scale._pointLabelSizes = [];
  11575. var valueCount = scale.chart.data.labels.length;
  11576. for (i = 0; i < valueCount; i++) {
  11577. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  11578. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
  11579. scale._pointLabelSizes[i] = textSize;
  11580. // Add quarter circle to make degree 0 mean top of circle
  11581. var angleRadians = scale.getIndexAngle(i);
  11582. var angle = helpers$1.toDegrees(angleRadians) % 360;
  11583. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  11584. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  11585. if (hLimits.start < furthestLimits.l) {
  11586. furthestLimits.l = hLimits.start;
  11587. furthestAngles.l = angleRadians;
  11588. }
  11589. if (hLimits.end > furthestLimits.r) {
  11590. furthestLimits.r = hLimits.end;
  11591. furthestAngles.r = angleRadians;
  11592. }
  11593. if (vLimits.start < furthestLimits.t) {
  11594. furthestLimits.t = vLimits.start;
  11595. furthestAngles.t = angleRadians;
  11596. }
  11597. if (vLimits.end > furthestLimits.b) {
  11598. furthestLimits.b = vLimits.end;
  11599. furthestAngles.b = angleRadians;
  11600. }
  11601. }
  11602. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  11603. }
  11604. function getTextAlignForAngle(angle) {
  11605. if (angle === 0 || angle === 180) {
  11606. return 'center';
  11607. } else if (angle < 180) {
  11608. return 'left';
  11609. }
  11610. return 'right';
  11611. }
  11612. function fillText(ctx, text, position, lineHeight) {
  11613. var y = position.y + lineHeight / 2;
  11614. var i, ilen;
  11615. if (helpers$1.isArray(text)) {
  11616. for (i = 0, ilen = text.length; i < ilen; ++i) {
  11617. ctx.fillText(text[i], position.x, y);
  11618. y += lineHeight;
  11619. }
  11620. } else {
  11621. ctx.fillText(text, position.x, y);
  11622. }
  11623. }
  11624. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  11625. if (angle === 90 || angle === 270) {
  11626. position.y -= (textSize.h / 2);
  11627. } else if (angle > 270 || angle < 90) {
  11628. position.y -= textSize.h;
  11629. }
  11630. }
  11631. function drawPointLabels(scale) {
  11632. var ctx = scale.ctx;
  11633. var opts = scale.options;
  11634. var pointLabelOpts = opts.pointLabels;
  11635. var tickBackdropHeight = getTickBackdropHeight(opts);
  11636. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  11637. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  11638. ctx.save();
  11639. ctx.font = plFont.string;
  11640. ctx.textBaseline = 'middle';
  11641. for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
  11642. // Extra pixels out for some label spacing
  11643. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  11644. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  11645. // Keep this in loop since we may support array properties here
  11646. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  11647. ctx.fillStyle = pointLabelFontColor;
  11648. var angleRadians = scale.getIndexAngle(i);
  11649. var angle = helpers$1.toDegrees(angleRadians);
  11650. ctx.textAlign = getTextAlignForAngle(angle);
  11651. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  11652. fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
  11653. }
  11654. ctx.restore();
  11655. }
  11656. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  11657. var ctx = scale.ctx;
  11658. var circular = gridLineOpts.circular;
  11659. var valueCount = scale.chart.data.labels.length;
  11660. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  11661. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  11662. var pointPosition;
  11663. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  11664. return;
  11665. }
  11666. ctx.save();
  11667. ctx.strokeStyle = lineColor;
  11668. ctx.lineWidth = lineWidth;
  11669. if (ctx.setLineDash) {
  11670. ctx.setLineDash(gridLineOpts.borderDash || []);
  11671. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  11672. }
  11673. ctx.beginPath();
  11674. if (circular) {
  11675. // Draw circular arcs between the points
  11676. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  11677. } else {
  11678. // Draw straight lines connecting each index
  11679. pointPosition = scale.getPointPosition(0, radius);
  11680. ctx.moveTo(pointPosition.x, pointPosition.y);
  11681. for (var i = 1; i < valueCount; i++) {
  11682. pointPosition = scale.getPointPosition(i, radius);
  11683. ctx.lineTo(pointPosition.x, pointPosition.y);
  11684. }
  11685. }
  11686. ctx.closePath();
  11687. ctx.stroke();
  11688. ctx.restore();
  11689. }
  11690. function numberOrZero(param) {
  11691. return helpers$1.isNumber(param) ? param : 0;
  11692. }
  11693. var scale_radialLinear = scale_linearbase.extend({
  11694. setDimensions: function() {
  11695. var me = this;
  11696. // Set the unconstrained dimension before label rotation
  11697. me.width = me.maxWidth;
  11698. me.height = me.maxHeight;
  11699. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  11700. me.xCenter = Math.floor(me.width / 2);
  11701. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  11702. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  11703. },
  11704. determineDataLimits: function() {
  11705. var me = this;
  11706. var chart = me.chart;
  11707. var min = Number.POSITIVE_INFINITY;
  11708. var max = Number.NEGATIVE_INFINITY;
  11709. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  11710. if (chart.isDatasetVisible(datasetIndex)) {
  11711. var meta = chart.getDatasetMeta(datasetIndex);
  11712. helpers$1.each(dataset.data, function(rawValue, index) {
  11713. var value = +me.getRightValue(rawValue);
  11714. if (isNaN(value) || meta.data[index].hidden) {
  11715. return;
  11716. }
  11717. min = Math.min(value, min);
  11718. max = Math.max(value, max);
  11719. });
  11720. }
  11721. });
  11722. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  11723. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  11724. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11725. me.handleTickRangeOptions();
  11726. },
  11727. // Returns the maximum number of ticks based on the scale dimension
  11728. _computeTickLimit: function() {
  11729. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  11730. },
  11731. convertTicksToLabels: function() {
  11732. var me = this;
  11733. scale_linearbase.prototype.convertTicksToLabels.call(me);
  11734. // Point labels
  11735. me.pointLabels = me.chart.data.labels.map(function() {
  11736. var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);
  11737. return label || label === 0 ? label : '';
  11738. });
  11739. },
  11740. getLabelForIndex: function(index, datasetIndex) {
  11741. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  11742. },
  11743. fit: function() {
  11744. var me = this;
  11745. var opts = me.options;
  11746. if (opts.display && opts.pointLabels.display) {
  11747. fitWithPointLabels(me);
  11748. } else {
  11749. me.setCenterPoint(0, 0, 0, 0);
  11750. }
  11751. },
  11752. /**
  11753. * Set radius reductions and determine new radius and center point
  11754. * @private
  11755. */
  11756. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  11757. var me = this;
  11758. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  11759. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  11760. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  11761. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  11762. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  11763. radiusReductionRight = numberOrZero(radiusReductionRight);
  11764. radiusReductionTop = numberOrZero(radiusReductionTop);
  11765. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  11766. me.drawingArea = Math.min(
  11767. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  11768. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  11769. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  11770. },
  11771. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  11772. var me = this;
  11773. var maxRight = me.width - rightMovement - me.drawingArea;
  11774. var maxLeft = leftMovement + me.drawingArea;
  11775. var maxTop = topMovement + me.drawingArea;
  11776. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  11777. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  11778. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  11779. },
  11780. getIndexAngle: function(index) {
  11781. var chart = this.chart;
  11782. var angleMultiplier = 360 / chart.data.labels.length;
  11783. var options = chart.options || {};
  11784. var startAngle = options.startAngle || 0;
  11785. // Start from the top instead of right, so remove a quarter of the circle
  11786. var angle = (index * angleMultiplier + startAngle) % 360;
  11787. return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;
  11788. },
  11789. getDistanceFromCenterForValue: function(value) {
  11790. var me = this;
  11791. if (helpers$1.isNullOrUndef(value)) {
  11792. return NaN;
  11793. }
  11794. // Take into account half font size + the yPadding of the top value
  11795. var scalingFactor = me.drawingArea / (me.max - me.min);
  11796. if (me.options.ticks.reverse) {
  11797. return (me.max - value) * scalingFactor;
  11798. }
  11799. return (value - me.min) * scalingFactor;
  11800. },
  11801. getPointPosition: function(index, distanceFromCenter) {
  11802. var me = this;
  11803. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  11804. return {
  11805. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  11806. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  11807. };
  11808. },
  11809. getPointPositionForValue: function(index, value) {
  11810. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  11811. },
  11812. getBasePosition: function(index) {
  11813. var me = this;
  11814. var min = me.min;
  11815. var max = me.max;
  11816. return me.getPointPositionForValue(index || 0,
  11817. me.beginAtZero ? 0 :
  11818. min < 0 && max < 0 ? max :
  11819. min > 0 && max > 0 ? min :
  11820. 0);
  11821. },
  11822. /**
  11823. * @private
  11824. */
  11825. _drawGrid: function() {
  11826. var me = this;
  11827. var ctx = me.ctx;
  11828. var opts = me.options;
  11829. var gridLineOpts = opts.gridLines;
  11830. var angleLineOpts = opts.angleLines;
  11831. var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  11832. var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);
  11833. var i, offset, position;
  11834. if (opts.pointLabels.display) {
  11835. drawPointLabels(me);
  11836. }
  11837. if (gridLineOpts.display) {
  11838. helpers$1.each(me.ticks, function(label, index) {
  11839. if (index !== 0) {
  11840. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11841. drawRadiusLine(me, gridLineOpts, offset, index);
  11842. }
  11843. });
  11844. }
  11845. if (angleLineOpts.display && lineWidth && lineColor) {
  11846. ctx.save();
  11847. ctx.lineWidth = lineWidth;
  11848. ctx.strokeStyle = lineColor;
  11849. if (ctx.setLineDash) {
  11850. ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  11851. ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  11852. }
  11853. for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
  11854. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  11855. position = me.getPointPosition(i, offset);
  11856. ctx.beginPath();
  11857. ctx.moveTo(me.xCenter, me.yCenter);
  11858. ctx.lineTo(position.x, position.y);
  11859. ctx.stroke();
  11860. }
  11861. ctx.restore();
  11862. }
  11863. },
  11864. /**
  11865. * @private
  11866. */
  11867. _drawLabels: function() {
  11868. var me = this;
  11869. var ctx = me.ctx;
  11870. var opts = me.options;
  11871. var tickOpts = opts.ticks;
  11872. if (!tickOpts.display) {
  11873. return;
  11874. }
  11875. var startAngle = me.getIndexAngle(0);
  11876. var tickFont = helpers$1.options._parseFont(tickOpts);
  11877. var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  11878. var offset, width;
  11879. ctx.save();
  11880. ctx.font = tickFont.string;
  11881. ctx.translate(me.xCenter, me.yCenter);
  11882. ctx.rotate(startAngle);
  11883. ctx.textAlign = 'center';
  11884. ctx.textBaseline = 'middle';
  11885. helpers$1.each(me.ticks, function(label, index) {
  11886. if (index === 0 && !tickOpts.reverse) {
  11887. return;
  11888. }
  11889. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11890. if (tickOpts.showLabelBackdrop) {
  11891. width = ctx.measureText(label).width;
  11892. ctx.fillStyle = tickOpts.backdropColor;
  11893. ctx.fillRect(
  11894. -width / 2 - tickOpts.backdropPaddingX,
  11895. -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  11896. width + tickOpts.backdropPaddingX * 2,
  11897. tickFont.size + tickOpts.backdropPaddingY * 2
  11898. );
  11899. }
  11900. ctx.fillStyle = tickFontColor;
  11901. ctx.fillText(label, 0, -offset);
  11902. });
  11903. ctx.restore();
  11904. },
  11905. /**
  11906. * @private
  11907. */
  11908. _drawTitle: helpers$1.noop
  11909. });
  11910. // INTERNAL: static default options, registered in src/index.js
  11911. var _defaults$3 = defaultConfig$3;
  11912. scale_radialLinear._defaults = _defaults$3;
  11913. var deprecated$1 = helpers$1._deprecated;
  11914. var resolve$5 = helpers$1.options.resolve;
  11915. var valueOrDefault$d = helpers$1.valueOrDefault;
  11916. // Integer constants are from the ES6 spec.
  11917. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  11918. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  11919. var INTERVALS = {
  11920. millisecond: {
  11921. common: true,
  11922. size: 1,
  11923. steps: 1000
  11924. },
  11925. second: {
  11926. common: true,
  11927. size: 1000,
  11928. steps: 60
  11929. },
  11930. minute: {
  11931. common: true,
  11932. size: 60000,
  11933. steps: 60
  11934. },
  11935. hour: {
  11936. common: true,
  11937. size: 3600000,
  11938. steps: 24
  11939. },
  11940. day: {
  11941. common: true,
  11942. size: 86400000,
  11943. steps: 30
  11944. },
  11945. week: {
  11946. common: false,
  11947. size: 604800000,
  11948. steps: 4
  11949. },
  11950. month: {
  11951. common: true,
  11952. size: 2.628e9,
  11953. steps: 12
  11954. },
  11955. quarter: {
  11956. common: false,
  11957. size: 7.884e9,
  11958. steps: 4
  11959. },
  11960. year: {
  11961. common: true,
  11962. size: 3.154e10
  11963. }
  11964. };
  11965. var UNITS = Object.keys(INTERVALS);
  11966. function sorter(a, b) {
  11967. return a - b;
  11968. }
  11969. function arrayUnique(items) {
  11970. var hash = {};
  11971. var out = [];
  11972. var i, ilen, item;
  11973. for (i = 0, ilen = items.length; i < ilen; ++i) {
  11974. item = items[i];
  11975. if (!hash[item]) {
  11976. hash[item] = true;
  11977. out.push(item);
  11978. }
  11979. }
  11980. return out;
  11981. }
  11982. function getMin(options) {
  11983. return helpers$1.valueOrDefault(options.time.min, options.ticks.min);
  11984. }
  11985. function getMax(options) {
  11986. return helpers$1.valueOrDefault(options.time.max, options.ticks.max);
  11987. }
  11988. /**
  11989. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  11990. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  11991. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  11992. * extremity (left + width or top + height). Note that it would be more optimized to directly
  11993. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  11994. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  11995. *
  11996. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  11997. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  11998. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  11999. * If 'series', timestamps will be positioned at the same distance from each other. In this
  12000. * case, only timestamps that break the time linearity are registered, meaning that in the
  12001. * best case, all timestamps are linear, the table contains only min and max.
  12002. */
  12003. function buildLookupTable(timestamps, min, max, distribution) {
  12004. if (distribution === 'linear' || !timestamps.length) {
  12005. return [
  12006. {time: min, pos: 0},
  12007. {time: max, pos: 1}
  12008. ];
  12009. }
  12010. var table = [];
  12011. var items = [min];
  12012. var i, ilen, prev, curr, next;
  12013. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12014. curr = timestamps[i];
  12015. if (curr > min && curr < max) {
  12016. items.push(curr);
  12017. }
  12018. }
  12019. items.push(max);
  12020. for (i = 0, ilen = items.length; i < ilen; ++i) {
  12021. next = items[i + 1];
  12022. prev = items[i - 1];
  12023. curr = items[i];
  12024. // only add points that breaks the scale linearity
  12025. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  12026. table.push({time: curr, pos: i / (ilen - 1)});
  12027. }
  12028. }
  12029. return table;
  12030. }
  12031. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  12032. function lookup(table, key, value) {
  12033. var lo = 0;
  12034. var hi = table.length - 1;
  12035. var mid, i0, i1;
  12036. while (lo >= 0 && lo <= hi) {
  12037. mid = (lo + hi) >> 1;
  12038. i0 = table[mid - 1] || null;
  12039. i1 = table[mid];
  12040. if (!i0) {
  12041. // given value is outside table (before first item)
  12042. return {lo: null, hi: i1};
  12043. } else if (i1[key] < value) {
  12044. lo = mid + 1;
  12045. } else if (i0[key] > value) {
  12046. hi = mid - 1;
  12047. } else {
  12048. return {lo: i0, hi: i1};
  12049. }
  12050. }
  12051. // given value is outside table (after last item)
  12052. return {lo: i1, hi: null};
  12053. }
  12054. /**
  12055. * Linearly interpolates the given source `value` using the table items `skey` values and
  12056. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  12057. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  12058. * index [0, 1] or [n - 1, n] are used for the interpolation.
  12059. */
  12060. function interpolate$1(table, skey, sval, tkey) {
  12061. var range = lookup(table, skey, sval);
  12062. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  12063. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  12064. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  12065. var span = next[skey] - prev[skey];
  12066. var ratio = span ? (sval - prev[skey]) / span : 0;
  12067. var offset = (next[tkey] - prev[tkey]) * ratio;
  12068. return prev[tkey] + offset;
  12069. }
  12070. function toTimestamp(scale, input) {
  12071. var adapter = scale._adapter;
  12072. var options = scale.options.time;
  12073. var parser = options.parser;
  12074. var format = parser || options.format;
  12075. var value = input;
  12076. if (typeof parser === 'function') {
  12077. value = parser(value);
  12078. }
  12079. // Only parse if its not a timestamp already
  12080. if (!helpers$1.isFinite(value)) {
  12081. value = typeof format === 'string'
  12082. ? adapter.parse(value, format)
  12083. : adapter.parse(value);
  12084. }
  12085. if (value !== null) {
  12086. return +value;
  12087. }
  12088. // Labels are in an incompatible format and no `parser` has been provided.
  12089. // The user might still use the deprecated `format` option for parsing.
  12090. if (!parser && typeof format === 'function') {
  12091. value = format(input);
  12092. // `format` could return something else than a timestamp, if so, parse it
  12093. if (!helpers$1.isFinite(value)) {
  12094. value = adapter.parse(value);
  12095. }
  12096. }
  12097. return value;
  12098. }
  12099. function parse(scale, input) {
  12100. if (helpers$1.isNullOrUndef(input)) {
  12101. return null;
  12102. }
  12103. var options = scale.options.time;
  12104. var value = toTimestamp(scale, scale.getRightValue(input));
  12105. if (value === null) {
  12106. return value;
  12107. }
  12108. if (options.round) {
  12109. value = +scale._adapter.startOf(value, options.round);
  12110. }
  12111. return value;
  12112. }
  12113. /**
  12114. * Figures out what unit results in an appropriate number of auto-generated ticks
  12115. */
  12116. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  12117. var ilen = UNITS.length;
  12118. var i, interval, factor;
  12119. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  12120. interval = INTERVALS[UNITS[i]];
  12121. factor = interval.steps ? interval.steps : MAX_INTEGER;
  12122. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  12123. return UNITS[i];
  12124. }
  12125. }
  12126. return UNITS[ilen - 1];
  12127. }
  12128. /**
  12129. * Figures out what unit to format a set of ticks with
  12130. */
  12131. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  12132. var i, unit;
  12133. for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  12134. unit = UNITS[i];
  12135. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  12136. return unit;
  12137. }
  12138. }
  12139. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  12140. }
  12141. function determineMajorUnit(unit) {
  12142. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  12143. if (INTERVALS[UNITS[i]].common) {
  12144. return UNITS[i];
  12145. }
  12146. }
  12147. }
  12148. /**
  12149. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  12150. * `minor` unit using the given scale time `options`.
  12151. * Important: this method can return ticks outside the min and max range, it's the
  12152. * responsibility of the calling code to clamp values if needed.
  12153. */
  12154. function generate(scale, min, max, capacity) {
  12155. var adapter = scale._adapter;
  12156. var options = scale.options;
  12157. var timeOpts = options.time;
  12158. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  12159. var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
  12160. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  12161. var first = min;
  12162. var ticks = [];
  12163. var time;
  12164. // For 'week' unit, handle the first day of week option
  12165. if (weekday) {
  12166. first = +adapter.startOf(first, 'isoWeek', weekday);
  12167. }
  12168. // Align first ticks on unit
  12169. first = +adapter.startOf(first, weekday ? 'day' : minor);
  12170. // Prevent browser from freezing in case user options request millions of milliseconds
  12171. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  12172. throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
  12173. }
  12174. for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {
  12175. ticks.push(time);
  12176. }
  12177. if (time === max || options.bounds === 'ticks') {
  12178. ticks.push(time);
  12179. }
  12180. return ticks;
  12181. }
  12182. /**
  12183. * Returns the start and end offsets from edges in the form of {start, end}
  12184. * where each value is a relative width to the scale and ranges between 0 and 1.
  12185. * They add extra margins on the both sides by scaling down the original scale.
  12186. * Offsets are added when the `offset` option is true.
  12187. */
  12188. function computeOffsets(table, ticks, min, max, options) {
  12189. var start = 0;
  12190. var end = 0;
  12191. var first, last;
  12192. if (options.offset && ticks.length) {
  12193. first = interpolate$1(table, 'time', ticks[0], 'pos');
  12194. if (ticks.length === 1) {
  12195. start = 1 - first;
  12196. } else {
  12197. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  12198. }
  12199. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  12200. if (ticks.length === 1) {
  12201. end = last;
  12202. } else {
  12203. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  12204. }
  12205. }
  12206. return {start: start, end: end, factor: 1 / (start + 1 + end)};
  12207. }
  12208. function setMajorTicks(scale, ticks, map, majorUnit) {
  12209. var adapter = scale._adapter;
  12210. var first = +adapter.startOf(ticks[0].value, majorUnit);
  12211. var last = ticks[ticks.length - 1].value;
  12212. var major, index;
  12213. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  12214. index = map[major];
  12215. if (index >= 0) {
  12216. ticks[index].major = true;
  12217. }
  12218. }
  12219. return ticks;
  12220. }
  12221. function ticksFromTimestamps(scale, values, majorUnit) {
  12222. var ticks = [];
  12223. var map = {};
  12224. var ilen = values.length;
  12225. var i, value;
  12226. for (i = 0; i < ilen; ++i) {
  12227. value = values[i];
  12228. map[value] = i;
  12229. ticks.push({
  12230. value: value,
  12231. major: false
  12232. });
  12233. }
  12234. // We set the major ticks separately from the above loop because calling startOf for every tick
  12235. // is expensive when there is a large number of ticks
  12236. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  12237. }
  12238. var defaultConfig$4 = {
  12239. position: 'bottom',
  12240. /**
  12241. * Data distribution along the scale:
  12242. * - 'linear': data are spread according to their time (distances can vary),
  12243. * - 'series': data are spread at the same distance from each other.
  12244. * @see https://github.com/chartjs/Chart.js/pull/4507
  12245. * @since 2.7.0
  12246. */
  12247. distribution: 'linear',
  12248. /**
  12249. * Scale boundary strategy (bypassed by min/max time options)
  12250. * - `data`: make sure data are fully visible, ticks outside are removed
  12251. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  12252. * @see https://github.com/chartjs/Chart.js/pull/4556
  12253. * @since 2.7.0
  12254. */
  12255. bounds: 'data',
  12256. adapters: {},
  12257. time: {
  12258. parser: false, // false == a pattern string from https://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
  12259. unit: false, // false == automatic or override with week, month, year, etc.
  12260. round: false, // none, or override with week, month, year, etc.
  12261. displayFormat: false, // DEPRECATED
  12262. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  12263. minUnit: 'millisecond',
  12264. displayFormats: {}
  12265. },
  12266. ticks: {
  12267. autoSkip: false,
  12268. /**
  12269. * Ticks generation input values:
  12270. * - 'auto': generates "optimal" ticks based on scale size and time options.
  12271. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  12272. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  12273. * @see https://github.com/chartjs/Chart.js/pull/4507
  12274. * @since 2.7.0
  12275. */
  12276. source: 'auto',
  12277. major: {
  12278. enabled: false
  12279. }
  12280. }
  12281. };
  12282. var scale_time = core_scale.extend({
  12283. initialize: function() {
  12284. this.mergeTicksOptions();
  12285. core_scale.prototype.initialize.call(this);
  12286. },
  12287. update: function() {
  12288. var me = this;
  12289. var options = me.options;
  12290. var time = options.time || (options.time = {});
  12291. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  12292. // DEPRECATIONS: output a message only one time per update
  12293. deprecated$1('time scale', time.format, 'time.format', 'time.parser');
  12294. deprecated$1('time scale', time.min, 'time.min', 'ticks.min');
  12295. deprecated$1('time scale', time.max, 'time.max', 'ticks.max');
  12296. // Backward compatibility: before introducing adapter, `displayFormats` was
  12297. // supposed to contain *all* unit/string pairs but this can't be resolved
  12298. // when loading the scale (adapters are loaded afterward), so let's populate
  12299. // missing formats on update
  12300. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  12301. return core_scale.prototype.update.apply(me, arguments);
  12302. },
  12303. /**
  12304. * Allows data to be referenced via 't' attribute
  12305. */
  12306. getRightValue: function(rawValue) {
  12307. if (rawValue && rawValue.t !== undefined) {
  12308. rawValue = rawValue.t;
  12309. }
  12310. return core_scale.prototype.getRightValue.call(this, rawValue);
  12311. },
  12312. determineDataLimits: function() {
  12313. var me = this;
  12314. var chart = me.chart;
  12315. var adapter = me._adapter;
  12316. var options = me.options;
  12317. var unit = options.time.unit || 'day';
  12318. var min = MAX_INTEGER;
  12319. var max = MIN_INTEGER;
  12320. var timestamps = [];
  12321. var datasets = [];
  12322. var labels = [];
  12323. var i, j, ilen, jlen, data, timestamp, labelsAdded;
  12324. var dataLabels = me._getLabels();
  12325. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  12326. labels.push(parse(me, dataLabels[i]));
  12327. }
  12328. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  12329. if (chart.isDatasetVisible(i)) {
  12330. data = chart.data.datasets[i].data;
  12331. // Let's consider that all data have the same format.
  12332. if (helpers$1.isObject(data[0])) {
  12333. datasets[i] = [];
  12334. for (j = 0, jlen = data.length; j < jlen; ++j) {
  12335. timestamp = parse(me, data[j]);
  12336. timestamps.push(timestamp);
  12337. datasets[i][j] = timestamp;
  12338. }
  12339. } else {
  12340. datasets[i] = labels.slice(0);
  12341. if (!labelsAdded) {
  12342. timestamps = timestamps.concat(labels);
  12343. labelsAdded = true;
  12344. }
  12345. }
  12346. } else {
  12347. datasets[i] = [];
  12348. }
  12349. }
  12350. if (labels.length) {
  12351. min = Math.min(min, labels[0]);
  12352. max = Math.max(max, labels[labels.length - 1]);
  12353. }
  12354. if (timestamps.length) {
  12355. timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);
  12356. min = Math.min(min, timestamps[0]);
  12357. max = Math.max(max, timestamps[timestamps.length - 1]);
  12358. }
  12359. min = parse(me, getMin(options)) || min;
  12360. max = parse(me, getMax(options)) || max;
  12361. // In case there is no valid min/max, set limits based on unit time option
  12362. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  12363. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  12364. // Make sure that max is strictly higher than min (required by the lookup table)
  12365. me.min = Math.min(min, max);
  12366. me.max = Math.max(min + 1, max);
  12367. // PRIVATE
  12368. me._table = [];
  12369. me._timestamps = {
  12370. data: timestamps,
  12371. datasets: datasets,
  12372. labels: labels
  12373. };
  12374. },
  12375. buildTicks: function() {
  12376. var me = this;
  12377. var min = me.min;
  12378. var max = me.max;
  12379. var options = me.options;
  12380. var tickOpts = options.ticks;
  12381. var timeOpts = options.time;
  12382. var timestamps = me._timestamps;
  12383. var ticks = [];
  12384. var capacity = me.getLabelCapacity(min);
  12385. var source = tickOpts.source;
  12386. var distribution = options.distribution;
  12387. var i, ilen, timestamp;
  12388. if (source === 'data' || (source === 'auto' && distribution === 'series')) {
  12389. timestamps = timestamps.data;
  12390. } else if (source === 'labels') {
  12391. timestamps = timestamps.labels;
  12392. } else {
  12393. timestamps = generate(me, min, max, capacity);
  12394. }
  12395. if (options.bounds === 'ticks' && timestamps.length) {
  12396. min = timestamps[0];
  12397. max = timestamps[timestamps.length - 1];
  12398. }
  12399. // Enforce limits with user min/max options
  12400. min = parse(me, getMin(options)) || min;
  12401. max = parse(me, getMax(options)) || max;
  12402. // Remove ticks outside the min/max range
  12403. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12404. timestamp = timestamps[i];
  12405. if (timestamp >= min && timestamp <= max) {
  12406. ticks.push(timestamp);
  12407. }
  12408. }
  12409. me.min = min;
  12410. me.max = max;
  12411. // PRIVATE
  12412. // determineUnitForFormatting relies on the number of ticks so we don't use it when
  12413. // autoSkip is enabled because we don't yet know what the final number of ticks will be
  12414. me._unit = timeOpts.unit || (tickOpts.autoSkip
  12415. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
  12416. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  12417. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  12418. : determineMajorUnit(me._unit);
  12419. me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
  12420. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  12421. if (tickOpts.reverse) {
  12422. ticks.reverse();
  12423. }
  12424. return ticksFromTimestamps(me, ticks, me._majorUnit);
  12425. },
  12426. getLabelForIndex: function(index, datasetIndex) {
  12427. var me = this;
  12428. var adapter = me._adapter;
  12429. var data = me.chart.data;
  12430. var timeOpts = me.options.time;
  12431. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  12432. var value = data.datasets[datasetIndex].data[index];
  12433. if (helpers$1.isObject(value)) {
  12434. label = me.getRightValue(value);
  12435. }
  12436. if (timeOpts.tooltipFormat) {
  12437. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  12438. }
  12439. if (typeof label === 'string') {
  12440. return label;
  12441. }
  12442. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  12443. },
  12444. /**
  12445. * Function to format an individual tick mark
  12446. * @private
  12447. */
  12448. tickFormatFunction: function(time, index, ticks, format) {
  12449. var me = this;
  12450. var adapter = me._adapter;
  12451. var options = me.options;
  12452. var formats = options.time.displayFormats;
  12453. var minorFormat = formats[me._unit];
  12454. var majorUnit = me._majorUnit;
  12455. var majorFormat = formats[majorUnit];
  12456. var tick = ticks[index];
  12457. var tickOpts = options.ticks;
  12458. var major = majorUnit && majorFormat && tick && tick.major;
  12459. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  12460. var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;
  12461. var formatter = resolve$5([
  12462. nestedTickOpts.callback,
  12463. nestedTickOpts.userCallback,
  12464. tickOpts.callback,
  12465. tickOpts.userCallback
  12466. ]);
  12467. return formatter ? formatter(label, index, ticks) : label;
  12468. },
  12469. convertTicksToLabels: function(ticks) {
  12470. var labels = [];
  12471. var i, ilen;
  12472. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  12473. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  12474. }
  12475. return labels;
  12476. },
  12477. /**
  12478. * @private
  12479. */
  12480. getPixelForOffset: function(time) {
  12481. var me = this;
  12482. var offsets = me._offsets;
  12483. var pos = interpolate$1(me._table, 'time', time, 'pos');
  12484. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12485. },
  12486. getPixelForValue: function(value, index, datasetIndex) {
  12487. var me = this;
  12488. var time = null;
  12489. if (index !== undefined && datasetIndex !== undefined) {
  12490. time = me._timestamps.datasets[datasetIndex][index];
  12491. }
  12492. if (time === null) {
  12493. time = parse(me, value);
  12494. }
  12495. if (time !== null) {
  12496. return me.getPixelForOffset(time);
  12497. }
  12498. },
  12499. getPixelForTick: function(index) {
  12500. var ticks = this.getTicks();
  12501. return index >= 0 && index < ticks.length ?
  12502. this.getPixelForOffset(ticks[index].value) :
  12503. null;
  12504. },
  12505. getValueForPixel: function(pixel) {
  12506. var me = this;
  12507. var offsets = me._offsets;
  12508. var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12509. var time = interpolate$1(me._table, 'pos', pos, 'time');
  12510. // DEPRECATION, we should return time directly
  12511. return me._adapter._create(time);
  12512. },
  12513. /**
  12514. * @private
  12515. */
  12516. _getLabelSize: function(label) {
  12517. var me = this;
  12518. var ticksOpts = me.options.ticks;
  12519. var tickLabelWidth = me.ctx.measureText(label).width;
  12520. var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  12521. var cosRotation = Math.cos(angle);
  12522. var sinRotation = Math.sin(angle);
  12523. var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  12524. return {
  12525. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  12526. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  12527. };
  12528. },
  12529. /**
  12530. * Crude approximation of what the label width might be
  12531. * @private
  12532. */
  12533. getLabelWidth: function(label) {
  12534. return this._getLabelSize(label).w;
  12535. },
  12536. /**
  12537. * @private
  12538. */
  12539. getLabelCapacity: function(exampleTime) {
  12540. var me = this;
  12541. var timeOpts = me.options.time;
  12542. var displayFormats = timeOpts.displayFormats;
  12543. // pick the longest format (milliseconds) for guestimation
  12544. var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  12545. var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  12546. var size = me._getLabelSize(exampleLabel);
  12547. var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);
  12548. if (me.options.offset) {
  12549. capacity--;
  12550. }
  12551. return capacity > 0 ? capacity : 1;
  12552. }
  12553. });
  12554. // INTERNAL: static default options, registered in src/index.js
  12555. var _defaults$4 = defaultConfig$4;
  12556. scale_time._defaults = _defaults$4;
  12557. var scales = {
  12558. category: scale_category,
  12559. linear: scale_linear,
  12560. logarithmic: scale_logarithmic,
  12561. radialLinear: scale_radialLinear,
  12562. time: scale_time
  12563. };
  12564. var moment = createCommonjsModule(function (module, exports) {
  12565. (function (global, factory) {
  12566. module.exports = factory() ;
  12567. }(commonjsGlobal, (function () {
  12568. var hookCallback;
  12569. function hooks () {
  12570. return hookCallback.apply(null, arguments);
  12571. }
  12572. // This is done to register the method called with moment()
  12573. // without creating circular dependencies.
  12574. function setHookCallback (callback) {
  12575. hookCallback = callback;
  12576. }
  12577. function isArray(input) {
  12578. return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
  12579. }
  12580. function isObject(input) {
  12581. // IE8 will treat undefined and null as object if it wasn't for
  12582. // input != null
  12583. return input != null && Object.prototype.toString.call(input) === '[object Object]';
  12584. }
  12585. function isObjectEmpty(obj) {
  12586. if (Object.getOwnPropertyNames) {
  12587. return (Object.getOwnPropertyNames(obj).length === 0);
  12588. } else {
  12589. var k;
  12590. for (k in obj) {
  12591. if (obj.hasOwnProperty(k)) {
  12592. return false;
  12593. }
  12594. }
  12595. return true;
  12596. }
  12597. }
  12598. function isUndefined(input) {
  12599. return input === void 0;
  12600. }
  12601. function isNumber(input) {
  12602. return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
  12603. }
  12604. function isDate(input) {
  12605. return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
  12606. }
  12607. function map(arr, fn) {
  12608. var res = [], i;
  12609. for (i = 0; i < arr.length; ++i) {
  12610. res.push(fn(arr[i], i));
  12611. }
  12612. return res;
  12613. }
  12614. function hasOwnProp(a, b) {
  12615. return Object.prototype.hasOwnProperty.call(a, b);
  12616. }
  12617. function extend(a, b) {
  12618. for (var i in b) {
  12619. if (hasOwnProp(b, i)) {
  12620. a[i] = b[i];
  12621. }
  12622. }
  12623. if (hasOwnProp(b, 'toString')) {
  12624. a.toString = b.toString;
  12625. }
  12626. if (hasOwnProp(b, 'valueOf')) {
  12627. a.valueOf = b.valueOf;
  12628. }
  12629. return a;
  12630. }
  12631. function createUTC (input, format, locale, strict) {
  12632. return createLocalOrUTC(input, format, locale, strict, true).utc();
  12633. }
  12634. function defaultParsingFlags() {
  12635. // We need to deep clone this object.
  12636. return {
  12637. empty : false,
  12638. unusedTokens : [],
  12639. unusedInput : [],
  12640. overflow : -2,
  12641. charsLeftOver : 0,
  12642. nullInput : false,
  12643. invalidMonth : null,
  12644. invalidFormat : false,
  12645. userInvalidated : false,
  12646. iso : false,
  12647. parsedDateParts : [],
  12648. meridiem : null,
  12649. rfc2822 : false,
  12650. weekdayMismatch : false
  12651. };
  12652. }
  12653. function getParsingFlags(m) {
  12654. if (m._pf == null) {
  12655. m._pf = defaultParsingFlags();
  12656. }
  12657. return m._pf;
  12658. }
  12659. var some;
  12660. if (Array.prototype.some) {
  12661. some = Array.prototype.some;
  12662. } else {
  12663. some = function (fun) {
  12664. var t = Object(this);
  12665. var len = t.length >>> 0;
  12666. for (var i = 0; i < len; i++) {
  12667. if (i in t && fun.call(this, t[i], i, t)) {
  12668. return true;
  12669. }
  12670. }
  12671. return false;
  12672. };
  12673. }
  12674. function isValid(m) {
  12675. if (m._isValid == null) {
  12676. var flags = getParsingFlags(m);
  12677. var parsedParts = some.call(flags.parsedDateParts, function (i) {
  12678. return i != null;
  12679. });
  12680. var isNowValid = !isNaN(m._d.getTime()) &&
  12681. flags.overflow < 0 &&
  12682. !flags.empty &&
  12683. !flags.invalidMonth &&
  12684. !flags.invalidWeekday &&
  12685. !flags.weekdayMismatch &&
  12686. !flags.nullInput &&
  12687. !flags.invalidFormat &&
  12688. !flags.userInvalidated &&
  12689. (!flags.meridiem || (flags.meridiem && parsedParts));
  12690. if (m._strict) {
  12691. isNowValid = isNowValid &&
  12692. flags.charsLeftOver === 0 &&
  12693. flags.unusedTokens.length === 0 &&
  12694. flags.bigHour === undefined;
  12695. }
  12696. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  12697. m._isValid = isNowValid;
  12698. }
  12699. else {
  12700. return isNowValid;
  12701. }
  12702. }
  12703. return m._isValid;
  12704. }
  12705. function createInvalid (flags) {
  12706. var m = createUTC(NaN);
  12707. if (flags != null) {
  12708. extend(getParsingFlags(m), flags);
  12709. }
  12710. else {
  12711. getParsingFlags(m).userInvalidated = true;
  12712. }
  12713. return m;
  12714. }
  12715. // Plugins that add properties should also add the key here (null value),
  12716. // so we can properly clone ourselves.
  12717. var momentProperties = hooks.momentProperties = [];
  12718. function copyConfig(to, from) {
  12719. var i, prop, val;
  12720. if (!isUndefined(from._isAMomentObject)) {
  12721. to._isAMomentObject = from._isAMomentObject;
  12722. }
  12723. if (!isUndefined(from._i)) {
  12724. to._i = from._i;
  12725. }
  12726. if (!isUndefined(from._f)) {
  12727. to._f = from._f;
  12728. }
  12729. if (!isUndefined(from._l)) {
  12730. to._l = from._l;
  12731. }
  12732. if (!isUndefined(from._strict)) {
  12733. to._strict = from._strict;
  12734. }
  12735. if (!isUndefined(from._tzm)) {
  12736. to._tzm = from._tzm;
  12737. }
  12738. if (!isUndefined(from._isUTC)) {
  12739. to._isUTC = from._isUTC;
  12740. }
  12741. if (!isUndefined(from._offset)) {
  12742. to._offset = from._offset;
  12743. }
  12744. if (!isUndefined(from._pf)) {
  12745. to._pf = getParsingFlags(from);
  12746. }
  12747. if (!isUndefined(from._locale)) {
  12748. to._locale = from._locale;
  12749. }
  12750. if (momentProperties.length > 0) {
  12751. for (i = 0; i < momentProperties.length; i++) {
  12752. prop = momentProperties[i];
  12753. val = from[prop];
  12754. if (!isUndefined(val)) {
  12755. to[prop] = val;
  12756. }
  12757. }
  12758. }
  12759. return to;
  12760. }
  12761. var updateInProgress = false;
  12762. // Moment prototype object
  12763. function Moment(config) {
  12764. copyConfig(this, config);
  12765. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  12766. if (!this.isValid()) {
  12767. this._d = new Date(NaN);
  12768. }
  12769. // Prevent infinite loop in case updateOffset creates new moment
  12770. // objects.
  12771. if (updateInProgress === false) {
  12772. updateInProgress = true;
  12773. hooks.updateOffset(this);
  12774. updateInProgress = false;
  12775. }
  12776. }
  12777. function isMoment (obj) {
  12778. return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
  12779. }
  12780. function absFloor (number) {
  12781. if (number < 0) {
  12782. // -0 -> 0
  12783. return Math.ceil(number) || 0;
  12784. } else {
  12785. return Math.floor(number);
  12786. }
  12787. }
  12788. function toInt(argumentForCoercion) {
  12789. var coercedNumber = +argumentForCoercion,
  12790. value = 0;
  12791. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  12792. value = absFloor(coercedNumber);
  12793. }
  12794. return value;
  12795. }
  12796. // compare two arrays, return the number of differences
  12797. function compareArrays(array1, array2, dontConvert) {
  12798. var len = Math.min(array1.length, array2.length),
  12799. lengthDiff = Math.abs(array1.length - array2.length),
  12800. diffs = 0,
  12801. i;
  12802. for (i = 0; i < len; i++) {
  12803. if ((dontConvert && array1[i] !== array2[i]) ||
  12804. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  12805. diffs++;
  12806. }
  12807. }
  12808. return diffs + lengthDiff;
  12809. }
  12810. function warn(msg) {
  12811. if (hooks.suppressDeprecationWarnings === false &&
  12812. (typeof console !== 'undefined') && console.warn) {
  12813. console.warn('Deprecation warning: ' + msg);
  12814. }
  12815. }
  12816. function deprecate(msg, fn) {
  12817. var firstTime = true;
  12818. return extend(function () {
  12819. if (hooks.deprecationHandler != null) {
  12820. hooks.deprecationHandler(null, msg);
  12821. }
  12822. if (firstTime) {
  12823. var args = [];
  12824. var arg;
  12825. for (var i = 0; i < arguments.length; i++) {
  12826. arg = '';
  12827. if (typeof arguments[i] === 'object') {
  12828. arg += '\n[' + i + '] ';
  12829. for (var key in arguments[0]) {
  12830. arg += key + ': ' + arguments[0][key] + ', ';
  12831. }
  12832. arg = arg.slice(0, -2); // Remove trailing comma and space
  12833. } else {
  12834. arg = arguments[i];
  12835. }
  12836. args.push(arg);
  12837. }
  12838. warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
  12839. firstTime = false;
  12840. }
  12841. return fn.apply(this, arguments);
  12842. }, fn);
  12843. }
  12844. var deprecations = {};
  12845. function deprecateSimple(name, msg) {
  12846. if (hooks.deprecationHandler != null) {
  12847. hooks.deprecationHandler(name, msg);
  12848. }
  12849. if (!deprecations[name]) {
  12850. warn(msg);
  12851. deprecations[name] = true;
  12852. }
  12853. }
  12854. hooks.suppressDeprecationWarnings = false;
  12855. hooks.deprecationHandler = null;
  12856. function isFunction(input) {
  12857. return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
  12858. }
  12859. function set (config) {
  12860. var prop, i;
  12861. for (i in config) {
  12862. prop = config[i];
  12863. if (isFunction(prop)) {
  12864. this[i] = prop;
  12865. } else {
  12866. this['_' + i] = prop;
  12867. }
  12868. }
  12869. this._config = config;
  12870. // Lenient ordinal parsing accepts just a number in addition to
  12871. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  12872. // TODO: Remove "ordinalParse" fallback in next major release.
  12873. this._dayOfMonthOrdinalParseLenient = new RegExp(
  12874. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  12875. '|' + (/\d{1,2}/).source);
  12876. }
  12877. function mergeConfigs(parentConfig, childConfig) {
  12878. var res = extend({}, parentConfig), prop;
  12879. for (prop in childConfig) {
  12880. if (hasOwnProp(childConfig, prop)) {
  12881. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  12882. res[prop] = {};
  12883. extend(res[prop], parentConfig[prop]);
  12884. extend(res[prop], childConfig[prop]);
  12885. } else if (childConfig[prop] != null) {
  12886. res[prop] = childConfig[prop];
  12887. } else {
  12888. delete res[prop];
  12889. }
  12890. }
  12891. }
  12892. for (prop in parentConfig) {
  12893. if (hasOwnProp(parentConfig, prop) &&
  12894. !hasOwnProp(childConfig, prop) &&
  12895. isObject(parentConfig[prop])) {
  12896. // make sure changes to properties don't modify parent config
  12897. res[prop] = extend({}, res[prop]);
  12898. }
  12899. }
  12900. return res;
  12901. }
  12902. function Locale(config) {
  12903. if (config != null) {
  12904. this.set(config);
  12905. }
  12906. }
  12907. var keys;
  12908. if (Object.keys) {
  12909. keys = Object.keys;
  12910. } else {
  12911. keys = function (obj) {
  12912. var i, res = [];
  12913. for (i in obj) {
  12914. if (hasOwnProp(obj, i)) {
  12915. res.push(i);
  12916. }
  12917. }
  12918. return res;
  12919. };
  12920. }
  12921. var defaultCalendar = {
  12922. sameDay : '[Today at] LT',
  12923. nextDay : '[Tomorrow at] LT',
  12924. nextWeek : 'dddd [at] LT',
  12925. lastDay : '[Yesterday at] LT',
  12926. lastWeek : '[Last] dddd [at] LT',
  12927. sameElse : 'L'
  12928. };
  12929. function calendar (key, mom, now) {
  12930. var output = this._calendar[key] || this._calendar['sameElse'];
  12931. return isFunction(output) ? output.call(mom, now) : output;
  12932. }
  12933. var defaultLongDateFormat = {
  12934. LTS : 'h:mm:ss A',
  12935. LT : 'h:mm A',
  12936. L : 'MM/DD/YYYY',
  12937. LL : 'MMMM D, YYYY',
  12938. LLL : 'MMMM D, YYYY h:mm A',
  12939. LLLL : 'dddd, MMMM D, YYYY h:mm A'
  12940. };
  12941. function longDateFormat (key) {
  12942. var format = this._longDateFormat[key],
  12943. formatUpper = this._longDateFormat[key.toUpperCase()];
  12944. if (format || !formatUpper) {
  12945. return format;
  12946. }
  12947. this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
  12948. return val.slice(1);
  12949. });
  12950. return this._longDateFormat[key];
  12951. }
  12952. var defaultInvalidDate = 'Invalid date';
  12953. function invalidDate () {
  12954. return this._invalidDate;
  12955. }
  12956. var defaultOrdinal = '%d';
  12957. var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  12958. function ordinal (number) {
  12959. return this._ordinal.replace('%d', number);
  12960. }
  12961. var defaultRelativeTime = {
  12962. future : 'in %s',
  12963. past : '%s ago',
  12964. s : 'a few seconds',
  12965. ss : '%d seconds',
  12966. m : 'a minute',
  12967. mm : '%d minutes',
  12968. h : 'an hour',
  12969. hh : '%d hours',
  12970. d : 'a day',
  12971. dd : '%d days',
  12972. M : 'a month',
  12973. MM : '%d months',
  12974. y : 'a year',
  12975. yy : '%d years'
  12976. };
  12977. function relativeTime (number, withoutSuffix, string, isFuture) {
  12978. var output = this._relativeTime[string];
  12979. return (isFunction(output)) ?
  12980. output(number, withoutSuffix, string, isFuture) :
  12981. output.replace(/%d/i, number);
  12982. }
  12983. function pastFuture (diff, output) {
  12984. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  12985. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  12986. }
  12987. var aliases = {};
  12988. function addUnitAlias (unit, shorthand) {
  12989. var lowerCase = unit.toLowerCase();
  12990. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  12991. }
  12992. function normalizeUnits(units) {
  12993. return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
  12994. }
  12995. function normalizeObjectUnits(inputObject) {
  12996. var normalizedInput = {},
  12997. normalizedProp,
  12998. prop;
  12999. for (prop in inputObject) {
  13000. if (hasOwnProp(inputObject, prop)) {
  13001. normalizedProp = normalizeUnits(prop);
  13002. if (normalizedProp) {
  13003. normalizedInput[normalizedProp] = inputObject[prop];
  13004. }
  13005. }
  13006. }
  13007. return normalizedInput;
  13008. }
  13009. var priorities = {};
  13010. function addUnitPriority(unit, priority) {
  13011. priorities[unit] = priority;
  13012. }
  13013. function getPrioritizedUnits(unitsObj) {
  13014. var units = [];
  13015. for (var u in unitsObj) {
  13016. units.push({unit: u, priority: priorities[u]});
  13017. }
  13018. units.sort(function (a, b) {
  13019. return a.priority - b.priority;
  13020. });
  13021. return units;
  13022. }
  13023. function zeroFill(number, targetLength, forceSign) {
  13024. var absNumber = '' + Math.abs(number),
  13025. zerosToFill = targetLength - absNumber.length,
  13026. sign = number >= 0;
  13027. return (sign ? (forceSign ? '+' : '') : '-') +
  13028. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
  13029. }
  13030. 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;
  13031. var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  13032. var formatFunctions = {};
  13033. var formatTokenFunctions = {};
  13034. // token: 'M'
  13035. // padded: ['MM', 2]
  13036. // ordinal: 'Mo'
  13037. // callback: function () { this.month() + 1 }
  13038. function addFormatToken (token, padded, ordinal, callback) {
  13039. var func = callback;
  13040. if (typeof callback === 'string') {
  13041. func = function () {
  13042. return this[callback]();
  13043. };
  13044. }
  13045. if (token) {
  13046. formatTokenFunctions[token] = func;
  13047. }
  13048. if (padded) {
  13049. formatTokenFunctions[padded[0]] = function () {
  13050. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  13051. };
  13052. }
  13053. if (ordinal) {
  13054. formatTokenFunctions[ordinal] = function () {
  13055. return this.localeData().ordinal(func.apply(this, arguments), token);
  13056. };
  13057. }
  13058. }
  13059. function removeFormattingTokens(input) {
  13060. if (input.match(/\[[\s\S]/)) {
  13061. return input.replace(/^\[|\]$/g, '');
  13062. }
  13063. return input.replace(/\\/g, '');
  13064. }
  13065. function makeFormatFunction(format) {
  13066. var array = format.match(formattingTokens), i, length;
  13067. for (i = 0, length = array.length; i < length; i++) {
  13068. if (formatTokenFunctions[array[i]]) {
  13069. array[i] = formatTokenFunctions[array[i]];
  13070. } else {
  13071. array[i] = removeFormattingTokens(array[i]);
  13072. }
  13073. }
  13074. return function (mom) {
  13075. var output = '', i;
  13076. for (i = 0; i < length; i++) {
  13077. output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
  13078. }
  13079. return output;
  13080. };
  13081. }
  13082. // format date using native date object
  13083. function formatMoment(m, format) {
  13084. if (!m.isValid()) {
  13085. return m.localeData().invalidDate();
  13086. }
  13087. format = expandFormat(format, m.localeData());
  13088. formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
  13089. return formatFunctions[format](m);
  13090. }
  13091. function expandFormat(format, locale) {
  13092. var i = 5;
  13093. function replaceLongDateFormatTokens(input) {
  13094. return locale.longDateFormat(input) || input;
  13095. }
  13096. localFormattingTokens.lastIndex = 0;
  13097. while (i >= 0 && localFormattingTokens.test(format)) {
  13098. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  13099. localFormattingTokens.lastIndex = 0;
  13100. i -= 1;
  13101. }
  13102. return format;
  13103. }
  13104. var match1 = /\d/; // 0 - 9
  13105. var match2 = /\d\d/; // 00 - 99
  13106. var match3 = /\d{3}/; // 000 - 999
  13107. var match4 = /\d{4}/; // 0000 - 9999
  13108. var match6 = /[+-]?\d{6}/; // -999999 - 999999
  13109. var match1to2 = /\d\d?/; // 0 - 99
  13110. var match3to4 = /\d\d\d\d?/; // 999 - 9999
  13111. var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
  13112. var match1to3 = /\d{1,3}/; // 0 - 999
  13113. var match1to4 = /\d{1,4}/; // 0 - 9999
  13114. var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
  13115. var matchUnsigned = /\d+/; // 0 - inf
  13116. var matchSigned = /[+-]?\d+/; // -inf - inf
  13117. var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
  13118. var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  13119. var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
  13120. // any word (or two) characters or numbers including two/three word month in arabic.
  13121. // includes scottish gaelic two word and hyphenated months
  13122. 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;
  13123. var regexes = {};
  13124. function addRegexToken (token, regex, strictRegex) {
  13125. regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
  13126. return (isStrict && strictRegex) ? strictRegex : regex;
  13127. };
  13128. }
  13129. function getParseRegexForToken (token, config) {
  13130. if (!hasOwnProp(regexes, token)) {
  13131. return new RegExp(unescapeFormat(token));
  13132. }
  13133. return regexes[token](config._strict, config._locale);
  13134. }
  13135. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  13136. function unescapeFormat(s) {
  13137. return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  13138. return p1 || p2 || p3 || p4;
  13139. }));
  13140. }
  13141. function regexEscape(s) {
  13142. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  13143. }
  13144. var tokens = {};
  13145. function addParseToken (token, callback) {
  13146. var i, func = callback;
  13147. if (typeof token === 'string') {
  13148. token = [token];
  13149. }
  13150. if (isNumber(callback)) {
  13151. func = function (input, array) {
  13152. array[callback] = toInt(input);
  13153. };
  13154. }
  13155. for (i = 0; i < token.length; i++) {
  13156. tokens[token[i]] = func;
  13157. }
  13158. }
  13159. function addWeekParseToken (token, callback) {
  13160. addParseToken(token, function (input, array, config, token) {
  13161. config._w = config._w || {};
  13162. callback(input, config._w, config, token);
  13163. });
  13164. }
  13165. function addTimeToArrayFromToken(token, input, config) {
  13166. if (input != null && hasOwnProp(tokens, token)) {
  13167. tokens[token](input, config._a, config, token);
  13168. }
  13169. }
  13170. var YEAR = 0;
  13171. var MONTH = 1;
  13172. var DATE = 2;
  13173. var HOUR = 3;
  13174. var MINUTE = 4;
  13175. var SECOND = 5;
  13176. var MILLISECOND = 6;
  13177. var WEEK = 7;
  13178. var WEEKDAY = 8;
  13179. // FORMATTING
  13180. addFormatToken('Y', 0, 0, function () {
  13181. var y = this.year();
  13182. return y <= 9999 ? '' + y : '+' + y;
  13183. });
  13184. addFormatToken(0, ['YY', 2], 0, function () {
  13185. return this.year() % 100;
  13186. });
  13187. addFormatToken(0, ['YYYY', 4], 0, 'year');
  13188. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  13189. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  13190. // ALIASES
  13191. addUnitAlias('year', 'y');
  13192. // PRIORITIES
  13193. addUnitPriority('year', 1);
  13194. // PARSING
  13195. addRegexToken('Y', matchSigned);
  13196. addRegexToken('YY', match1to2, match2);
  13197. addRegexToken('YYYY', match1to4, match4);
  13198. addRegexToken('YYYYY', match1to6, match6);
  13199. addRegexToken('YYYYYY', match1to6, match6);
  13200. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  13201. addParseToken('YYYY', function (input, array) {
  13202. array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  13203. });
  13204. addParseToken('YY', function (input, array) {
  13205. array[YEAR] = hooks.parseTwoDigitYear(input);
  13206. });
  13207. addParseToken('Y', function (input, array) {
  13208. array[YEAR] = parseInt(input, 10);
  13209. });
  13210. // HELPERS
  13211. function daysInYear(year) {
  13212. return isLeapYear(year) ? 366 : 365;
  13213. }
  13214. function isLeapYear(year) {
  13215. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  13216. }
  13217. // HOOKS
  13218. hooks.parseTwoDigitYear = function (input) {
  13219. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  13220. };
  13221. // MOMENTS
  13222. var getSetYear = makeGetSet('FullYear', true);
  13223. function getIsLeapYear () {
  13224. return isLeapYear(this.year());
  13225. }
  13226. function makeGetSet (unit, keepTime) {
  13227. return function (value) {
  13228. if (value != null) {
  13229. set$1(this, unit, value);
  13230. hooks.updateOffset(this, keepTime);
  13231. return this;
  13232. } else {
  13233. return get(this, unit);
  13234. }
  13235. };
  13236. }
  13237. function get (mom, unit) {
  13238. return mom.isValid() ?
  13239. mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
  13240. }
  13241. function set$1 (mom, unit, value) {
  13242. if (mom.isValid() && !isNaN(value)) {
  13243. if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
  13244. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
  13245. }
  13246. else {
  13247. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  13248. }
  13249. }
  13250. }
  13251. // MOMENTS
  13252. function stringGet (units) {
  13253. units = normalizeUnits(units);
  13254. if (isFunction(this[units])) {
  13255. return this[units]();
  13256. }
  13257. return this;
  13258. }
  13259. function stringSet (units, value) {
  13260. if (typeof units === 'object') {
  13261. units = normalizeObjectUnits(units);
  13262. var prioritized = getPrioritizedUnits(units);
  13263. for (var i = 0; i < prioritized.length; i++) {
  13264. this[prioritized[i].unit](units[prioritized[i].unit]);
  13265. }
  13266. } else {
  13267. units = normalizeUnits(units);
  13268. if (isFunction(this[units])) {
  13269. return this[units](value);
  13270. }
  13271. }
  13272. return this;
  13273. }
  13274. function mod(n, x) {
  13275. return ((n % x) + x) % x;
  13276. }
  13277. var indexOf;
  13278. if (Array.prototype.indexOf) {
  13279. indexOf = Array.prototype.indexOf;
  13280. } else {
  13281. indexOf = function (o) {
  13282. // I know
  13283. var i;
  13284. for (i = 0; i < this.length; ++i) {
  13285. if (this[i] === o) {
  13286. return i;
  13287. }
  13288. }
  13289. return -1;
  13290. };
  13291. }
  13292. function daysInMonth(year, month) {
  13293. if (isNaN(year) || isNaN(month)) {
  13294. return NaN;
  13295. }
  13296. var modMonth = mod(month, 12);
  13297. year += (month - modMonth) / 12;
  13298. return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
  13299. }
  13300. // FORMATTING
  13301. addFormatToken('M', ['MM', 2], 'Mo', function () {
  13302. return this.month() + 1;
  13303. });
  13304. addFormatToken('MMM', 0, 0, function (format) {
  13305. return this.localeData().monthsShort(this, format);
  13306. });
  13307. addFormatToken('MMMM', 0, 0, function (format) {
  13308. return this.localeData().months(this, format);
  13309. });
  13310. // ALIASES
  13311. addUnitAlias('month', 'M');
  13312. // PRIORITY
  13313. addUnitPriority('month', 8);
  13314. // PARSING
  13315. addRegexToken('M', match1to2);
  13316. addRegexToken('MM', match1to2, match2);
  13317. addRegexToken('MMM', function (isStrict, locale) {
  13318. return locale.monthsShortRegex(isStrict);
  13319. });
  13320. addRegexToken('MMMM', function (isStrict, locale) {
  13321. return locale.monthsRegex(isStrict);
  13322. });
  13323. addParseToken(['M', 'MM'], function (input, array) {
  13324. array[MONTH] = toInt(input) - 1;
  13325. });
  13326. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  13327. var month = config._locale.monthsParse(input, token, config._strict);
  13328. // if we didn't find a month name, mark the date as invalid.
  13329. if (month != null) {
  13330. array[MONTH] = month;
  13331. } else {
  13332. getParsingFlags(config).invalidMonth = input;
  13333. }
  13334. });
  13335. // LOCALES
  13336. var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
  13337. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
  13338. function localeMonths (m, format) {
  13339. if (!m) {
  13340. return isArray(this._months) ? this._months :
  13341. this._months['standalone'];
  13342. }
  13343. return isArray(this._months) ? this._months[m.month()] :
  13344. this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
  13345. }
  13346. var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
  13347. function localeMonthsShort (m, format) {
  13348. if (!m) {
  13349. return isArray(this._monthsShort) ? this._monthsShort :
  13350. this._monthsShort['standalone'];
  13351. }
  13352. return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
  13353. this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
  13354. }
  13355. function handleStrictParse(monthName, format, strict) {
  13356. var i, ii, mom, llc = monthName.toLocaleLowerCase();
  13357. if (!this._monthsParse) {
  13358. // this is not used
  13359. this._monthsParse = [];
  13360. this._longMonthsParse = [];
  13361. this._shortMonthsParse = [];
  13362. for (i = 0; i < 12; ++i) {
  13363. mom = createUTC([2000, i]);
  13364. this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
  13365. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  13366. }
  13367. }
  13368. if (strict) {
  13369. if (format === 'MMM') {
  13370. ii = indexOf.call(this._shortMonthsParse, llc);
  13371. return ii !== -1 ? ii : null;
  13372. } else {
  13373. ii = indexOf.call(this._longMonthsParse, llc);
  13374. return ii !== -1 ? ii : null;
  13375. }
  13376. } else {
  13377. if (format === 'MMM') {
  13378. ii = indexOf.call(this._shortMonthsParse, llc);
  13379. if (ii !== -1) {
  13380. return ii;
  13381. }
  13382. ii = indexOf.call(this._longMonthsParse, llc);
  13383. return ii !== -1 ? ii : null;
  13384. } else {
  13385. ii = indexOf.call(this._longMonthsParse, llc);
  13386. if (ii !== -1) {
  13387. return ii;
  13388. }
  13389. ii = indexOf.call(this._shortMonthsParse, llc);
  13390. return ii !== -1 ? ii : null;
  13391. }
  13392. }
  13393. }
  13394. function localeMonthsParse (monthName, format, strict) {
  13395. var i, mom, regex;
  13396. if (this._monthsParseExact) {
  13397. return handleStrictParse.call(this, monthName, format, strict);
  13398. }
  13399. if (!this._monthsParse) {
  13400. this._monthsParse = [];
  13401. this._longMonthsParse = [];
  13402. this._shortMonthsParse = [];
  13403. }
  13404. // TODO: add sorting
  13405. // Sorting makes sure if one month (or abbr) is a prefix of another
  13406. // see sorting in computeMonthsParse
  13407. for (i = 0; i < 12; i++) {
  13408. // make the regex if we don't have it already
  13409. mom = createUTC([2000, i]);
  13410. if (strict && !this._longMonthsParse[i]) {
  13411. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  13412. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  13413. }
  13414. if (!strict && !this._monthsParse[i]) {
  13415. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  13416. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13417. }
  13418. // test the regex
  13419. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  13420. return i;
  13421. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  13422. return i;
  13423. } else if (!strict && this._monthsParse[i].test(monthName)) {
  13424. return i;
  13425. }
  13426. }
  13427. }
  13428. // MOMENTS
  13429. function setMonth (mom, value) {
  13430. var dayOfMonth;
  13431. if (!mom.isValid()) {
  13432. // No op
  13433. return mom;
  13434. }
  13435. if (typeof value === 'string') {
  13436. if (/^\d+$/.test(value)) {
  13437. value = toInt(value);
  13438. } else {
  13439. value = mom.localeData().monthsParse(value);
  13440. // TODO: Another silent failure?
  13441. if (!isNumber(value)) {
  13442. return mom;
  13443. }
  13444. }
  13445. }
  13446. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  13447. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  13448. return mom;
  13449. }
  13450. function getSetMonth (value) {
  13451. if (value != null) {
  13452. setMonth(this, value);
  13453. hooks.updateOffset(this, true);
  13454. return this;
  13455. } else {
  13456. return get(this, 'Month');
  13457. }
  13458. }
  13459. function getDaysInMonth () {
  13460. return daysInMonth(this.year(), this.month());
  13461. }
  13462. var defaultMonthsShortRegex = matchWord;
  13463. function monthsShortRegex (isStrict) {
  13464. if (this._monthsParseExact) {
  13465. if (!hasOwnProp(this, '_monthsRegex')) {
  13466. computeMonthsParse.call(this);
  13467. }
  13468. if (isStrict) {
  13469. return this._monthsShortStrictRegex;
  13470. } else {
  13471. return this._monthsShortRegex;
  13472. }
  13473. } else {
  13474. if (!hasOwnProp(this, '_monthsShortRegex')) {
  13475. this._monthsShortRegex = defaultMonthsShortRegex;
  13476. }
  13477. return this._monthsShortStrictRegex && isStrict ?
  13478. this._monthsShortStrictRegex : this._monthsShortRegex;
  13479. }
  13480. }
  13481. var defaultMonthsRegex = matchWord;
  13482. function monthsRegex (isStrict) {
  13483. if (this._monthsParseExact) {
  13484. if (!hasOwnProp(this, '_monthsRegex')) {
  13485. computeMonthsParse.call(this);
  13486. }
  13487. if (isStrict) {
  13488. return this._monthsStrictRegex;
  13489. } else {
  13490. return this._monthsRegex;
  13491. }
  13492. } else {
  13493. if (!hasOwnProp(this, '_monthsRegex')) {
  13494. this._monthsRegex = defaultMonthsRegex;
  13495. }
  13496. return this._monthsStrictRegex && isStrict ?
  13497. this._monthsStrictRegex : this._monthsRegex;
  13498. }
  13499. }
  13500. function computeMonthsParse () {
  13501. function cmpLenRev(a, b) {
  13502. return b.length - a.length;
  13503. }
  13504. var shortPieces = [], longPieces = [], mixedPieces = [],
  13505. i, mom;
  13506. for (i = 0; i < 12; i++) {
  13507. // make the regex if we don't have it already
  13508. mom = createUTC([2000, i]);
  13509. shortPieces.push(this.monthsShort(mom, ''));
  13510. longPieces.push(this.months(mom, ''));
  13511. mixedPieces.push(this.months(mom, ''));
  13512. mixedPieces.push(this.monthsShort(mom, ''));
  13513. }
  13514. // Sorting makes sure if one month (or abbr) is a prefix of another it
  13515. // will match the longer piece.
  13516. shortPieces.sort(cmpLenRev);
  13517. longPieces.sort(cmpLenRev);
  13518. mixedPieces.sort(cmpLenRev);
  13519. for (i = 0; i < 12; i++) {
  13520. shortPieces[i] = regexEscape(shortPieces[i]);
  13521. longPieces[i] = regexEscape(longPieces[i]);
  13522. }
  13523. for (i = 0; i < 24; i++) {
  13524. mixedPieces[i] = regexEscape(mixedPieces[i]);
  13525. }
  13526. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  13527. this._monthsShortRegex = this._monthsRegex;
  13528. this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  13529. this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  13530. }
  13531. function createDate (y, m, d, h, M, s, ms) {
  13532. // can't just apply() to create a date:
  13533. // https://stackoverflow.com/q/181348
  13534. var date;
  13535. // the date constructor remaps years 0-99 to 1900-1999
  13536. if (y < 100 && y >= 0) {
  13537. // preserve leap years using a full 400 year cycle, then reset
  13538. date = new Date(y + 400, m, d, h, M, s, ms);
  13539. if (isFinite(date.getFullYear())) {
  13540. date.setFullYear(y);
  13541. }
  13542. } else {
  13543. date = new Date(y, m, d, h, M, s, ms);
  13544. }
  13545. return date;
  13546. }
  13547. function createUTCDate (y) {
  13548. var date;
  13549. // the Date.UTC function remaps years 0-99 to 1900-1999
  13550. if (y < 100 && y >= 0) {
  13551. var args = Array.prototype.slice.call(arguments);
  13552. // preserve leap years using a full 400 year cycle, then reset
  13553. args[0] = y + 400;
  13554. date = new Date(Date.UTC.apply(null, args));
  13555. if (isFinite(date.getUTCFullYear())) {
  13556. date.setUTCFullYear(y);
  13557. }
  13558. } else {
  13559. date = new Date(Date.UTC.apply(null, arguments));
  13560. }
  13561. return date;
  13562. }
  13563. // start-of-first-week - start-of-year
  13564. function firstWeekOffset(year, dow, doy) {
  13565. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  13566. fwd = 7 + dow - doy,
  13567. // first-week day local weekday -- which local weekday is fwd
  13568. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  13569. return -fwdlw + fwd - 1;
  13570. }
  13571. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  13572. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  13573. var localWeekday = (7 + weekday - dow) % 7,
  13574. weekOffset = firstWeekOffset(year, dow, doy),
  13575. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  13576. resYear, resDayOfYear;
  13577. if (dayOfYear <= 0) {
  13578. resYear = year - 1;
  13579. resDayOfYear = daysInYear(resYear) + dayOfYear;
  13580. } else if (dayOfYear > daysInYear(year)) {
  13581. resYear = year + 1;
  13582. resDayOfYear = dayOfYear - daysInYear(year);
  13583. } else {
  13584. resYear = year;
  13585. resDayOfYear = dayOfYear;
  13586. }
  13587. return {
  13588. year: resYear,
  13589. dayOfYear: resDayOfYear
  13590. };
  13591. }
  13592. function weekOfYear(mom, dow, doy) {
  13593. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  13594. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  13595. resWeek, resYear;
  13596. if (week < 1) {
  13597. resYear = mom.year() - 1;
  13598. resWeek = week + weeksInYear(resYear, dow, doy);
  13599. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  13600. resWeek = week - weeksInYear(mom.year(), dow, doy);
  13601. resYear = mom.year() + 1;
  13602. } else {
  13603. resYear = mom.year();
  13604. resWeek = week;
  13605. }
  13606. return {
  13607. week: resWeek,
  13608. year: resYear
  13609. };
  13610. }
  13611. function weeksInYear(year, dow, doy) {
  13612. var weekOffset = firstWeekOffset(year, dow, doy),
  13613. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  13614. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  13615. }
  13616. // FORMATTING
  13617. addFormatToken('w', ['ww', 2], 'wo', 'week');
  13618. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  13619. // ALIASES
  13620. addUnitAlias('week', 'w');
  13621. addUnitAlias('isoWeek', 'W');
  13622. // PRIORITIES
  13623. addUnitPriority('week', 5);
  13624. addUnitPriority('isoWeek', 5);
  13625. // PARSING
  13626. addRegexToken('w', match1to2);
  13627. addRegexToken('ww', match1to2, match2);
  13628. addRegexToken('W', match1to2);
  13629. addRegexToken('WW', match1to2, match2);
  13630. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
  13631. week[token.substr(0, 1)] = toInt(input);
  13632. });
  13633. // HELPERS
  13634. // LOCALES
  13635. function localeWeek (mom) {
  13636. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  13637. }
  13638. var defaultLocaleWeek = {
  13639. dow : 0, // Sunday is the first day of the week.
  13640. doy : 6 // The week that contains Jan 6th is the first week of the year.
  13641. };
  13642. function localeFirstDayOfWeek () {
  13643. return this._week.dow;
  13644. }
  13645. function localeFirstDayOfYear () {
  13646. return this._week.doy;
  13647. }
  13648. // MOMENTS
  13649. function getSetWeek (input) {
  13650. var week = this.localeData().week(this);
  13651. return input == null ? week : this.add((input - week) * 7, 'd');
  13652. }
  13653. function getSetISOWeek (input) {
  13654. var week = weekOfYear(this, 1, 4).week;
  13655. return input == null ? week : this.add((input - week) * 7, 'd');
  13656. }
  13657. // FORMATTING
  13658. addFormatToken('d', 0, 'do', 'day');
  13659. addFormatToken('dd', 0, 0, function (format) {
  13660. return this.localeData().weekdaysMin(this, format);
  13661. });
  13662. addFormatToken('ddd', 0, 0, function (format) {
  13663. return this.localeData().weekdaysShort(this, format);
  13664. });
  13665. addFormatToken('dddd', 0, 0, function (format) {
  13666. return this.localeData().weekdays(this, format);
  13667. });
  13668. addFormatToken('e', 0, 0, 'weekday');
  13669. addFormatToken('E', 0, 0, 'isoWeekday');
  13670. // ALIASES
  13671. addUnitAlias('day', 'd');
  13672. addUnitAlias('weekday', 'e');
  13673. addUnitAlias('isoWeekday', 'E');
  13674. // PRIORITY
  13675. addUnitPriority('day', 11);
  13676. addUnitPriority('weekday', 11);
  13677. addUnitPriority('isoWeekday', 11);
  13678. // PARSING
  13679. addRegexToken('d', match1to2);
  13680. addRegexToken('e', match1to2);
  13681. addRegexToken('E', match1to2);
  13682. addRegexToken('dd', function (isStrict, locale) {
  13683. return locale.weekdaysMinRegex(isStrict);
  13684. });
  13685. addRegexToken('ddd', function (isStrict, locale) {
  13686. return locale.weekdaysShortRegex(isStrict);
  13687. });
  13688. addRegexToken('dddd', function (isStrict, locale) {
  13689. return locale.weekdaysRegex(isStrict);
  13690. });
  13691. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  13692. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  13693. // if we didn't get a weekday name, mark the date as invalid
  13694. if (weekday != null) {
  13695. week.d = weekday;
  13696. } else {
  13697. getParsingFlags(config).invalidWeekday = input;
  13698. }
  13699. });
  13700. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  13701. week[token] = toInt(input);
  13702. });
  13703. // HELPERS
  13704. function parseWeekday(input, locale) {
  13705. if (typeof input !== 'string') {
  13706. return input;
  13707. }
  13708. if (!isNaN(input)) {
  13709. return parseInt(input, 10);
  13710. }
  13711. input = locale.weekdaysParse(input);
  13712. if (typeof input === 'number') {
  13713. return input;
  13714. }
  13715. return null;
  13716. }
  13717. function parseIsoWeekday(input, locale) {
  13718. if (typeof input === 'string') {
  13719. return locale.weekdaysParse(input) % 7 || 7;
  13720. }
  13721. return isNaN(input) ? null : input;
  13722. }
  13723. // LOCALES
  13724. function shiftWeekdays (ws, n) {
  13725. return ws.slice(n, 7).concat(ws.slice(0, n));
  13726. }
  13727. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
  13728. function localeWeekdays (m, format) {
  13729. var weekdays = isArray(this._weekdays) ? this._weekdays :
  13730. this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone'];
  13731. return (m === true) ? shiftWeekdays(weekdays, this._week.dow)
  13732. : (m) ? weekdays[m.day()] : weekdays;
  13733. }
  13734. var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
  13735. function localeWeekdaysShort (m) {
  13736. return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  13737. : (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
  13738. }
  13739. var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
  13740. function localeWeekdaysMin (m) {
  13741. return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  13742. : (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
  13743. }
  13744. function handleStrictParse$1(weekdayName, format, strict) {
  13745. var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
  13746. if (!this._weekdaysParse) {
  13747. this._weekdaysParse = [];
  13748. this._shortWeekdaysParse = [];
  13749. this._minWeekdaysParse = [];
  13750. for (i = 0; i < 7; ++i) {
  13751. mom = createUTC([2000, 1]).day(i);
  13752. this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
  13753. this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
  13754. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  13755. }
  13756. }
  13757. if (strict) {
  13758. if (format === 'dddd') {
  13759. ii = indexOf.call(this._weekdaysParse, llc);
  13760. return ii !== -1 ? ii : null;
  13761. } else if (format === 'ddd') {
  13762. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13763. return ii !== -1 ? ii : null;
  13764. } else {
  13765. ii = indexOf.call(this._minWeekdaysParse, llc);
  13766. return ii !== -1 ? ii : null;
  13767. }
  13768. } else {
  13769. if (format === 'dddd') {
  13770. ii = indexOf.call(this._weekdaysParse, llc);
  13771. if (ii !== -1) {
  13772. return ii;
  13773. }
  13774. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13775. if (ii !== -1) {
  13776. return ii;
  13777. }
  13778. ii = indexOf.call(this._minWeekdaysParse, llc);
  13779. return ii !== -1 ? ii : null;
  13780. } else if (format === 'ddd') {
  13781. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13782. if (ii !== -1) {
  13783. return ii;
  13784. }
  13785. ii = indexOf.call(this._weekdaysParse, llc);
  13786. if (ii !== -1) {
  13787. return ii;
  13788. }
  13789. ii = indexOf.call(this._minWeekdaysParse, llc);
  13790. return ii !== -1 ? ii : null;
  13791. } else {
  13792. ii = indexOf.call(this._minWeekdaysParse, llc);
  13793. if (ii !== -1) {
  13794. return ii;
  13795. }
  13796. ii = indexOf.call(this._weekdaysParse, llc);
  13797. if (ii !== -1) {
  13798. return ii;
  13799. }
  13800. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13801. return ii !== -1 ? ii : null;
  13802. }
  13803. }
  13804. }
  13805. function localeWeekdaysParse (weekdayName, format, strict) {
  13806. var i, mom, regex;
  13807. if (this._weekdaysParseExact) {
  13808. return handleStrictParse$1.call(this, weekdayName, format, strict);
  13809. }
  13810. if (!this._weekdaysParse) {
  13811. this._weekdaysParse = [];
  13812. this._minWeekdaysParse = [];
  13813. this._shortWeekdaysParse = [];
  13814. this._fullWeekdaysParse = [];
  13815. }
  13816. for (i = 0; i < 7; i++) {
  13817. // make the regex if we don't have it already
  13818. mom = createUTC([2000, 1]).day(i);
  13819. if (strict && !this._fullWeekdaysParse[i]) {
  13820. this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
  13821. this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
  13822. this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
  13823. }
  13824. if (!this._weekdaysParse[i]) {
  13825. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  13826. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13827. }
  13828. // test the regex
  13829. if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
  13830. return i;
  13831. } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
  13832. return i;
  13833. } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
  13834. return i;
  13835. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  13836. return i;
  13837. }
  13838. }
  13839. }
  13840. // MOMENTS
  13841. function getSetDayOfWeek (input) {
  13842. if (!this.isValid()) {
  13843. return input != null ? this : NaN;
  13844. }
  13845. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  13846. if (input != null) {
  13847. input = parseWeekday(input, this.localeData());
  13848. return this.add(input - day, 'd');
  13849. } else {
  13850. return day;
  13851. }
  13852. }
  13853. function getSetLocaleDayOfWeek (input) {
  13854. if (!this.isValid()) {
  13855. return input != null ? this : NaN;
  13856. }
  13857. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  13858. return input == null ? weekday : this.add(input - weekday, 'd');
  13859. }
  13860. function getSetISODayOfWeek (input) {
  13861. if (!this.isValid()) {
  13862. return input != null ? this : NaN;
  13863. }
  13864. // behaves the same as moment#day except
  13865. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  13866. // as a setter, sunday should belong to the previous week.
  13867. if (input != null) {
  13868. var weekday = parseIsoWeekday(input, this.localeData());
  13869. return this.day(this.day() % 7 ? weekday : weekday - 7);
  13870. } else {
  13871. return this.day() || 7;
  13872. }
  13873. }
  13874. var defaultWeekdaysRegex = matchWord;
  13875. function weekdaysRegex (isStrict) {
  13876. if (this._weekdaysParseExact) {
  13877. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13878. computeWeekdaysParse.call(this);
  13879. }
  13880. if (isStrict) {
  13881. return this._weekdaysStrictRegex;
  13882. } else {
  13883. return this._weekdaysRegex;
  13884. }
  13885. } else {
  13886. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13887. this._weekdaysRegex = defaultWeekdaysRegex;
  13888. }
  13889. return this._weekdaysStrictRegex && isStrict ?
  13890. this._weekdaysStrictRegex : this._weekdaysRegex;
  13891. }
  13892. }
  13893. var defaultWeekdaysShortRegex = matchWord;
  13894. function weekdaysShortRegex (isStrict) {
  13895. if (this._weekdaysParseExact) {
  13896. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13897. computeWeekdaysParse.call(this);
  13898. }
  13899. if (isStrict) {
  13900. return this._weekdaysShortStrictRegex;
  13901. } else {
  13902. return this._weekdaysShortRegex;
  13903. }
  13904. } else {
  13905. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  13906. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  13907. }
  13908. return this._weekdaysShortStrictRegex && isStrict ?
  13909. this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
  13910. }
  13911. }
  13912. var defaultWeekdaysMinRegex = matchWord;
  13913. function weekdaysMinRegex (isStrict) {
  13914. if (this._weekdaysParseExact) {
  13915. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13916. computeWeekdaysParse.call(this);
  13917. }
  13918. if (isStrict) {
  13919. return this._weekdaysMinStrictRegex;
  13920. } else {
  13921. return this._weekdaysMinRegex;
  13922. }
  13923. } else {
  13924. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  13925. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  13926. }
  13927. return this._weekdaysMinStrictRegex && isStrict ?
  13928. this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
  13929. }
  13930. }
  13931. function computeWeekdaysParse () {
  13932. function cmpLenRev(a, b) {
  13933. return b.length - a.length;
  13934. }
  13935. var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
  13936. i, mom, minp, shortp, longp;
  13937. for (i = 0; i < 7; i++) {
  13938. // make the regex if we don't have it already
  13939. mom = createUTC([2000, 1]).day(i);
  13940. minp = this.weekdaysMin(mom, '');
  13941. shortp = this.weekdaysShort(mom, '');
  13942. longp = this.weekdays(mom, '');
  13943. minPieces.push(minp);
  13944. shortPieces.push(shortp);
  13945. longPieces.push(longp);
  13946. mixedPieces.push(minp);
  13947. mixedPieces.push(shortp);
  13948. mixedPieces.push(longp);
  13949. }
  13950. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  13951. // will match the longer piece.
  13952. minPieces.sort(cmpLenRev);
  13953. shortPieces.sort(cmpLenRev);
  13954. longPieces.sort(cmpLenRev);
  13955. mixedPieces.sort(cmpLenRev);
  13956. for (i = 0; i < 7; i++) {
  13957. shortPieces[i] = regexEscape(shortPieces[i]);
  13958. longPieces[i] = regexEscape(longPieces[i]);
  13959. mixedPieces[i] = regexEscape(mixedPieces[i]);
  13960. }
  13961. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  13962. this._weekdaysShortRegex = this._weekdaysRegex;
  13963. this._weekdaysMinRegex = this._weekdaysRegex;
  13964. this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  13965. this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  13966. this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
  13967. }
  13968. // FORMATTING
  13969. function hFormat() {
  13970. return this.hours() % 12 || 12;
  13971. }
  13972. function kFormat() {
  13973. return this.hours() || 24;
  13974. }
  13975. addFormatToken('H', ['HH', 2], 0, 'hour');
  13976. addFormatToken('h', ['hh', 2], 0, hFormat);
  13977. addFormatToken('k', ['kk', 2], 0, kFormat);
  13978. addFormatToken('hmm', 0, 0, function () {
  13979. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  13980. });
  13981. addFormatToken('hmmss', 0, 0, function () {
  13982. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
  13983. zeroFill(this.seconds(), 2);
  13984. });
  13985. addFormatToken('Hmm', 0, 0, function () {
  13986. return '' + this.hours() + zeroFill(this.minutes(), 2);
  13987. });
  13988. addFormatToken('Hmmss', 0, 0, function () {
  13989. return '' + this.hours() + zeroFill(this.minutes(), 2) +
  13990. zeroFill(this.seconds(), 2);
  13991. });
  13992. function meridiem (token, lowercase) {
  13993. addFormatToken(token, 0, 0, function () {
  13994. return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
  13995. });
  13996. }
  13997. meridiem('a', true);
  13998. meridiem('A', false);
  13999. // ALIASES
  14000. addUnitAlias('hour', 'h');
  14001. // PRIORITY
  14002. addUnitPriority('hour', 13);
  14003. // PARSING
  14004. function matchMeridiem (isStrict, locale) {
  14005. return locale._meridiemParse;
  14006. }
  14007. addRegexToken('a', matchMeridiem);
  14008. addRegexToken('A', matchMeridiem);
  14009. addRegexToken('H', match1to2);
  14010. addRegexToken('h', match1to2);
  14011. addRegexToken('k', match1to2);
  14012. addRegexToken('HH', match1to2, match2);
  14013. addRegexToken('hh', match1to2, match2);
  14014. addRegexToken('kk', match1to2, match2);
  14015. addRegexToken('hmm', match3to4);
  14016. addRegexToken('hmmss', match5to6);
  14017. addRegexToken('Hmm', match3to4);
  14018. addRegexToken('Hmmss', match5to6);
  14019. addParseToken(['H', 'HH'], HOUR);
  14020. addParseToken(['k', 'kk'], function (input, array, config) {
  14021. var kInput = toInt(input);
  14022. array[HOUR] = kInput === 24 ? 0 : kInput;
  14023. });
  14024. addParseToken(['a', 'A'], function (input, array, config) {
  14025. config._isPm = config._locale.isPM(input);
  14026. config._meridiem = input;
  14027. });
  14028. addParseToken(['h', 'hh'], function (input, array, config) {
  14029. array[HOUR] = toInt(input);
  14030. getParsingFlags(config).bigHour = true;
  14031. });
  14032. addParseToken('hmm', function (input, array, config) {
  14033. var pos = input.length - 2;
  14034. array[HOUR] = toInt(input.substr(0, pos));
  14035. array[MINUTE] = toInt(input.substr(pos));
  14036. getParsingFlags(config).bigHour = true;
  14037. });
  14038. addParseToken('hmmss', function (input, array, config) {
  14039. var pos1 = input.length - 4;
  14040. var pos2 = input.length - 2;
  14041. array[HOUR] = toInt(input.substr(0, pos1));
  14042. array[MINUTE] = toInt(input.substr(pos1, 2));
  14043. array[SECOND] = toInt(input.substr(pos2));
  14044. getParsingFlags(config).bigHour = true;
  14045. });
  14046. addParseToken('Hmm', function (input, array, config) {
  14047. var pos = input.length - 2;
  14048. array[HOUR] = toInt(input.substr(0, pos));
  14049. array[MINUTE] = toInt(input.substr(pos));
  14050. });
  14051. addParseToken('Hmmss', function (input, array, config) {
  14052. var pos1 = input.length - 4;
  14053. var pos2 = input.length - 2;
  14054. array[HOUR] = toInt(input.substr(0, pos1));
  14055. array[MINUTE] = toInt(input.substr(pos1, 2));
  14056. array[SECOND] = toInt(input.substr(pos2));
  14057. });
  14058. // LOCALES
  14059. function localeIsPM (input) {
  14060. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  14061. // Using charAt should be more compatible.
  14062. return ((input + '').toLowerCase().charAt(0) === 'p');
  14063. }
  14064. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  14065. function localeMeridiem (hours, minutes, isLower) {
  14066. if (hours > 11) {
  14067. return isLower ? 'pm' : 'PM';
  14068. } else {
  14069. return isLower ? 'am' : 'AM';
  14070. }
  14071. }
  14072. // MOMENTS
  14073. // Setting the hour should keep the time, because the user explicitly
  14074. // specified which hour they want. So trying to maintain the same hour (in
  14075. // a new timezone) makes sense. Adding/subtracting hours does not follow
  14076. // this rule.
  14077. var getSetHour = makeGetSet('Hours', true);
  14078. var baseConfig = {
  14079. calendar: defaultCalendar,
  14080. longDateFormat: defaultLongDateFormat,
  14081. invalidDate: defaultInvalidDate,
  14082. ordinal: defaultOrdinal,
  14083. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  14084. relativeTime: defaultRelativeTime,
  14085. months: defaultLocaleMonths,
  14086. monthsShort: defaultLocaleMonthsShort,
  14087. week: defaultLocaleWeek,
  14088. weekdays: defaultLocaleWeekdays,
  14089. weekdaysMin: defaultLocaleWeekdaysMin,
  14090. weekdaysShort: defaultLocaleWeekdaysShort,
  14091. meridiemParse: defaultLocaleMeridiemParse
  14092. };
  14093. // internal storage for locale config files
  14094. var locales = {};
  14095. var localeFamilies = {};
  14096. var globalLocale;
  14097. function normalizeLocale(key) {
  14098. return key ? key.toLowerCase().replace('_', '-') : key;
  14099. }
  14100. // pick the locale from the array
  14101. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  14102. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  14103. function chooseLocale(names) {
  14104. var i = 0, j, next, locale, split;
  14105. while (i < names.length) {
  14106. split = normalizeLocale(names[i]).split('-');
  14107. j = split.length;
  14108. next = normalizeLocale(names[i + 1]);
  14109. next = next ? next.split('-') : null;
  14110. while (j > 0) {
  14111. locale = loadLocale(split.slice(0, j).join('-'));
  14112. if (locale) {
  14113. return locale;
  14114. }
  14115. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  14116. //the next array item is better than a shallower substring of this one
  14117. break;
  14118. }
  14119. j--;
  14120. }
  14121. i++;
  14122. }
  14123. return globalLocale;
  14124. }
  14125. function loadLocale(name) {
  14126. var oldLocale = null;
  14127. // TODO: Find a better way to register and load all the locales in Node
  14128. if (!locales[name] && ('object' !== 'undefined') &&
  14129. module && module.exports) {
  14130. try {
  14131. oldLocale = globalLocale._abbr;
  14132. var aliasedRequire = commonjsRequire;
  14133. aliasedRequire('./locale/' + name);
  14134. getSetGlobalLocale(oldLocale);
  14135. } catch (e) {}
  14136. }
  14137. return locales[name];
  14138. }
  14139. // This function will load locale and then set the global locale. If
  14140. // no arguments are passed in, it will simply return the current global
  14141. // locale key.
  14142. function getSetGlobalLocale (key, values) {
  14143. var data;
  14144. if (key) {
  14145. if (isUndefined(values)) {
  14146. data = getLocale(key);
  14147. }
  14148. else {
  14149. data = defineLocale(key, values);
  14150. }
  14151. if (data) {
  14152. // moment.duration._locale = moment._locale = data;
  14153. globalLocale = data;
  14154. }
  14155. else {
  14156. if ((typeof console !== 'undefined') && console.warn) {
  14157. //warn user if arguments are passed but the locale could not be set
  14158. console.warn('Locale ' + key + ' not found. Did you forget to load it?');
  14159. }
  14160. }
  14161. }
  14162. return globalLocale._abbr;
  14163. }
  14164. function defineLocale (name, config) {
  14165. if (config !== null) {
  14166. var locale, parentConfig = baseConfig;
  14167. config.abbr = name;
  14168. if (locales[name] != null) {
  14169. deprecateSimple('defineLocaleOverride',
  14170. 'use moment.updateLocale(localeName, config) to change ' +
  14171. 'an existing locale. moment.defineLocale(localeName, ' +
  14172. 'config) should only be used for creating a new locale ' +
  14173. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
  14174. parentConfig = locales[name]._config;
  14175. } else if (config.parentLocale != null) {
  14176. if (locales[config.parentLocale] != null) {
  14177. parentConfig = locales[config.parentLocale]._config;
  14178. } else {
  14179. locale = loadLocale(config.parentLocale);
  14180. if (locale != null) {
  14181. parentConfig = locale._config;
  14182. } else {
  14183. if (!localeFamilies[config.parentLocale]) {
  14184. localeFamilies[config.parentLocale] = [];
  14185. }
  14186. localeFamilies[config.parentLocale].push({
  14187. name: name,
  14188. config: config
  14189. });
  14190. return null;
  14191. }
  14192. }
  14193. }
  14194. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  14195. if (localeFamilies[name]) {
  14196. localeFamilies[name].forEach(function (x) {
  14197. defineLocale(x.name, x.config);
  14198. });
  14199. }
  14200. // backwards compat for now: also set the locale
  14201. // make sure we set the locale AFTER all child locales have been
  14202. // created, so we won't end up with the child locale set.
  14203. getSetGlobalLocale(name);
  14204. return locales[name];
  14205. } else {
  14206. // useful for testing
  14207. delete locales[name];
  14208. return null;
  14209. }
  14210. }
  14211. function updateLocale(name, config) {
  14212. if (config != null) {
  14213. var locale, tmpLocale, parentConfig = baseConfig;
  14214. // MERGE
  14215. tmpLocale = loadLocale(name);
  14216. if (tmpLocale != null) {
  14217. parentConfig = tmpLocale._config;
  14218. }
  14219. config = mergeConfigs(parentConfig, config);
  14220. locale = new Locale(config);
  14221. locale.parentLocale = locales[name];
  14222. locales[name] = locale;
  14223. // backwards compat for now: also set the locale
  14224. getSetGlobalLocale(name);
  14225. } else {
  14226. // pass null for config to unupdate, useful for tests
  14227. if (locales[name] != null) {
  14228. if (locales[name].parentLocale != null) {
  14229. locales[name] = locales[name].parentLocale;
  14230. } else if (locales[name] != null) {
  14231. delete locales[name];
  14232. }
  14233. }
  14234. }
  14235. return locales[name];
  14236. }
  14237. // returns locale data
  14238. function getLocale (key) {
  14239. var locale;
  14240. if (key && key._locale && key._locale._abbr) {
  14241. key = key._locale._abbr;
  14242. }
  14243. if (!key) {
  14244. return globalLocale;
  14245. }
  14246. if (!isArray(key)) {
  14247. //short-circuit everything else
  14248. locale = loadLocale(key);
  14249. if (locale) {
  14250. return locale;
  14251. }
  14252. key = [key];
  14253. }
  14254. return chooseLocale(key);
  14255. }
  14256. function listLocales() {
  14257. return keys(locales);
  14258. }
  14259. function checkOverflow (m) {
  14260. var overflow;
  14261. var a = m._a;
  14262. if (a && getParsingFlags(m).overflow === -2) {
  14263. overflow =
  14264. a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
  14265. a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
  14266. a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
  14267. a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
  14268. a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
  14269. a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
  14270. -1;
  14271. if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  14272. overflow = DATE;
  14273. }
  14274. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  14275. overflow = WEEK;
  14276. }
  14277. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  14278. overflow = WEEKDAY;
  14279. }
  14280. getParsingFlags(m).overflow = overflow;
  14281. }
  14282. return m;
  14283. }
  14284. // Pick the first defined of two or three arguments.
  14285. function defaults(a, b, c) {
  14286. if (a != null) {
  14287. return a;
  14288. }
  14289. if (b != null) {
  14290. return b;
  14291. }
  14292. return c;
  14293. }
  14294. function currentDateArray(config) {
  14295. // hooks is actually the exported moment object
  14296. var nowValue = new Date(hooks.now());
  14297. if (config._useUTC) {
  14298. return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
  14299. }
  14300. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  14301. }
  14302. // convert an array to a date.
  14303. // the array should mirror the parameters below
  14304. // note: all values past the year are optional and will default to the lowest possible value.
  14305. // [year, month, day , hour, minute, second, millisecond]
  14306. function configFromArray (config) {
  14307. var i, date, input = [], currentDate, expectedWeekday, yearToUse;
  14308. if (config._d) {
  14309. return;
  14310. }
  14311. currentDate = currentDateArray(config);
  14312. //compute day of the year from weeks and weekdays
  14313. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  14314. dayOfYearFromWeekInfo(config);
  14315. }
  14316. //if the day of the year is set, figure out what it is
  14317. if (config._dayOfYear != null) {
  14318. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  14319. if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
  14320. getParsingFlags(config)._overflowDayOfYear = true;
  14321. }
  14322. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  14323. config._a[MONTH] = date.getUTCMonth();
  14324. config._a[DATE] = date.getUTCDate();
  14325. }
  14326. // Default to current date.
  14327. // * if no year, month, day of month are given, default to today
  14328. // * if day of month is given, default month and year
  14329. // * if month is given, default only year
  14330. // * if year is given, don't default anything
  14331. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  14332. config._a[i] = input[i] = currentDate[i];
  14333. }
  14334. // Zero out whatever was not defaulted, including time
  14335. for (; i < 7; i++) {
  14336. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  14337. }
  14338. // Check for 24:00:00.000
  14339. if (config._a[HOUR] === 24 &&
  14340. config._a[MINUTE] === 0 &&
  14341. config._a[SECOND] === 0 &&
  14342. config._a[MILLISECOND] === 0) {
  14343. config._nextDay = true;
  14344. config._a[HOUR] = 0;
  14345. }
  14346. config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
  14347. expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
  14348. // Apply timezone offset from input. The actual utcOffset can be changed
  14349. // with parseZone.
  14350. if (config._tzm != null) {
  14351. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  14352. }
  14353. if (config._nextDay) {
  14354. config._a[HOUR] = 24;
  14355. }
  14356. // check for mismatching day of week
  14357. if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
  14358. getParsingFlags(config).weekdayMismatch = true;
  14359. }
  14360. }
  14361. function dayOfYearFromWeekInfo(config) {
  14362. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
  14363. w = config._w;
  14364. if (w.GG != null || w.W != null || w.E != null) {
  14365. dow = 1;
  14366. doy = 4;
  14367. // TODO: We need to take the current isoWeekYear, but that depends on
  14368. // how we interpret now (local, utc, fixed offset). So create
  14369. // a now version of current config (take local/utc/offset flags, and
  14370. // create now).
  14371. weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
  14372. week = defaults(w.W, 1);
  14373. weekday = defaults(w.E, 1);
  14374. if (weekday < 1 || weekday > 7) {
  14375. weekdayOverflow = true;
  14376. }
  14377. } else {
  14378. dow = config._locale._week.dow;
  14379. doy = config._locale._week.doy;
  14380. var curWeek = weekOfYear(createLocal(), dow, doy);
  14381. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  14382. // Default to current week.
  14383. week = defaults(w.w, curWeek.week);
  14384. if (w.d != null) {
  14385. // weekday -- low day numbers are considered next week
  14386. weekday = w.d;
  14387. if (weekday < 0 || weekday > 6) {
  14388. weekdayOverflow = true;
  14389. }
  14390. } else if (w.e != null) {
  14391. // local weekday -- counting starts from beginning of week
  14392. weekday = w.e + dow;
  14393. if (w.e < 0 || w.e > 6) {
  14394. weekdayOverflow = true;
  14395. }
  14396. } else {
  14397. // default to beginning of week
  14398. weekday = dow;
  14399. }
  14400. }
  14401. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  14402. getParsingFlags(config)._overflowWeeks = true;
  14403. } else if (weekdayOverflow != null) {
  14404. getParsingFlags(config)._overflowWeekday = true;
  14405. } else {
  14406. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  14407. config._a[YEAR] = temp.year;
  14408. config._dayOfYear = temp.dayOfYear;
  14409. }
  14410. }
  14411. // iso 8601 regex
  14412. // 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)
  14413. 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)?)?$/;
  14414. 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)?)?$/;
  14415. var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
  14416. var isoDates = [
  14417. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  14418. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  14419. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  14420. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  14421. ['YYYY-DDD', /\d{4}-\d{3}/],
  14422. ['YYYY-MM', /\d{4}-\d\d/, false],
  14423. ['YYYYYYMMDD', /[+-]\d{10}/],
  14424. ['YYYYMMDD', /\d{8}/],
  14425. // YYYYMM is NOT allowed by the standard
  14426. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  14427. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  14428. ['YYYYDDD', /\d{7}/]
  14429. ];
  14430. // iso time formats and regexes
  14431. var isoTimes = [
  14432. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  14433. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  14434. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  14435. ['HH:mm', /\d\d:\d\d/],
  14436. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  14437. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  14438. ['HHmmss', /\d\d\d\d\d\d/],
  14439. ['HHmm', /\d\d\d\d/],
  14440. ['HH', /\d\d/]
  14441. ];
  14442. var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
  14443. // date from iso format
  14444. function configFromISO(config) {
  14445. var i, l,
  14446. string = config._i,
  14447. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  14448. allowTime, dateFormat, timeFormat, tzFormat;
  14449. if (match) {
  14450. getParsingFlags(config).iso = true;
  14451. for (i = 0, l = isoDates.length; i < l; i++) {
  14452. if (isoDates[i][1].exec(match[1])) {
  14453. dateFormat = isoDates[i][0];
  14454. allowTime = isoDates[i][2] !== false;
  14455. break;
  14456. }
  14457. }
  14458. if (dateFormat == null) {
  14459. config._isValid = false;
  14460. return;
  14461. }
  14462. if (match[3]) {
  14463. for (i = 0, l = isoTimes.length; i < l; i++) {
  14464. if (isoTimes[i][1].exec(match[3])) {
  14465. // match[2] should be 'T' or space
  14466. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  14467. break;
  14468. }
  14469. }
  14470. if (timeFormat == null) {
  14471. config._isValid = false;
  14472. return;
  14473. }
  14474. }
  14475. if (!allowTime && timeFormat != null) {
  14476. config._isValid = false;
  14477. return;
  14478. }
  14479. if (match[4]) {
  14480. if (tzRegex.exec(match[4])) {
  14481. tzFormat = 'Z';
  14482. } else {
  14483. config._isValid = false;
  14484. return;
  14485. }
  14486. }
  14487. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  14488. configFromStringAndFormat(config);
  14489. } else {
  14490. config._isValid = false;
  14491. }
  14492. }
  14493. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  14494. 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}))$/;
  14495. function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  14496. var result = [
  14497. untruncateYear(yearStr),
  14498. defaultLocaleMonthsShort.indexOf(monthStr),
  14499. parseInt(dayStr, 10),
  14500. parseInt(hourStr, 10),
  14501. parseInt(minuteStr, 10)
  14502. ];
  14503. if (secondStr) {
  14504. result.push(parseInt(secondStr, 10));
  14505. }
  14506. return result;
  14507. }
  14508. function untruncateYear(yearStr) {
  14509. var year = parseInt(yearStr, 10);
  14510. if (year <= 49) {
  14511. return 2000 + year;
  14512. } else if (year <= 999) {
  14513. return 1900 + year;
  14514. }
  14515. return year;
  14516. }
  14517. function preprocessRFC2822(s) {
  14518. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  14519. return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  14520. }
  14521. function checkWeekday(weekdayStr, parsedInput, config) {
  14522. if (weekdayStr) {
  14523. // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
  14524. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  14525. weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
  14526. if (weekdayProvided !== weekdayActual) {
  14527. getParsingFlags(config).weekdayMismatch = true;
  14528. config._isValid = false;
  14529. return false;
  14530. }
  14531. }
  14532. return true;
  14533. }
  14534. var obsOffsets = {
  14535. UT: 0,
  14536. GMT: 0,
  14537. EDT: -4 * 60,
  14538. EST: -5 * 60,
  14539. CDT: -5 * 60,
  14540. CST: -6 * 60,
  14541. MDT: -6 * 60,
  14542. MST: -7 * 60,
  14543. PDT: -7 * 60,
  14544. PST: -8 * 60
  14545. };
  14546. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  14547. if (obsOffset) {
  14548. return obsOffsets[obsOffset];
  14549. } else if (militaryOffset) {
  14550. // the only allowed military tz is Z
  14551. return 0;
  14552. } else {
  14553. var hm = parseInt(numOffset, 10);
  14554. var m = hm % 100, h = (hm - m) / 100;
  14555. return h * 60 + m;
  14556. }
  14557. }
  14558. // date and time from ref 2822 format
  14559. function configFromRFC2822(config) {
  14560. var match = rfc2822.exec(preprocessRFC2822(config._i));
  14561. if (match) {
  14562. var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
  14563. if (!checkWeekday(match[1], parsedArray, config)) {
  14564. return;
  14565. }
  14566. config._a = parsedArray;
  14567. config._tzm = calculateOffset(match[8], match[9], match[10]);
  14568. config._d = createUTCDate.apply(null, config._a);
  14569. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  14570. getParsingFlags(config).rfc2822 = true;
  14571. } else {
  14572. config._isValid = false;
  14573. }
  14574. }
  14575. // date from iso format or fallback
  14576. function configFromString(config) {
  14577. var matched = aspNetJsonRegex.exec(config._i);
  14578. if (matched !== null) {
  14579. config._d = new Date(+matched[1]);
  14580. return;
  14581. }
  14582. configFromISO(config);
  14583. if (config._isValid === false) {
  14584. delete config._isValid;
  14585. } else {
  14586. return;
  14587. }
  14588. configFromRFC2822(config);
  14589. if (config._isValid === false) {
  14590. delete config._isValid;
  14591. } else {
  14592. return;
  14593. }
  14594. // Final attempt, use Input Fallback
  14595. hooks.createFromInputFallback(config);
  14596. }
  14597. hooks.createFromInputFallback = deprecate(
  14598. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  14599. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  14600. 'discouraged and will be removed in an upcoming major release. Please refer to ' +
  14601. 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  14602. function (config) {
  14603. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  14604. }
  14605. );
  14606. // constant that refers to the ISO standard
  14607. hooks.ISO_8601 = function () {};
  14608. // constant that refers to the RFC 2822 form
  14609. hooks.RFC_2822 = function () {};
  14610. // date from string and format string
  14611. function configFromStringAndFormat(config) {
  14612. // TODO: Move this to another part of the creation flow to prevent circular deps
  14613. if (config._f === hooks.ISO_8601) {
  14614. configFromISO(config);
  14615. return;
  14616. }
  14617. if (config._f === hooks.RFC_2822) {
  14618. configFromRFC2822(config);
  14619. return;
  14620. }
  14621. config._a = [];
  14622. getParsingFlags(config).empty = true;
  14623. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  14624. var string = '' + config._i,
  14625. i, parsedInput, tokens, token, skipped,
  14626. stringLength = string.length,
  14627. totalParsedInputLength = 0;
  14628. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  14629. for (i = 0; i < tokens.length; i++) {
  14630. token = tokens[i];
  14631. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  14632. // console.log('token', token, 'parsedInput', parsedInput,
  14633. // 'regex', getParseRegexForToken(token, config));
  14634. if (parsedInput) {
  14635. skipped = string.substr(0, string.indexOf(parsedInput));
  14636. if (skipped.length > 0) {
  14637. getParsingFlags(config).unusedInput.push(skipped);
  14638. }
  14639. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  14640. totalParsedInputLength += parsedInput.length;
  14641. }
  14642. // don't parse if it's not a known token
  14643. if (formatTokenFunctions[token]) {
  14644. if (parsedInput) {
  14645. getParsingFlags(config).empty = false;
  14646. }
  14647. else {
  14648. getParsingFlags(config).unusedTokens.push(token);
  14649. }
  14650. addTimeToArrayFromToken(token, parsedInput, config);
  14651. }
  14652. else if (config._strict && !parsedInput) {
  14653. getParsingFlags(config).unusedTokens.push(token);
  14654. }
  14655. }
  14656. // add remaining unparsed input length to the string
  14657. getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
  14658. if (string.length > 0) {
  14659. getParsingFlags(config).unusedInput.push(string);
  14660. }
  14661. // clear _12h flag if hour is <= 12
  14662. if (config._a[HOUR] <= 12 &&
  14663. getParsingFlags(config).bigHour === true &&
  14664. config._a[HOUR] > 0) {
  14665. getParsingFlags(config).bigHour = undefined;
  14666. }
  14667. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  14668. getParsingFlags(config).meridiem = config._meridiem;
  14669. // handle meridiem
  14670. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
  14671. configFromArray(config);
  14672. checkOverflow(config);
  14673. }
  14674. function meridiemFixWrap (locale, hour, meridiem) {
  14675. var isPm;
  14676. if (meridiem == null) {
  14677. // nothing to do
  14678. return hour;
  14679. }
  14680. if (locale.meridiemHour != null) {
  14681. return locale.meridiemHour(hour, meridiem);
  14682. } else if (locale.isPM != null) {
  14683. // Fallback
  14684. isPm = locale.isPM(meridiem);
  14685. if (isPm && hour < 12) {
  14686. hour += 12;
  14687. }
  14688. if (!isPm && hour === 12) {
  14689. hour = 0;
  14690. }
  14691. return hour;
  14692. } else {
  14693. // this is not supposed to happen
  14694. return hour;
  14695. }
  14696. }
  14697. // date from string and array of format strings
  14698. function configFromStringAndArray(config) {
  14699. var tempConfig,
  14700. bestMoment,
  14701. scoreToBeat,
  14702. i,
  14703. currentScore;
  14704. if (config._f.length === 0) {
  14705. getParsingFlags(config).invalidFormat = true;
  14706. config._d = new Date(NaN);
  14707. return;
  14708. }
  14709. for (i = 0; i < config._f.length; i++) {
  14710. currentScore = 0;
  14711. tempConfig = copyConfig({}, config);
  14712. if (config._useUTC != null) {
  14713. tempConfig._useUTC = config._useUTC;
  14714. }
  14715. tempConfig._f = config._f[i];
  14716. configFromStringAndFormat(tempConfig);
  14717. if (!isValid(tempConfig)) {
  14718. continue;
  14719. }
  14720. // if there is any input that was not parsed add a penalty for that format
  14721. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  14722. //or tokens
  14723. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  14724. getParsingFlags(tempConfig).score = currentScore;
  14725. if (scoreToBeat == null || currentScore < scoreToBeat) {
  14726. scoreToBeat = currentScore;
  14727. bestMoment = tempConfig;
  14728. }
  14729. }
  14730. extend(config, bestMoment || tempConfig);
  14731. }
  14732. function configFromObject(config) {
  14733. if (config._d) {
  14734. return;
  14735. }
  14736. var i = normalizeObjectUnits(config._i);
  14737. config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
  14738. return obj && parseInt(obj, 10);
  14739. });
  14740. configFromArray(config);
  14741. }
  14742. function createFromConfig (config) {
  14743. var res = new Moment(checkOverflow(prepareConfig(config)));
  14744. if (res._nextDay) {
  14745. // Adding is smart enough around DST
  14746. res.add(1, 'd');
  14747. res._nextDay = undefined;
  14748. }
  14749. return res;
  14750. }
  14751. function prepareConfig (config) {
  14752. var input = config._i,
  14753. format = config._f;
  14754. config._locale = config._locale || getLocale(config._l);
  14755. if (input === null || (format === undefined && input === '')) {
  14756. return createInvalid({nullInput: true});
  14757. }
  14758. if (typeof input === 'string') {
  14759. config._i = input = config._locale.preparse(input);
  14760. }
  14761. if (isMoment(input)) {
  14762. return new Moment(checkOverflow(input));
  14763. } else if (isDate(input)) {
  14764. config._d = input;
  14765. } else if (isArray(format)) {
  14766. configFromStringAndArray(config);
  14767. } else if (format) {
  14768. configFromStringAndFormat(config);
  14769. } else {
  14770. configFromInput(config);
  14771. }
  14772. if (!isValid(config)) {
  14773. config._d = null;
  14774. }
  14775. return config;
  14776. }
  14777. function configFromInput(config) {
  14778. var input = config._i;
  14779. if (isUndefined(input)) {
  14780. config._d = new Date(hooks.now());
  14781. } else if (isDate(input)) {
  14782. config._d = new Date(input.valueOf());
  14783. } else if (typeof input === 'string') {
  14784. configFromString(config);
  14785. } else if (isArray(input)) {
  14786. config._a = map(input.slice(0), function (obj) {
  14787. return parseInt(obj, 10);
  14788. });
  14789. configFromArray(config);
  14790. } else if (isObject(input)) {
  14791. configFromObject(config);
  14792. } else if (isNumber(input)) {
  14793. // from milliseconds
  14794. config._d = new Date(input);
  14795. } else {
  14796. hooks.createFromInputFallback(config);
  14797. }
  14798. }
  14799. function createLocalOrUTC (input, format, locale, strict, isUTC) {
  14800. var c = {};
  14801. if (locale === true || locale === false) {
  14802. strict = locale;
  14803. locale = undefined;
  14804. }
  14805. if ((isObject(input) && isObjectEmpty(input)) ||
  14806. (isArray(input) && input.length === 0)) {
  14807. input = undefined;
  14808. }
  14809. // object construction must be done this way.
  14810. // https://github.com/moment/moment/issues/1423
  14811. c._isAMomentObject = true;
  14812. c._useUTC = c._isUTC = isUTC;
  14813. c._l = locale;
  14814. c._i = input;
  14815. c._f = format;
  14816. c._strict = strict;
  14817. return createFromConfig(c);
  14818. }
  14819. function createLocal (input, format, locale, strict) {
  14820. return createLocalOrUTC(input, format, locale, strict, false);
  14821. }
  14822. var prototypeMin = deprecate(
  14823. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  14824. function () {
  14825. var other = createLocal.apply(null, arguments);
  14826. if (this.isValid() && other.isValid()) {
  14827. return other < this ? this : other;
  14828. } else {
  14829. return createInvalid();
  14830. }
  14831. }
  14832. );
  14833. var prototypeMax = deprecate(
  14834. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  14835. function () {
  14836. var other = createLocal.apply(null, arguments);
  14837. if (this.isValid() && other.isValid()) {
  14838. return other > this ? this : other;
  14839. } else {
  14840. return createInvalid();
  14841. }
  14842. }
  14843. );
  14844. // Pick a moment m from moments so that m[fn](other) is true for all
  14845. // other. This relies on the function fn to be transitive.
  14846. //
  14847. // moments should either be an array of moment objects or an array, whose
  14848. // first element is an array of moment objects.
  14849. function pickBy(fn, moments) {
  14850. var res, i;
  14851. if (moments.length === 1 && isArray(moments[0])) {
  14852. moments = moments[0];
  14853. }
  14854. if (!moments.length) {
  14855. return createLocal();
  14856. }
  14857. res = moments[0];
  14858. for (i = 1; i < moments.length; ++i) {
  14859. if (!moments[i].isValid() || moments[i][fn](res)) {
  14860. res = moments[i];
  14861. }
  14862. }
  14863. return res;
  14864. }
  14865. // TODO: Use [].sort instead?
  14866. function min () {
  14867. var args = [].slice.call(arguments, 0);
  14868. return pickBy('isBefore', args);
  14869. }
  14870. function max () {
  14871. var args = [].slice.call(arguments, 0);
  14872. return pickBy('isAfter', args);
  14873. }
  14874. var now = function () {
  14875. return Date.now ? Date.now() : +(new Date());
  14876. };
  14877. var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
  14878. function isDurationValid(m) {
  14879. for (var key in m) {
  14880. if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
  14881. return false;
  14882. }
  14883. }
  14884. var unitHasDecimal = false;
  14885. for (var i = 0; i < ordering.length; ++i) {
  14886. if (m[ordering[i]]) {
  14887. if (unitHasDecimal) {
  14888. return false; // only allow non-integers for smallest unit
  14889. }
  14890. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  14891. unitHasDecimal = true;
  14892. }
  14893. }
  14894. }
  14895. return true;
  14896. }
  14897. function isValid$1() {
  14898. return this._isValid;
  14899. }
  14900. function createInvalid$1() {
  14901. return createDuration(NaN);
  14902. }
  14903. function Duration (duration) {
  14904. var normalizedInput = normalizeObjectUnits(duration),
  14905. years = normalizedInput.year || 0,
  14906. quarters = normalizedInput.quarter || 0,
  14907. months = normalizedInput.month || 0,
  14908. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  14909. days = normalizedInput.day || 0,
  14910. hours = normalizedInput.hour || 0,
  14911. minutes = normalizedInput.minute || 0,
  14912. seconds = normalizedInput.second || 0,
  14913. milliseconds = normalizedInput.millisecond || 0;
  14914. this._isValid = isDurationValid(normalizedInput);
  14915. // representation for dateAddRemove
  14916. this._milliseconds = +milliseconds +
  14917. seconds * 1e3 + // 1000
  14918. minutes * 6e4 + // 1000 * 60
  14919. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  14920. // Because of dateAddRemove treats 24 hours as different from a
  14921. // day when working around DST, we need to store them separately
  14922. this._days = +days +
  14923. weeks * 7;
  14924. // It is impossible to translate months into days without knowing
  14925. // which months you are are talking about, so we have to store
  14926. // it separately.
  14927. this._months = +months +
  14928. quarters * 3 +
  14929. years * 12;
  14930. this._data = {};
  14931. this._locale = getLocale();
  14932. this._bubble();
  14933. }
  14934. function isDuration (obj) {
  14935. return obj instanceof Duration;
  14936. }
  14937. function absRound (number) {
  14938. if (number < 0) {
  14939. return Math.round(-1 * number) * -1;
  14940. } else {
  14941. return Math.round(number);
  14942. }
  14943. }
  14944. // FORMATTING
  14945. function offset (token, separator) {
  14946. addFormatToken(token, 0, 0, function () {
  14947. var offset = this.utcOffset();
  14948. var sign = '+';
  14949. if (offset < 0) {
  14950. offset = -offset;
  14951. sign = '-';
  14952. }
  14953. return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
  14954. });
  14955. }
  14956. offset('Z', ':');
  14957. offset('ZZ', '');
  14958. // PARSING
  14959. addRegexToken('Z', matchShortOffset);
  14960. addRegexToken('ZZ', matchShortOffset);
  14961. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  14962. config._useUTC = true;
  14963. config._tzm = offsetFromString(matchShortOffset, input);
  14964. });
  14965. // HELPERS
  14966. // timezone chunker
  14967. // '+10:00' > ['10', '00']
  14968. // '-1530' > ['-15', '30']
  14969. var chunkOffset = /([\+\-]|\d\d)/gi;
  14970. function offsetFromString(matcher, string) {
  14971. var matches = (string || '').match(matcher);
  14972. if (matches === null) {
  14973. return null;
  14974. }
  14975. var chunk = matches[matches.length - 1] || [];
  14976. var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  14977. var minutes = +(parts[1] * 60) + toInt(parts[2]);
  14978. return minutes === 0 ?
  14979. 0 :
  14980. parts[0] === '+' ? minutes : -minutes;
  14981. }
  14982. // Return a moment from input, that is local/utc/zone equivalent to model.
  14983. function cloneWithOffset(input, model) {
  14984. var res, diff;
  14985. if (model._isUTC) {
  14986. res = model.clone();
  14987. diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
  14988. // Use low-level api, because this fn is low-level api.
  14989. res._d.setTime(res._d.valueOf() + diff);
  14990. hooks.updateOffset(res, false);
  14991. return res;
  14992. } else {
  14993. return createLocal(input).local();
  14994. }
  14995. }
  14996. function getDateOffset (m) {
  14997. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  14998. // https://github.com/moment/moment/pull/1871
  14999. return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
  15000. }
  15001. // HOOKS
  15002. // This function will be called whenever a moment is mutated.
  15003. // It is intended to keep the offset in sync with the timezone.
  15004. hooks.updateOffset = function () {};
  15005. // MOMENTS
  15006. // keepLocalTime = true means only change the timezone, without
  15007. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  15008. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  15009. // +0200, so we adjust the time as needed, to be valid.
  15010. //
  15011. // Keeping the time actually adds/subtracts (one hour)
  15012. // from the actual represented time. That is why we call updateOffset
  15013. // a second time. In case it wants us to change the offset again
  15014. // _changeInProgress == true case, then we have to adjust, because
  15015. // there is no such time in the given timezone.
  15016. function getSetOffset (input, keepLocalTime, keepMinutes) {
  15017. var offset = this._offset || 0,
  15018. localAdjust;
  15019. if (!this.isValid()) {
  15020. return input != null ? this : NaN;
  15021. }
  15022. if (input != null) {
  15023. if (typeof input === 'string') {
  15024. input = offsetFromString(matchShortOffset, input);
  15025. if (input === null) {
  15026. return this;
  15027. }
  15028. } else if (Math.abs(input) < 16 && !keepMinutes) {
  15029. input = input * 60;
  15030. }
  15031. if (!this._isUTC && keepLocalTime) {
  15032. localAdjust = getDateOffset(this);
  15033. }
  15034. this._offset = input;
  15035. this._isUTC = true;
  15036. if (localAdjust != null) {
  15037. this.add(localAdjust, 'm');
  15038. }
  15039. if (offset !== input) {
  15040. if (!keepLocalTime || this._changeInProgress) {
  15041. addSubtract(this, createDuration(input - offset, 'm'), 1, false);
  15042. } else if (!this._changeInProgress) {
  15043. this._changeInProgress = true;
  15044. hooks.updateOffset(this, true);
  15045. this._changeInProgress = null;
  15046. }
  15047. }
  15048. return this;
  15049. } else {
  15050. return this._isUTC ? offset : getDateOffset(this);
  15051. }
  15052. }
  15053. function getSetZone (input, keepLocalTime) {
  15054. if (input != null) {
  15055. if (typeof input !== 'string') {
  15056. input = -input;
  15057. }
  15058. this.utcOffset(input, keepLocalTime);
  15059. return this;
  15060. } else {
  15061. return -this.utcOffset();
  15062. }
  15063. }
  15064. function setOffsetToUTC (keepLocalTime) {
  15065. return this.utcOffset(0, keepLocalTime);
  15066. }
  15067. function setOffsetToLocal (keepLocalTime) {
  15068. if (this._isUTC) {
  15069. this.utcOffset(0, keepLocalTime);
  15070. this._isUTC = false;
  15071. if (keepLocalTime) {
  15072. this.subtract(getDateOffset(this), 'm');
  15073. }
  15074. }
  15075. return this;
  15076. }
  15077. function setOffsetToParsedOffset () {
  15078. if (this._tzm != null) {
  15079. this.utcOffset(this._tzm, false, true);
  15080. } else if (typeof this._i === 'string') {
  15081. var tZone = offsetFromString(matchOffset, this._i);
  15082. if (tZone != null) {
  15083. this.utcOffset(tZone);
  15084. }
  15085. else {
  15086. this.utcOffset(0, true);
  15087. }
  15088. }
  15089. return this;
  15090. }
  15091. function hasAlignedHourOffset (input) {
  15092. if (!this.isValid()) {
  15093. return false;
  15094. }
  15095. input = input ? createLocal(input).utcOffset() : 0;
  15096. return (this.utcOffset() - input) % 60 === 0;
  15097. }
  15098. function isDaylightSavingTime () {
  15099. return (
  15100. this.utcOffset() > this.clone().month(0).utcOffset() ||
  15101. this.utcOffset() > this.clone().month(5).utcOffset()
  15102. );
  15103. }
  15104. function isDaylightSavingTimeShifted () {
  15105. if (!isUndefined(this._isDSTShifted)) {
  15106. return this._isDSTShifted;
  15107. }
  15108. var c = {};
  15109. copyConfig(c, this);
  15110. c = prepareConfig(c);
  15111. if (c._a) {
  15112. var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  15113. this._isDSTShifted = this.isValid() &&
  15114. compareArrays(c._a, other.toArray()) > 0;
  15115. } else {
  15116. this._isDSTShifted = false;
  15117. }
  15118. return this._isDSTShifted;
  15119. }
  15120. function isLocal () {
  15121. return this.isValid() ? !this._isUTC : false;
  15122. }
  15123. function isUtcOffset () {
  15124. return this.isValid() ? this._isUTC : false;
  15125. }
  15126. function isUtc () {
  15127. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  15128. }
  15129. // ASP.NET json date format regex
  15130. var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
  15131. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  15132. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  15133. // and further modified to allow for strings containing both week and day
  15134. 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)?)?$/;
  15135. function createDuration (input, key) {
  15136. var duration = input,
  15137. // matching against regexp is expensive, do it on demand
  15138. match = null,
  15139. sign,
  15140. ret,
  15141. diffRes;
  15142. if (isDuration(input)) {
  15143. duration = {
  15144. ms : input._milliseconds,
  15145. d : input._days,
  15146. M : input._months
  15147. };
  15148. } else if (isNumber(input)) {
  15149. duration = {};
  15150. if (key) {
  15151. duration[key] = input;
  15152. } else {
  15153. duration.milliseconds = input;
  15154. }
  15155. } else if (!!(match = aspNetRegex.exec(input))) {
  15156. sign = (match[1] === '-') ? -1 : 1;
  15157. duration = {
  15158. y : 0,
  15159. d : toInt(match[DATE]) * sign,
  15160. h : toInt(match[HOUR]) * sign,
  15161. m : toInt(match[MINUTE]) * sign,
  15162. s : toInt(match[SECOND]) * sign,
  15163. ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
  15164. };
  15165. } else if (!!(match = isoRegex.exec(input))) {
  15166. sign = (match[1] === '-') ? -1 : 1;
  15167. duration = {
  15168. y : parseIso(match[2], sign),
  15169. M : parseIso(match[3], sign),
  15170. w : parseIso(match[4], sign),
  15171. d : parseIso(match[5], sign),
  15172. h : parseIso(match[6], sign),
  15173. m : parseIso(match[7], sign),
  15174. s : parseIso(match[8], sign)
  15175. };
  15176. } else if (duration == null) {// checks for null or undefined
  15177. duration = {};
  15178. } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
  15179. diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
  15180. duration = {};
  15181. duration.ms = diffRes.milliseconds;
  15182. duration.M = diffRes.months;
  15183. }
  15184. ret = new Duration(duration);
  15185. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  15186. ret._locale = input._locale;
  15187. }
  15188. return ret;
  15189. }
  15190. createDuration.fn = Duration.prototype;
  15191. createDuration.invalid = createInvalid$1;
  15192. function parseIso (inp, sign) {
  15193. // We'd normally use ~~inp for this, but unfortunately it also
  15194. // converts floats to ints.
  15195. // inp may be undefined, so careful calling replace on it.
  15196. var res = inp && parseFloat(inp.replace(',', '.'));
  15197. // apply sign while we're at it
  15198. return (isNaN(res) ? 0 : res) * sign;
  15199. }
  15200. function positiveMomentsDifference(base, other) {
  15201. var res = {};
  15202. res.months = other.month() - base.month() +
  15203. (other.year() - base.year()) * 12;
  15204. if (base.clone().add(res.months, 'M').isAfter(other)) {
  15205. --res.months;
  15206. }
  15207. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  15208. return res;
  15209. }
  15210. function momentsDifference(base, other) {
  15211. var res;
  15212. if (!(base.isValid() && other.isValid())) {
  15213. return {milliseconds: 0, months: 0};
  15214. }
  15215. other = cloneWithOffset(other, base);
  15216. if (base.isBefore(other)) {
  15217. res = positiveMomentsDifference(base, other);
  15218. } else {
  15219. res = positiveMomentsDifference(other, base);
  15220. res.milliseconds = -res.milliseconds;
  15221. res.months = -res.months;
  15222. }
  15223. return res;
  15224. }
  15225. // TODO: remove 'name' arg after deprecation is removed
  15226. function createAdder(direction, name) {
  15227. return function (val, period) {
  15228. var dur, tmp;
  15229. //invert the arguments, but complain about it
  15230. if (period !== null && !isNaN(+period)) {
  15231. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
  15232. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
  15233. tmp = val; val = period; period = tmp;
  15234. }
  15235. val = typeof val === 'string' ? +val : val;
  15236. dur = createDuration(val, period);
  15237. addSubtract(this, dur, direction);
  15238. return this;
  15239. };
  15240. }
  15241. function addSubtract (mom, duration, isAdding, updateOffset) {
  15242. var milliseconds = duration._milliseconds,
  15243. days = absRound(duration._days),
  15244. months = absRound(duration._months);
  15245. if (!mom.isValid()) {
  15246. // No op
  15247. return;
  15248. }
  15249. updateOffset = updateOffset == null ? true : updateOffset;
  15250. if (months) {
  15251. setMonth(mom, get(mom, 'Month') + months * isAdding);
  15252. }
  15253. if (days) {
  15254. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  15255. }
  15256. if (milliseconds) {
  15257. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  15258. }
  15259. if (updateOffset) {
  15260. hooks.updateOffset(mom, days || months);
  15261. }
  15262. }
  15263. var add = createAdder(1, 'add');
  15264. var subtract = createAdder(-1, 'subtract');
  15265. function getCalendarFormat(myMoment, now) {
  15266. var diff = myMoment.diff(now, 'days', true);
  15267. return diff < -6 ? 'sameElse' :
  15268. diff < -1 ? 'lastWeek' :
  15269. diff < 0 ? 'lastDay' :
  15270. diff < 1 ? 'sameDay' :
  15271. diff < 2 ? 'nextDay' :
  15272. diff < 7 ? 'nextWeek' : 'sameElse';
  15273. }
  15274. function calendar$1 (time, formats) {
  15275. // We want to compare the start of today, vs this.
  15276. // Getting start-of-today depends on whether we're local/utc/offset or not.
  15277. var now = time || createLocal(),
  15278. sod = cloneWithOffset(now, this).startOf('day'),
  15279. format = hooks.calendarFormat(this, sod) || 'sameElse';
  15280. var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
  15281. return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
  15282. }
  15283. function clone () {
  15284. return new Moment(this);
  15285. }
  15286. function isAfter (input, units) {
  15287. var localInput = isMoment(input) ? input : createLocal(input);
  15288. if (!(this.isValid() && localInput.isValid())) {
  15289. return false;
  15290. }
  15291. units = normalizeUnits(units) || 'millisecond';
  15292. if (units === 'millisecond') {
  15293. return this.valueOf() > localInput.valueOf();
  15294. } else {
  15295. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  15296. }
  15297. }
  15298. function isBefore (input, units) {
  15299. var localInput = isMoment(input) ? input : createLocal(input);
  15300. if (!(this.isValid() && localInput.isValid())) {
  15301. return false;
  15302. }
  15303. units = normalizeUnits(units) || 'millisecond';
  15304. if (units === 'millisecond') {
  15305. return this.valueOf() < localInput.valueOf();
  15306. } else {
  15307. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  15308. }
  15309. }
  15310. function isBetween (from, to, units, inclusivity) {
  15311. var localFrom = isMoment(from) ? from : createLocal(from),
  15312. localTo = isMoment(to) ? to : createLocal(to);
  15313. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  15314. return false;
  15315. }
  15316. inclusivity = inclusivity || '()';
  15317. return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) &&
  15318. (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
  15319. }
  15320. function isSame (input, units) {
  15321. var localInput = isMoment(input) ? input : createLocal(input),
  15322. inputMs;
  15323. if (!(this.isValid() && localInput.isValid())) {
  15324. return false;
  15325. }
  15326. units = normalizeUnits(units) || 'millisecond';
  15327. if (units === 'millisecond') {
  15328. return this.valueOf() === localInput.valueOf();
  15329. } else {
  15330. inputMs = localInput.valueOf();
  15331. return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
  15332. }
  15333. }
  15334. function isSameOrAfter (input, units) {
  15335. return this.isSame(input, units) || this.isAfter(input, units);
  15336. }
  15337. function isSameOrBefore (input, units) {
  15338. return this.isSame(input, units) || this.isBefore(input, units);
  15339. }
  15340. function diff (input, units, asFloat) {
  15341. var that,
  15342. zoneDelta,
  15343. output;
  15344. if (!this.isValid()) {
  15345. return NaN;
  15346. }
  15347. that = cloneWithOffset(input, this);
  15348. if (!that.isValid()) {
  15349. return NaN;
  15350. }
  15351. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  15352. units = normalizeUnits(units);
  15353. switch (units) {
  15354. case 'year': output = monthDiff(this, that) / 12; break;
  15355. case 'month': output = monthDiff(this, that); break;
  15356. case 'quarter': output = monthDiff(this, that) / 3; break;
  15357. case 'second': output = (this - that) / 1e3; break; // 1000
  15358. case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
  15359. case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
  15360. case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
  15361. case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
  15362. default: output = this - that;
  15363. }
  15364. return asFloat ? output : absFloor(output);
  15365. }
  15366. function monthDiff (a, b) {
  15367. // difference in months
  15368. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  15369. // b is in (anchor - 1 month, anchor + 1 month)
  15370. anchor = a.clone().add(wholeMonthDiff, 'months'),
  15371. anchor2, adjust;
  15372. if (b - anchor < 0) {
  15373. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  15374. // linear across the month
  15375. adjust = (b - anchor) / (anchor - anchor2);
  15376. } else {
  15377. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  15378. // linear across the month
  15379. adjust = (b - anchor) / (anchor2 - anchor);
  15380. }
  15381. //check for negative zero, return zero if negative zero
  15382. return -(wholeMonthDiff + adjust) || 0;
  15383. }
  15384. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  15385. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  15386. function toString () {
  15387. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  15388. }
  15389. function toISOString(keepOffset) {
  15390. if (!this.isValid()) {
  15391. return null;
  15392. }
  15393. var utc = keepOffset !== true;
  15394. var m = utc ? this.clone().utc() : this;
  15395. if (m.year() < 0 || m.year() > 9999) {
  15396. return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
  15397. }
  15398. if (isFunction(Date.prototype.toISOString)) {
  15399. // native implementation is ~50x faster, use it when we can
  15400. if (utc) {
  15401. return this.toDate().toISOString();
  15402. } else {
  15403. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
  15404. }
  15405. }
  15406. return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
  15407. }
  15408. /**
  15409. * Return a human readable representation of a moment that can
  15410. * also be evaluated to get a new moment which is the same
  15411. *
  15412. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  15413. */
  15414. function inspect () {
  15415. if (!this.isValid()) {
  15416. return 'moment.invalid(/* ' + this._i + ' */)';
  15417. }
  15418. var func = 'moment';
  15419. var zone = '';
  15420. if (!this.isLocal()) {
  15421. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  15422. zone = 'Z';
  15423. }
  15424. var prefix = '[' + func + '("]';
  15425. var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
  15426. var datetime = '-MM-DD[T]HH:mm:ss.SSS';
  15427. var suffix = zone + '[")]';
  15428. return this.format(prefix + year + datetime + suffix);
  15429. }
  15430. function format (inputString) {
  15431. if (!inputString) {
  15432. inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
  15433. }
  15434. var output = formatMoment(this, inputString);
  15435. return this.localeData().postformat(output);
  15436. }
  15437. function from (time, withoutSuffix) {
  15438. if (this.isValid() &&
  15439. ((isMoment(time) && time.isValid()) ||
  15440. createLocal(time).isValid())) {
  15441. return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  15442. } else {
  15443. return this.localeData().invalidDate();
  15444. }
  15445. }
  15446. function fromNow (withoutSuffix) {
  15447. return this.from(createLocal(), withoutSuffix);
  15448. }
  15449. function to (time, withoutSuffix) {
  15450. if (this.isValid() &&
  15451. ((isMoment(time) && time.isValid()) ||
  15452. createLocal(time).isValid())) {
  15453. return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
  15454. } else {
  15455. return this.localeData().invalidDate();
  15456. }
  15457. }
  15458. function toNow (withoutSuffix) {
  15459. return this.to(createLocal(), withoutSuffix);
  15460. }
  15461. // If passed a locale key, it will set the locale for this
  15462. // instance. Otherwise, it will return the locale configuration
  15463. // variables for this instance.
  15464. function locale (key) {
  15465. var newLocaleData;
  15466. if (key === undefined) {
  15467. return this._locale._abbr;
  15468. } else {
  15469. newLocaleData = getLocale(key);
  15470. if (newLocaleData != null) {
  15471. this._locale = newLocaleData;
  15472. }
  15473. return this;
  15474. }
  15475. }
  15476. var lang = deprecate(
  15477. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  15478. function (key) {
  15479. if (key === undefined) {
  15480. return this.localeData();
  15481. } else {
  15482. return this.locale(key);
  15483. }
  15484. }
  15485. );
  15486. function localeData () {
  15487. return this._locale;
  15488. }
  15489. var MS_PER_SECOND = 1000;
  15490. var MS_PER_MINUTE = 60 * MS_PER_SECOND;
  15491. var MS_PER_HOUR = 60 * MS_PER_MINUTE;
  15492. var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  15493. // actual modulo - handles negative numbers (for dates before 1970):
  15494. function mod$1(dividend, divisor) {
  15495. return (dividend % divisor + divisor) % divisor;
  15496. }
  15497. function localStartOfDate(y, m, d) {
  15498. // the date constructor remaps years 0-99 to 1900-1999
  15499. if (y < 100 && y >= 0) {
  15500. // preserve leap years using a full 400 year cycle, then reset
  15501. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  15502. } else {
  15503. return new Date(y, m, d).valueOf();
  15504. }
  15505. }
  15506. function utcStartOfDate(y, m, d) {
  15507. // Date.UTC remaps years 0-99 to 1900-1999
  15508. if (y < 100 && y >= 0) {
  15509. // preserve leap years using a full 400 year cycle, then reset
  15510. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  15511. } else {
  15512. return Date.UTC(y, m, d);
  15513. }
  15514. }
  15515. function startOf (units) {
  15516. var time;
  15517. units = normalizeUnits(units);
  15518. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  15519. return this;
  15520. }
  15521. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  15522. switch (units) {
  15523. case 'year':
  15524. time = startOfDate(this.year(), 0, 1);
  15525. break;
  15526. case 'quarter':
  15527. time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
  15528. break;
  15529. case 'month':
  15530. time = startOfDate(this.year(), this.month(), 1);
  15531. break;
  15532. case 'week':
  15533. time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
  15534. break;
  15535. case 'isoWeek':
  15536. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
  15537. break;
  15538. case 'day':
  15539. case 'date':
  15540. time = startOfDate(this.year(), this.month(), this.date());
  15541. break;
  15542. case 'hour':
  15543. time = this._d.valueOf();
  15544. time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
  15545. break;
  15546. case 'minute':
  15547. time = this._d.valueOf();
  15548. time -= mod$1(time, MS_PER_MINUTE);
  15549. break;
  15550. case 'second':
  15551. time = this._d.valueOf();
  15552. time -= mod$1(time, MS_PER_SECOND);
  15553. break;
  15554. }
  15555. this._d.setTime(time);
  15556. hooks.updateOffset(this, true);
  15557. return this;
  15558. }
  15559. function endOf (units) {
  15560. var time;
  15561. units = normalizeUnits(units);
  15562. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  15563. return this;
  15564. }
  15565. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  15566. switch (units) {
  15567. case 'year':
  15568. time = startOfDate(this.year() + 1, 0, 1) - 1;
  15569. break;
  15570. case 'quarter':
  15571. time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
  15572. break;
  15573. case 'month':
  15574. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  15575. break;
  15576. case 'week':
  15577. time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
  15578. break;
  15579. case 'isoWeek':
  15580. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
  15581. break;
  15582. case 'day':
  15583. case 'date':
  15584. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  15585. break;
  15586. case 'hour':
  15587. time = this._d.valueOf();
  15588. time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
  15589. break;
  15590. case 'minute':
  15591. time = this._d.valueOf();
  15592. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  15593. break;
  15594. case 'second':
  15595. time = this._d.valueOf();
  15596. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  15597. break;
  15598. }
  15599. this._d.setTime(time);
  15600. hooks.updateOffset(this, true);
  15601. return this;
  15602. }
  15603. function valueOf () {
  15604. return this._d.valueOf() - ((this._offset || 0) * 60000);
  15605. }
  15606. function unix () {
  15607. return Math.floor(this.valueOf() / 1000);
  15608. }
  15609. function toDate () {
  15610. return new Date(this.valueOf());
  15611. }
  15612. function toArray () {
  15613. var m = this;
  15614. return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
  15615. }
  15616. function toObject () {
  15617. var m = this;
  15618. return {
  15619. years: m.year(),
  15620. months: m.month(),
  15621. date: m.date(),
  15622. hours: m.hours(),
  15623. minutes: m.minutes(),
  15624. seconds: m.seconds(),
  15625. milliseconds: m.milliseconds()
  15626. };
  15627. }
  15628. function toJSON () {
  15629. // new Date(NaN).toJSON() === null
  15630. return this.isValid() ? this.toISOString() : null;
  15631. }
  15632. function isValid$2 () {
  15633. return isValid(this);
  15634. }
  15635. function parsingFlags () {
  15636. return extend({}, getParsingFlags(this));
  15637. }
  15638. function invalidAt () {
  15639. return getParsingFlags(this).overflow;
  15640. }
  15641. function creationData() {
  15642. return {
  15643. input: this._i,
  15644. format: this._f,
  15645. locale: this._locale,
  15646. isUTC: this._isUTC,
  15647. strict: this._strict
  15648. };
  15649. }
  15650. // FORMATTING
  15651. addFormatToken(0, ['gg', 2], 0, function () {
  15652. return this.weekYear() % 100;
  15653. });
  15654. addFormatToken(0, ['GG', 2], 0, function () {
  15655. return this.isoWeekYear() % 100;
  15656. });
  15657. function addWeekYearFormatToken (token, getter) {
  15658. addFormatToken(0, [token, token.length], 0, getter);
  15659. }
  15660. addWeekYearFormatToken('gggg', 'weekYear');
  15661. addWeekYearFormatToken('ggggg', 'weekYear');
  15662. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  15663. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  15664. // ALIASES
  15665. addUnitAlias('weekYear', 'gg');
  15666. addUnitAlias('isoWeekYear', 'GG');
  15667. // PRIORITY
  15668. addUnitPriority('weekYear', 1);
  15669. addUnitPriority('isoWeekYear', 1);
  15670. // PARSING
  15671. addRegexToken('G', matchSigned);
  15672. addRegexToken('g', matchSigned);
  15673. addRegexToken('GG', match1to2, match2);
  15674. addRegexToken('gg', match1to2, match2);
  15675. addRegexToken('GGGG', match1to4, match4);
  15676. addRegexToken('gggg', match1to4, match4);
  15677. addRegexToken('GGGGG', match1to6, match6);
  15678. addRegexToken('ggggg', match1to6, match6);
  15679. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
  15680. week[token.substr(0, 2)] = toInt(input);
  15681. });
  15682. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  15683. week[token] = hooks.parseTwoDigitYear(input);
  15684. });
  15685. // MOMENTS
  15686. function getSetWeekYear (input) {
  15687. return getSetWeekYearHelper.call(this,
  15688. input,
  15689. this.week(),
  15690. this.weekday(),
  15691. this.localeData()._week.dow,
  15692. this.localeData()._week.doy);
  15693. }
  15694. function getSetISOWeekYear (input) {
  15695. return getSetWeekYearHelper.call(this,
  15696. input, this.isoWeek(), this.isoWeekday(), 1, 4);
  15697. }
  15698. function getISOWeeksInYear () {
  15699. return weeksInYear(this.year(), 1, 4);
  15700. }
  15701. function getWeeksInYear () {
  15702. var weekInfo = this.localeData()._week;
  15703. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  15704. }
  15705. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  15706. var weeksTarget;
  15707. if (input == null) {
  15708. return weekOfYear(this, dow, doy).year;
  15709. } else {
  15710. weeksTarget = weeksInYear(input, dow, doy);
  15711. if (week > weeksTarget) {
  15712. week = weeksTarget;
  15713. }
  15714. return setWeekAll.call(this, input, week, weekday, dow, doy);
  15715. }
  15716. }
  15717. function setWeekAll(weekYear, week, weekday, dow, doy) {
  15718. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  15719. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  15720. this.year(date.getUTCFullYear());
  15721. this.month(date.getUTCMonth());
  15722. this.date(date.getUTCDate());
  15723. return this;
  15724. }
  15725. // FORMATTING
  15726. addFormatToken('Q', 0, 'Qo', 'quarter');
  15727. // ALIASES
  15728. addUnitAlias('quarter', 'Q');
  15729. // PRIORITY
  15730. addUnitPriority('quarter', 7);
  15731. // PARSING
  15732. addRegexToken('Q', match1);
  15733. addParseToken('Q', function (input, array) {
  15734. array[MONTH] = (toInt(input) - 1) * 3;
  15735. });
  15736. // MOMENTS
  15737. function getSetQuarter (input) {
  15738. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  15739. }
  15740. // FORMATTING
  15741. addFormatToken('D', ['DD', 2], 'Do', 'date');
  15742. // ALIASES
  15743. addUnitAlias('date', 'D');
  15744. // PRIORITY
  15745. addUnitPriority('date', 9);
  15746. // PARSING
  15747. addRegexToken('D', match1to2);
  15748. addRegexToken('DD', match1to2, match2);
  15749. addRegexToken('Do', function (isStrict, locale) {
  15750. // TODO: Remove "ordinalParse" fallback in next major release.
  15751. return isStrict ?
  15752. (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
  15753. locale._dayOfMonthOrdinalParseLenient;
  15754. });
  15755. addParseToken(['D', 'DD'], DATE);
  15756. addParseToken('Do', function (input, array) {
  15757. array[DATE] = toInt(input.match(match1to2)[0]);
  15758. });
  15759. // MOMENTS
  15760. var getSetDayOfMonth = makeGetSet('Date', true);
  15761. // FORMATTING
  15762. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  15763. // ALIASES
  15764. addUnitAlias('dayOfYear', 'DDD');
  15765. // PRIORITY
  15766. addUnitPriority('dayOfYear', 4);
  15767. // PARSING
  15768. addRegexToken('DDD', match1to3);
  15769. addRegexToken('DDDD', match3);
  15770. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  15771. config._dayOfYear = toInt(input);
  15772. });
  15773. // HELPERS
  15774. // MOMENTS
  15775. function getSetDayOfYear (input) {
  15776. var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
  15777. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  15778. }
  15779. // FORMATTING
  15780. addFormatToken('m', ['mm', 2], 0, 'minute');
  15781. // ALIASES
  15782. addUnitAlias('minute', 'm');
  15783. // PRIORITY
  15784. addUnitPriority('minute', 14);
  15785. // PARSING
  15786. addRegexToken('m', match1to2);
  15787. addRegexToken('mm', match1to2, match2);
  15788. addParseToken(['m', 'mm'], MINUTE);
  15789. // MOMENTS
  15790. var getSetMinute = makeGetSet('Minutes', false);
  15791. // FORMATTING
  15792. addFormatToken('s', ['ss', 2], 0, 'second');
  15793. // ALIASES
  15794. addUnitAlias('second', 's');
  15795. // PRIORITY
  15796. addUnitPriority('second', 15);
  15797. // PARSING
  15798. addRegexToken('s', match1to2);
  15799. addRegexToken('ss', match1to2, match2);
  15800. addParseToken(['s', 'ss'], SECOND);
  15801. // MOMENTS
  15802. var getSetSecond = makeGetSet('Seconds', false);
  15803. // FORMATTING
  15804. addFormatToken('S', 0, 0, function () {
  15805. return ~~(this.millisecond() / 100);
  15806. });
  15807. addFormatToken(0, ['SS', 2], 0, function () {
  15808. return ~~(this.millisecond() / 10);
  15809. });
  15810. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  15811. addFormatToken(0, ['SSSS', 4], 0, function () {
  15812. return this.millisecond() * 10;
  15813. });
  15814. addFormatToken(0, ['SSSSS', 5], 0, function () {
  15815. return this.millisecond() * 100;
  15816. });
  15817. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  15818. return this.millisecond() * 1000;
  15819. });
  15820. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  15821. return this.millisecond() * 10000;
  15822. });
  15823. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  15824. return this.millisecond() * 100000;
  15825. });
  15826. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  15827. return this.millisecond() * 1000000;
  15828. });
  15829. // ALIASES
  15830. addUnitAlias('millisecond', 'ms');
  15831. // PRIORITY
  15832. addUnitPriority('millisecond', 16);
  15833. // PARSING
  15834. addRegexToken('S', match1to3, match1);
  15835. addRegexToken('SS', match1to3, match2);
  15836. addRegexToken('SSS', match1to3, match3);
  15837. var token;
  15838. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  15839. addRegexToken(token, matchUnsigned);
  15840. }
  15841. function parseMs(input, array) {
  15842. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  15843. }
  15844. for (token = 'S'; token.length <= 9; token += 'S') {
  15845. addParseToken(token, parseMs);
  15846. }
  15847. // MOMENTS
  15848. var getSetMillisecond = makeGetSet('Milliseconds', false);
  15849. // FORMATTING
  15850. addFormatToken('z', 0, 0, 'zoneAbbr');
  15851. addFormatToken('zz', 0, 0, 'zoneName');
  15852. // MOMENTS
  15853. function getZoneAbbr () {
  15854. return this._isUTC ? 'UTC' : '';
  15855. }
  15856. function getZoneName () {
  15857. return this._isUTC ? 'Coordinated Universal Time' : '';
  15858. }
  15859. var proto = Moment.prototype;
  15860. proto.add = add;
  15861. proto.calendar = calendar$1;
  15862. proto.clone = clone;
  15863. proto.diff = diff;
  15864. proto.endOf = endOf;
  15865. proto.format = format;
  15866. proto.from = from;
  15867. proto.fromNow = fromNow;
  15868. proto.to = to;
  15869. proto.toNow = toNow;
  15870. proto.get = stringGet;
  15871. proto.invalidAt = invalidAt;
  15872. proto.isAfter = isAfter;
  15873. proto.isBefore = isBefore;
  15874. proto.isBetween = isBetween;
  15875. proto.isSame = isSame;
  15876. proto.isSameOrAfter = isSameOrAfter;
  15877. proto.isSameOrBefore = isSameOrBefore;
  15878. proto.isValid = isValid$2;
  15879. proto.lang = lang;
  15880. proto.locale = locale;
  15881. proto.localeData = localeData;
  15882. proto.max = prototypeMax;
  15883. proto.min = prototypeMin;
  15884. proto.parsingFlags = parsingFlags;
  15885. proto.set = stringSet;
  15886. proto.startOf = startOf;
  15887. proto.subtract = subtract;
  15888. proto.toArray = toArray;
  15889. proto.toObject = toObject;
  15890. proto.toDate = toDate;
  15891. proto.toISOString = toISOString;
  15892. proto.inspect = inspect;
  15893. proto.toJSON = toJSON;
  15894. proto.toString = toString;
  15895. proto.unix = unix;
  15896. proto.valueOf = valueOf;
  15897. proto.creationData = creationData;
  15898. proto.year = getSetYear;
  15899. proto.isLeapYear = getIsLeapYear;
  15900. proto.weekYear = getSetWeekYear;
  15901. proto.isoWeekYear = getSetISOWeekYear;
  15902. proto.quarter = proto.quarters = getSetQuarter;
  15903. proto.month = getSetMonth;
  15904. proto.daysInMonth = getDaysInMonth;
  15905. proto.week = proto.weeks = getSetWeek;
  15906. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  15907. proto.weeksInYear = getWeeksInYear;
  15908. proto.isoWeeksInYear = getISOWeeksInYear;
  15909. proto.date = getSetDayOfMonth;
  15910. proto.day = proto.days = getSetDayOfWeek;
  15911. proto.weekday = getSetLocaleDayOfWeek;
  15912. proto.isoWeekday = getSetISODayOfWeek;
  15913. proto.dayOfYear = getSetDayOfYear;
  15914. proto.hour = proto.hours = getSetHour;
  15915. proto.minute = proto.minutes = getSetMinute;
  15916. proto.second = proto.seconds = getSetSecond;
  15917. proto.millisecond = proto.milliseconds = getSetMillisecond;
  15918. proto.utcOffset = getSetOffset;
  15919. proto.utc = setOffsetToUTC;
  15920. proto.local = setOffsetToLocal;
  15921. proto.parseZone = setOffsetToParsedOffset;
  15922. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  15923. proto.isDST = isDaylightSavingTime;
  15924. proto.isLocal = isLocal;
  15925. proto.isUtcOffset = isUtcOffset;
  15926. proto.isUtc = isUtc;
  15927. proto.isUTC = isUtc;
  15928. proto.zoneAbbr = getZoneAbbr;
  15929. proto.zoneName = getZoneName;
  15930. proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
  15931. proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
  15932. proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
  15933. proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
  15934. proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
  15935. function createUnix (input) {
  15936. return createLocal(input * 1000);
  15937. }
  15938. function createInZone () {
  15939. return createLocal.apply(null, arguments).parseZone();
  15940. }
  15941. function preParsePostFormat (string) {
  15942. return string;
  15943. }
  15944. var proto$1 = Locale.prototype;
  15945. proto$1.calendar = calendar;
  15946. proto$1.longDateFormat = longDateFormat;
  15947. proto$1.invalidDate = invalidDate;
  15948. proto$1.ordinal = ordinal;
  15949. proto$1.preparse = preParsePostFormat;
  15950. proto$1.postformat = preParsePostFormat;
  15951. proto$1.relativeTime = relativeTime;
  15952. proto$1.pastFuture = pastFuture;
  15953. proto$1.set = set;
  15954. proto$1.months = localeMonths;
  15955. proto$1.monthsShort = localeMonthsShort;
  15956. proto$1.monthsParse = localeMonthsParse;
  15957. proto$1.monthsRegex = monthsRegex;
  15958. proto$1.monthsShortRegex = monthsShortRegex;
  15959. proto$1.week = localeWeek;
  15960. proto$1.firstDayOfYear = localeFirstDayOfYear;
  15961. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  15962. proto$1.weekdays = localeWeekdays;
  15963. proto$1.weekdaysMin = localeWeekdaysMin;
  15964. proto$1.weekdaysShort = localeWeekdaysShort;
  15965. proto$1.weekdaysParse = localeWeekdaysParse;
  15966. proto$1.weekdaysRegex = weekdaysRegex;
  15967. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  15968. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  15969. proto$1.isPM = localeIsPM;
  15970. proto$1.meridiem = localeMeridiem;
  15971. function get$1 (format, index, field, setter) {
  15972. var locale = getLocale();
  15973. var utc = createUTC().set(setter, index);
  15974. return locale[field](utc, format);
  15975. }
  15976. function listMonthsImpl (format, index, field) {
  15977. if (isNumber(format)) {
  15978. index = format;
  15979. format = undefined;
  15980. }
  15981. format = format || '';
  15982. if (index != null) {
  15983. return get$1(format, index, field, 'month');
  15984. }
  15985. var i;
  15986. var out = [];
  15987. for (i = 0; i < 12; i++) {
  15988. out[i] = get$1(format, i, field, 'month');
  15989. }
  15990. return out;
  15991. }
  15992. // ()
  15993. // (5)
  15994. // (fmt, 5)
  15995. // (fmt)
  15996. // (true)
  15997. // (true, 5)
  15998. // (true, fmt, 5)
  15999. // (true, fmt)
  16000. function listWeekdaysImpl (localeSorted, format, index, field) {
  16001. if (typeof localeSorted === 'boolean') {
  16002. if (isNumber(format)) {
  16003. index = format;
  16004. format = undefined;
  16005. }
  16006. format = format || '';
  16007. } else {
  16008. format = localeSorted;
  16009. index = format;
  16010. localeSorted = false;
  16011. if (isNumber(format)) {
  16012. index = format;
  16013. format = undefined;
  16014. }
  16015. format = format || '';
  16016. }
  16017. var locale = getLocale(),
  16018. shift = localeSorted ? locale._week.dow : 0;
  16019. if (index != null) {
  16020. return get$1(format, (index + shift) % 7, field, 'day');
  16021. }
  16022. var i;
  16023. var out = [];
  16024. for (i = 0; i < 7; i++) {
  16025. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  16026. }
  16027. return out;
  16028. }
  16029. function listMonths (format, index) {
  16030. return listMonthsImpl(format, index, 'months');
  16031. }
  16032. function listMonthsShort (format, index) {
  16033. return listMonthsImpl(format, index, 'monthsShort');
  16034. }
  16035. function listWeekdays (localeSorted, format, index) {
  16036. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  16037. }
  16038. function listWeekdaysShort (localeSorted, format, index) {
  16039. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  16040. }
  16041. function listWeekdaysMin (localeSorted, format, index) {
  16042. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  16043. }
  16044. getSetGlobalLocale('en', {
  16045. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  16046. ordinal : function (number) {
  16047. var b = number % 10,
  16048. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  16049. (b === 1) ? 'st' :
  16050. (b === 2) ? 'nd' :
  16051. (b === 3) ? 'rd' : 'th';
  16052. return number + output;
  16053. }
  16054. });
  16055. // Side effect imports
  16056. hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
  16057. hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
  16058. var mathAbs = Math.abs;
  16059. function abs () {
  16060. var data = this._data;
  16061. this._milliseconds = mathAbs(this._milliseconds);
  16062. this._days = mathAbs(this._days);
  16063. this._months = mathAbs(this._months);
  16064. data.milliseconds = mathAbs(data.milliseconds);
  16065. data.seconds = mathAbs(data.seconds);
  16066. data.minutes = mathAbs(data.minutes);
  16067. data.hours = mathAbs(data.hours);
  16068. data.months = mathAbs(data.months);
  16069. data.years = mathAbs(data.years);
  16070. return this;
  16071. }
  16072. function addSubtract$1 (duration, input, value, direction) {
  16073. var other = createDuration(input, value);
  16074. duration._milliseconds += direction * other._milliseconds;
  16075. duration._days += direction * other._days;
  16076. duration._months += direction * other._months;
  16077. return duration._bubble();
  16078. }
  16079. // supports only 2.0-style add(1, 's') or add(duration)
  16080. function add$1 (input, value) {
  16081. return addSubtract$1(this, input, value, 1);
  16082. }
  16083. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  16084. function subtract$1 (input, value) {
  16085. return addSubtract$1(this, input, value, -1);
  16086. }
  16087. function absCeil (number) {
  16088. if (number < 0) {
  16089. return Math.floor(number);
  16090. } else {
  16091. return Math.ceil(number);
  16092. }
  16093. }
  16094. function bubble () {
  16095. var milliseconds = this._milliseconds;
  16096. var days = this._days;
  16097. var months = this._months;
  16098. var data = this._data;
  16099. var seconds, minutes, hours, years, monthsFromDays;
  16100. // if we have a mix of positive and negative values, bubble down first
  16101. // check: https://github.com/moment/moment/issues/2166
  16102. if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
  16103. (milliseconds <= 0 && days <= 0 && months <= 0))) {
  16104. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  16105. days = 0;
  16106. months = 0;
  16107. }
  16108. // The following code bubbles up values, see the tests for
  16109. // examples of what that means.
  16110. data.milliseconds = milliseconds % 1000;
  16111. seconds = absFloor(milliseconds / 1000);
  16112. data.seconds = seconds % 60;
  16113. minutes = absFloor(seconds / 60);
  16114. data.minutes = minutes % 60;
  16115. hours = absFloor(minutes / 60);
  16116. data.hours = hours % 24;
  16117. days += absFloor(hours / 24);
  16118. // convert days to months
  16119. monthsFromDays = absFloor(daysToMonths(days));
  16120. months += monthsFromDays;
  16121. days -= absCeil(monthsToDays(monthsFromDays));
  16122. // 12 months -> 1 year
  16123. years = absFloor(months / 12);
  16124. months %= 12;
  16125. data.days = days;
  16126. data.months = months;
  16127. data.years = years;
  16128. return this;
  16129. }
  16130. function daysToMonths (days) {
  16131. // 400 years have 146097 days (taking into account leap year rules)
  16132. // 400 years have 12 months === 4800
  16133. return days * 4800 / 146097;
  16134. }
  16135. function monthsToDays (months) {
  16136. // the reverse of daysToMonths
  16137. return months * 146097 / 4800;
  16138. }
  16139. function as (units) {
  16140. if (!this.isValid()) {
  16141. return NaN;
  16142. }
  16143. var days;
  16144. var months;
  16145. var milliseconds = this._milliseconds;
  16146. units = normalizeUnits(units);
  16147. if (units === 'month' || units === 'quarter' || units === 'year') {
  16148. days = this._days + milliseconds / 864e5;
  16149. months = this._months + daysToMonths(days);
  16150. switch (units) {
  16151. case 'month': return months;
  16152. case 'quarter': return months / 3;
  16153. case 'year': return months / 12;
  16154. }
  16155. } else {
  16156. // handle milliseconds separately because of floating point math errors (issue #1867)
  16157. days = this._days + Math.round(monthsToDays(this._months));
  16158. switch (units) {
  16159. case 'week' : return days / 7 + milliseconds / 6048e5;
  16160. case 'day' : return days + milliseconds / 864e5;
  16161. case 'hour' : return days * 24 + milliseconds / 36e5;
  16162. case 'minute' : return days * 1440 + milliseconds / 6e4;
  16163. case 'second' : return days * 86400 + milliseconds / 1000;
  16164. // Math.floor prevents floating point math errors here
  16165. case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
  16166. default: throw new Error('Unknown unit ' + units);
  16167. }
  16168. }
  16169. }
  16170. // TODO: Use this.as('ms')?
  16171. function valueOf$1 () {
  16172. if (!this.isValid()) {
  16173. return NaN;
  16174. }
  16175. return (
  16176. this._milliseconds +
  16177. this._days * 864e5 +
  16178. (this._months % 12) * 2592e6 +
  16179. toInt(this._months / 12) * 31536e6
  16180. );
  16181. }
  16182. function makeAs (alias) {
  16183. return function () {
  16184. return this.as(alias);
  16185. };
  16186. }
  16187. var asMilliseconds = makeAs('ms');
  16188. var asSeconds = makeAs('s');
  16189. var asMinutes = makeAs('m');
  16190. var asHours = makeAs('h');
  16191. var asDays = makeAs('d');
  16192. var asWeeks = makeAs('w');
  16193. var asMonths = makeAs('M');
  16194. var asQuarters = makeAs('Q');
  16195. var asYears = makeAs('y');
  16196. function clone$1 () {
  16197. return createDuration(this);
  16198. }
  16199. function get$2 (units) {
  16200. units = normalizeUnits(units);
  16201. return this.isValid() ? this[units + 's']() : NaN;
  16202. }
  16203. function makeGetter(name) {
  16204. return function () {
  16205. return this.isValid() ? this._data[name] : NaN;
  16206. };
  16207. }
  16208. var milliseconds = makeGetter('milliseconds');
  16209. var seconds = makeGetter('seconds');
  16210. var minutes = makeGetter('minutes');
  16211. var hours = makeGetter('hours');
  16212. var days = makeGetter('days');
  16213. var months = makeGetter('months');
  16214. var years = makeGetter('years');
  16215. function weeks () {
  16216. return absFloor(this.days() / 7);
  16217. }
  16218. var round = Math.round;
  16219. var thresholds = {
  16220. ss: 44, // a few seconds to seconds
  16221. s : 45, // seconds to minute
  16222. m : 45, // minutes to hour
  16223. h : 22, // hours to day
  16224. d : 26, // days to month
  16225. M : 11 // months to year
  16226. };
  16227. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  16228. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  16229. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  16230. }
  16231. function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
  16232. var duration = createDuration(posNegDuration).abs();
  16233. var seconds = round(duration.as('s'));
  16234. var minutes = round(duration.as('m'));
  16235. var hours = round(duration.as('h'));
  16236. var days = round(duration.as('d'));
  16237. var months = round(duration.as('M'));
  16238. var years = round(duration.as('y'));
  16239. var a = seconds <= thresholds.ss && ['s', seconds] ||
  16240. seconds < thresholds.s && ['ss', seconds] ||
  16241. minutes <= 1 && ['m'] ||
  16242. minutes < thresholds.m && ['mm', minutes] ||
  16243. hours <= 1 && ['h'] ||
  16244. hours < thresholds.h && ['hh', hours] ||
  16245. days <= 1 && ['d'] ||
  16246. days < thresholds.d && ['dd', days] ||
  16247. months <= 1 && ['M'] ||
  16248. months < thresholds.M && ['MM', months] ||
  16249. years <= 1 && ['y'] || ['yy', years];
  16250. a[2] = withoutSuffix;
  16251. a[3] = +posNegDuration > 0;
  16252. a[4] = locale;
  16253. return substituteTimeAgo.apply(null, a);
  16254. }
  16255. // This function allows you to set the rounding function for relative time strings
  16256. function getSetRelativeTimeRounding (roundingFunction) {
  16257. if (roundingFunction === undefined) {
  16258. return round;
  16259. }
  16260. if (typeof(roundingFunction) === 'function') {
  16261. round = roundingFunction;
  16262. return true;
  16263. }
  16264. return false;
  16265. }
  16266. // This function allows you to set a threshold for relative time strings
  16267. function getSetRelativeTimeThreshold (threshold, limit) {
  16268. if (thresholds[threshold] === undefined) {
  16269. return false;
  16270. }
  16271. if (limit === undefined) {
  16272. return thresholds[threshold];
  16273. }
  16274. thresholds[threshold] = limit;
  16275. if (threshold === 's') {
  16276. thresholds.ss = limit - 1;
  16277. }
  16278. return true;
  16279. }
  16280. function humanize (withSuffix) {
  16281. if (!this.isValid()) {
  16282. return this.localeData().invalidDate();
  16283. }
  16284. var locale = this.localeData();
  16285. var output = relativeTime$1(this, !withSuffix, locale);
  16286. if (withSuffix) {
  16287. output = locale.pastFuture(+this, output);
  16288. }
  16289. return locale.postformat(output);
  16290. }
  16291. var abs$1 = Math.abs;
  16292. function sign(x) {
  16293. return ((x > 0) - (x < 0)) || +x;
  16294. }
  16295. function toISOString$1() {
  16296. // for ISO strings we do not use the normal bubbling rules:
  16297. // * milliseconds bubble up until they become hours
  16298. // * days do not bubble at all
  16299. // * months bubble up until they become years
  16300. // This is because there is no context-free conversion between hours and days
  16301. // (think of clock changes)
  16302. // and also not between days and months (28-31 days per month)
  16303. if (!this.isValid()) {
  16304. return this.localeData().invalidDate();
  16305. }
  16306. var seconds = abs$1(this._milliseconds) / 1000;
  16307. var days = abs$1(this._days);
  16308. var months = abs$1(this._months);
  16309. var minutes, hours, years;
  16310. // 3600 seconds -> 60 minutes -> 1 hour
  16311. minutes = absFloor(seconds / 60);
  16312. hours = absFloor(minutes / 60);
  16313. seconds %= 60;
  16314. minutes %= 60;
  16315. // 12 months -> 1 year
  16316. years = absFloor(months / 12);
  16317. months %= 12;
  16318. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  16319. var Y = years;
  16320. var M = months;
  16321. var D = days;
  16322. var h = hours;
  16323. var m = minutes;
  16324. var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  16325. var total = this.asSeconds();
  16326. if (!total) {
  16327. // this is the same as C#'s (Noda) and python (isodate)...
  16328. // but not other JS (goog.date)
  16329. return 'P0D';
  16330. }
  16331. var totalSign = total < 0 ? '-' : '';
  16332. var ymSign = sign(this._months) !== sign(total) ? '-' : '';
  16333. var daysSign = sign(this._days) !== sign(total) ? '-' : '';
  16334. var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  16335. return totalSign + 'P' +
  16336. (Y ? ymSign + Y + 'Y' : '') +
  16337. (M ? ymSign + M + 'M' : '') +
  16338. (D ? daysSign + D + 'D' : '') +
  16339. ((h || m || s) ? 'T' : '') +
  16340. (h ? hmsSign + h + 'H' : '') +
  16341. (m ? hmsSign + m + 'M' : '') +
  16342. (s ? hmsSign + s + 'S' : '');
  16343. }
  16344. var proto$2 = Duration.prototype;
  16345. proto$2.isValid = isValid$1;
  16346. proto$2.abs = abs;
  16347. proto$2.add = add$1;
  16348. proto$2.subtract = subtract$1;
  16349. proto$2.as = as;
  16350. proto$2.asMilliseconds = asMilliseconds;
  16351. proto$2.asSeconds = asSeconds;
  16352. proto$2.asMinutes = asMinutes;
  16353. proto$2.asHours = asHours;
  16354. proto$2.asDays = asDays;
  16355. proto$2.asWeeks = asWeeks;
  16356. proto$2.asMonths = asMonths;
  16357. proto$2.asQuarters = asQuarters;
  16358. proto$2.asYears = asYears;
  16359. proto$2.valueOf = valueOf$1;
  16360. proto$2._bubble = bubble;
  16361. proto$2.clone = clone$1;
  16362. proto$2.get = get$2;
  16363. proto$2.milliseconds = milliseconds;
  16364. proto$2.seconds = seconds;
  16365. proto$2.minutes = minutes;
  16366. proto$2.hours = hours;
  16367. proto$2.days = days;
  16368. proto$2.weeks = weeks;
  16369. proto$2.months = months;
  16370. proto$2.years = years;
  16371. proto$2.humanize = humanize;
  16372. proto$2.toISOString = toISOString$1;
  16373. proto$2.toString = toISOString$1;
  16374. proto$2.toJSON = toISOString$1;
  16375. proto$2.locale = locale;
  16376. proto$2.localeData = localeData;
  16377. proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
  16378. proto$2.lang = lang;
  16379. // Side effect imports
  16380. // FORMATTING
  16381. addFormatToken('X', 0, 0, 'unix');
  16382. addFormatToken('x', 0, 0, 'valueOf');
  16383. // PARSING
  16384. addRegexToken('x', matchSigned);
  16385. addRegexToken('X', matchTimestamp);
  16386. addParseToken('X', function (input, array, config) {
  16387. config._d = new Date(parseFloat(input, 10) * 1000);
  16388. });
  16389. addParseToken('x', function (input, array, config) {
  16390. config._d = new Date(toInt(input));
  16391. });
  16392. // Side effect imports
  16393. hooks.version = '2.24.0';
  16394. setHookCallback(createLocal);
  16395. hooks.fn = proto;
  16396. hooks.min = min;
  16397. hooks.max = max;
  16398. hooks.now = now;
  16399. hooks.utc = createUTC;
  16400. hooks.unix = createUnix;
  16401. hooks.months = listMonths;
  16402. hooks.isDate = isDate;
  16403. hooks.locale = getSetGlobalLocale;
  16404. hooks.invalid = createInvalid;
  16405. hooks.duration = createDuration;
  16406. hooks.isMoment = isMoment;
  16407. hooks.weekdays = listWeekdays;
  16408. hooks.parseZone = createInZone;
  16409. hooks.localeData = getLocale;
  16410. hooks.isDuration = isDuration;
  16411. hooks.monthsShort = listMonthsShort;
  16412. hooks.weekdaysMin = listWeekdaysMin;
  16413. hooks.defineLocale = defineLocale;
  16414. hooks.updateLocale = updateLocale;
  16415. hooks.locales = listLocales;
  16416. hooks.weekdaysShort = listWeekdaysShort;
  16417. hooks.normalizeUnits = normalizeUnits;
  16418. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  16419. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  16420. hooks.calendarFormat = getCalendarFormat;
  16421. hooks.prototype = proto;
  16422. // currently HTML5 input type only supports 24-hour formats
  16423. hooks.HTML5_FMT = {
  16424. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  16425. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  16426. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  16427. DATE: 'YYYY-MM-DD', // <input type="date" />
  16428. TIME: 'HH:mm', // <input type="time" />
  16429. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  16430. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  16431. WEEK: 'GGGG-[W]WW', // <input type="week" />
  16432. MONTH: 'YYYY-MM' // <input type="month" />
  16433. };
  16434. return hooks;
  16435. })));
  16436. });
  16437. var FORMATS = {
  16438. datetime: 'MMM D, YYYY, h:mm:ss a',
  16439. millisecond: 'h:mm:ss.SSS a',
  16440. second: 'h:mm:ss a',
  16441. minute: 'h:mm a',
  16442. hour: 'hA',
  16443. day: 'MMM D',
  16444. week: 'll',
  16445. month: 'MMM YYYY',
  16446. quarter: '[Q]Q - YYYY',
  16447. year: 'YYYY'
  16448. };
  16449. core_adapters._date.override(typeof moment === 'function' ? {
  16450. _id: 'moment', // DEBUG ONLY
  16451. formats: function() {
  16452. return FORMATS;
  16453. },
  16454. parse: function(value, format) {
  16455. if (typeof value === 'string' && typeof format === 'string') {
  16456. value = moment(value, format);
  16457. } else if (!(value instanceof moment)) {
  16458. value = moment(value);
  16459. }
  16460. return value.isValid() ? value.valueOf() : null;
  16461. },
  16462. format: function(time, format) {
  16463. return moment(time).format(format);
  16464. },
  16465. add: function(time, amount, unit) {
  16466. return moment(time).add(amount, unit).valueOf();
  16467. },
  16468. diff: function(max, min, unit) {
  16469. return moment(max).diff(moment(min), unit);
  16470. },
  16471. startOf: function(time, unit, weekday) {
  16472. time = moment(time);
  16473. if (unit === 'isoWeek') {
  16474. return time.isoWeekday(weekday).valueOf();
  16475. }
  16476. return time.startOf(unit).valueOf();
  16477. },
  16478. endOf: function(time, unit) {
  16479. return moment(time).endOf(unit).valueOf();
  16480. },
  16481. // DEPRECATIONS
  16482. /**
  16483. * Provided for backward compatibility with scale.getValueForPixel().
  16484. * @deprecated since version 2.8.0
  16485. * @todo remove at version 3
  16486. * @private
  16487. */
  16488. _create: function(time) {
  16489. return moment(time);
  16490. },
  16491. } : {});
  16492. core_defaults._set('global', {
  16493. plugins: {
  16494. filler: {
  16495. propagate: true
  16496. }
  16497. }
  16498. });
  16499. var mappers = {
  16500. dataset: function(source) {
  16501. var index = source.fill;
  16502. var chart = source.chart;
  16503. var meta = chart.getDatasetMeta(index);
  16504. var visible = meta && chart.isDatasetVisible(index);
  16505. var points = (visible && meta.dataset._children) || [];
  16506. var length = points.length || 0;
  16507. return !length ? null : function(point, i) {
  16508. return (i < length && points[i]._view) || null;
  16509. };
  16510. },
  16511. boundary: function(source) {
  16512. var boundary = source.boundary;
  16513. var x = boundary ? boundary.x : null;
  16514. var y = boundary ? boundary.y : null;
  16515. if (helpers$1.isArray(boundary)) {
  16516. return function(point, i) {
  16517. return boundary[i];
  16518. };
  16519. }
  16520. return function(point) {
  16521. return {
  16522. x: x === null ? point.x : x,
  16523. y: y === null ? point.y : y,
  16524. };
  16525. };
  16526. }
  16527. };
  16528. // @todo if (fill[0] === '#')
  16529. function decodeFill(el, index, count) {
  16530. var model = el._model || {};
  16531. var fill = model.fill;
  16532. var target;
  16533. if (fill === undefined) {
  16534. fill = !!model.backgroundColor;
  16535. }
  16536. if (fill === false || fill === null) {
  16537. return false;
  16538. }
  16539. if (fill === true) {
  16540. return 'origin';
  16541. }
  16542. target = parseFloat(fill, 10);
  16543. if (isFinite(target) && Math.floor(target) === target) {
  16544. if (fill[0] === '-' || fill[0] === '+') {
  16545. target = index + target;
  16546. }
  16547. if (target === index || target < 0 || target >= count) {
  16548. return false;
  16549. }
  16550. return target;
  16551. }
  16552. switch (fill) {
  16553. // compatibility
  16554. case 'bottom':
  16555. return 'start';
  16556. case 'top':
  16557. return 'end';
  16558. case 'zero':
  16559. return 'origin';
  16560. // supported boundaries
  16561. case 'origin':
  16562. case 'start':
  16563. case 'end':
  16564. return fill;
  16565. // invalid fill values
  16566. default:
  16567. return false;
  16568. }
  16569. }
  16570. function computeLinearBoundary(source) {
  16571. var model = source.el._model || {};
  16572. var scale = source.el._scale || {};
  16573. var fill = source.fill;
  16574. var target = null;
  16575. var horizontal;
  16576. if (isFinite(fill)) {
  16577. return null;
  16578. }
  16579. // Backward compatibility: until v3, we still need to support boundary values set on
  16580. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  16581. // controllers might still use it (e.g. the Smith chart).
  16582. if (fill === 'start') {
  16583. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  16584. } else if (fill === 'end') {
  16585. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  16586. } else if (model.scaleZero !== undefined) {
  16587. target = model.scaleZero;
  16588. } else if (scale.getBasePixel) {
  16589. target = scale.getBasePixel();
  16590. }
  16591. if (target !== undefined && target !== null) {
  16592. if (target.x !== undefined && target.y !== undefined) {
  16593. return target;
  16594. }
  16595. if (helpers$1.isFinite(target)) {
  16596. horizontal = scale.isHorizontal();
  16597. return {
  16598. x: horizontal ? target : null,
  16599. y: horizontal ? null : target
  16600. };
  16601. }
  16602. }
  16603. return null;
  16604. }
  16605. function computeCircularBoundary(source) {
  16606. var scale = source.el._scale;
  16607. var options = scale.options;
  16608. var length = scale.chart.data.labels.length;
  16609. var fill = source.fill;
  16610. var target = [];
  16611. var start, end, center, i, point;
  16612. if (!length) {
  16613. return null;
  16614. }
  16615. start = options.ticks.reverse ? scale.max : scale.min;
  16616. end = options.ticks.reverse ? scale.min : scale.max;
  16617. center = scale.getPointPositionForValue(0, start);
  16618. for (i = 0; i < length; ++i) {
  16619. point = fill === 'start' || fill === 'end'
  16620. ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)
  16621. : scale.getBasePosition(i);
  16622. if (options.gridLines.circular) {
  16623. point.cx = center.x;
  16624. point.cy = center.y;
  16625. point.angle = scale.getIndexAngle(i) - Math.PI / 2;
  16626. }
  16627. target.push(point);
  16628. }
  16629. return target;
  16630. }
  16631. function computeBoundary(source) {
  16632. var scale = source.el._scale || {};
  16633. if (scale.getPointPositionForValue) {
  16634. return computeCircularBoundary(source);
  16635. }
  16636. return computeLinearBoundary(source);
  16637. }
  16638. function resolveTarget(sources, index, propagate) {
  16639. var source = sources[index];
  16640. var fill = source.fill;
  16641. var visited = [index];
  16642. var target;
  16643. if (!propagate) {
  16644. return fill;
  16645. }
  16646. while (fill !== false && visited.indexOf(fill) === -1) {
  16647. if (!isFinite(fill)) {
  16648. return fill;
  16649. }
  16650. target = sources[fill];
  16651. if (!target) {
  16652. return false;
  16653. }
  16654. if (target.visible) {
  16655. return fill;
  16656. }
  16657. visited.push(fill);
  16658. fill = target.fill;
  16659. }
  16660. return false;
  16661. }
  16662. function createMapper(source) {
  16663. var fill = source.fill;
  16664. var type = 'dataset';
  16665. if (fill === false) {
  16666. return null;
  16667. }
  16668. if (!isFinite(fill)) {
  16669. type = 'boundary';
  16670. }
  16671. return mappers[type](source);
  16672. }
  16673. function isDrawable(point) {
  16674. return point && !point.skip;
  16675. }
  16676. function drawArea(ctx, curve0, curve1, len0, len1) {
  16677. var i, cx, cy, r;
  16678. if (!len0 || !len1) {
  16679. return;
  16680. }
  16681. // building first area curve (normal)
  16682. ctx.moveTo(curve0[0].x, curve0[0].y);
  16683. for (i = 1; i < len0; ++i) {
  16684. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  16685. }
  16686. if (curve1[0].angle !== undefined) {
  16687. cx = curve1[0].cx;
  16688. cy = curve1[0].cy;
  16689. r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));
  16690. for (i = len1 - 1; i > 0; --i) {
  16691. ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);
  16692. }
  16693. return;
  16694. }
  16695. // joining the two area curves
  16696. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  16697. // building opposite area curve (reverse)
  16698. for (i = len1 - 1; i > 0; --i) {
  16699. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  16700. }
  16701. }
  16702. function doFill(ctx, points, mapper, view, color, loop) {
  16703. var count = points.length;
  16704. var span = view.spanGaps;
  16705. var curve0 = [];
  16706. var curve1 = [];
  16707. var len0 = 0;
  16708. var len1 = 0;
  16709. var i, ilen, index, p0, p1, d0, d1, loopOffset;
  16710. ctx.beginPath();
  16711. for (i = 0, ilen = count; i < ilen; ++i) {
  16712. index = i % count;
  16713. p0 = points[index]._view;
  16714. p1 = mapper(p0, index, view);
  16715. d0 = isDrawable(p0);
  16716. d1 = isDrawable(p1);
  16717. if (loop && loopOffset === undefined && d0) {
  16718. loopOffset = i + 1;
  16719. ilen = count + loopOffset;
  16720. }
  16721. if (d0 && d1) {
  16722. len0 = curve0.push(p0);
  16723. len1 = curve1.push(p1);
  16724. } else if (len0 && len1) {
  16725. if (!span) {
  16726. drawArea(ctx, curve0, curve1, len0, len1);
  16727. len0 = len1 = 0;
  16728. curve0 = [];
  16729. curve1 = [];
  16730. } else {
  16731. if (d0) {
  16732. curve0.push(p0);
  16733. }
  16734. if (d1) {
  16735. curve1.push(p1);
  16736. }
  16737. }
  16738. }
  16739. }
  16740. drawArea(ctx, curve0, curve1, len0, len1);
  16741. ctx.closePath();
  16742. ctx.fillStyle = color;
  16743. ctx.fill();
  16744. }
  16745. var plugin_filler = {
  16746. id: 'filler',
  16747. afterDatasetsUpdate: function(chart, options) {
  16748. var count = (chart.data.datasets || []).length;
  16749. var propagate = options.propagate;
  16750. var sources = [];
  16751. var meta, i, el, source;
  16752. for (i = 0; i < count; ++i) {
  16753. meta = chart.getDatasetMeta(i);
  16754. el = meta.dataset;
  16755. source = null;
  16756. if (el && el._model && el instanceof elements.Line) {
  16757. source = {
  16758. visible: chart.isDatasetVisible(i),
  16759. fill: decodeFill(el, i, count),
  16760. chart: chart,
  16761. el: el
  16762. };
  16763. }
  16764. meta.$filler = source;
  16765. sources.push(source);
  16766. }
  16767. for (i = 0; i < count; ++i) {
  16768. source = sources[i];
  16769. if (!source) {
  16770. continue;
  16771. }
  16772. source.fill = resolveTarget(sources, i, propagate);
  16773. source.boundary = computeBoundary(source);
  16774. source.mapper = createMapper(source);
  16775. }
  16776. },
  16777. beforeDatasetsDraw: function(chart) {
  16778. var metasets = chart._getSortedVisibleDatasetMetas();
  16779. var ctx = chart.ctx;
  16780. var meta, i, el, view, points, mapper, color;
  16781. for (i = metasets.length - 1; i >= 0; --i) {
  16782. meta = metasets[i].$filler;
  16783. if (!meta || !meta.visible) {
  16784. continue;
  16785. }
  16786. el = meta.el;
  16787. view = el._view;
  16788. points = el._children || [];
  16789. mapper = meta.mapper;
  16790. color = view.backgroundColor || core_defaults.global.defaultColor;
  16791. if (mapper && color && points.length) {
  16792. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  16793. doFill(ctx, points, mapper, view, color, el._loop);
  16794. helpers$1.canvas.unclipArea(ctx);
  16795. }
  16796. }
  16797. }
  16798. };
  16799. var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;
  16800. var noop$1 = helpers$1.noop;
  16801. var valueOrDefault$e = helpers$1.valueOrDefault;
  16802. core_defaults._set('global', {
  16803. legend: {
  16804. display: true,
  16805. position: 'top',
  16806. align: 'center',
  16807. fullWidth: true,
  16808. reverse: false,
  16809. weight: 1000,
  16810. // a callback that will handle
  16811. onClick: function(e, legendItem) {
  16812. var index = legendItem.datasetIndex;
  16813. var ci = this.chart;
  16814. var meta = ci.getDatasetMeta(index);
  16815. // See controller.isDatasetVisible comment
  16816. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  16817. // We hid a dataset ... rerender the chart
  16818. ci.update();
  16819. },
  16820. onHover: null,
  16821. onLeave: null,
  16822. labels: {
  16823. boxWidth: 40,
  16824. padding: 10,
  16825. // Generates labels shown in the legend
  16826. // Valid properties to return:
  16827. // text : text to display
  16828. // fillStyle : fill of coloured box
  16829. // strokeStyle: stroke of coloured box
  16830. // hidden : if this legend item refers to a hidden item
  16831. // lineCap : cap style for line
  16832. // lineDash
  16833. // lineDashOffset :
  16834. // lineJoin :
  16835. // lineWidth :
  16836. generateLabels: function(chart) {
  16837. var datasets = chart.data.datasets;
  16838. var options = chart.options.legend || {};
  16839. var usePointStyle = options.labels && options.labels.usePointStyle;
  16840. return chart._getSortedDatasetMetas().map(function(meta) {
  16841. var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  16842. return {
  16843. text: datasets[meta.index].label,
  16844. fillStyle: style.backgroundColor,
  16845. hidden: !chart.isDatasetVisible(meta.index),
  16846. lineCap: style.borderCapStyle,
  16847. lineDash: style.borderDash,
  16848. lineDashOffset: style.borderDashOffset,
  16849. lineJoin: style.borderJoinStyle,
  16850. lineWidth: style.borderWidth,
  16851. strokeStyle: style.borderColor,
  16852. pointStyle: style.pointStyle,
  16853. rotation: style.rotation,
  16854. // Below is extra data used for toggling the datasets
  16855. datasetIndex: meta.index
  16856. };
  16857. }, this);
  16858. }
  16859. }
  16860. },
  16861. legendCallback: function(chart) {
  16862. var list = document.createElement('ul');
  16863. var datasets = chart.data.datasets;
  16864. var i, ilen, listItem, listItemSpan;
  16865. list.setAttribute('class', chart.id + '-legend');
  16866. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  16867. listItem = list.appendChild(document.createElement('li'));
  16868. listItemSpan = listItem.appendChild(document.createElement('span'));
  16869. listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
  16870. if (datasets[i].label) {
  16871. listItem.appendChild(document.createTextNode(datasets[i].label));
  16872. }
  16873. }
  16874. return list.outerHTML;
  16875. }
  16876. });
  16877. /**
  16878. * Helper function to get the box width based on the usePointStyle option
  16879. * @param {object} labelopts - the label options on the legend
  16880. * @param {number} fontSize - the label font size
  16881. * @return {number} width of the color box area
  16882. */
  16883. function getBoxWidth(labelOpts, fontSize) {
  16884. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  16885. fontSize :
  16886. labelOpts.boxWidth;
  16887. }
  16888. /**
  16889. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  16890. */
  16891. var Legend = core_element.extend({
  16892. initialize: function(config) {
  16893. var me = this;
  16894. helpers$1.extend(me, config);
  16895. // Contains hit boxes for each dataset (in dataset order)
  16896. me.legendHitBoxes = [];
  16897. /**
  16898. * @private
  16899. */
  16900. me._hoveredItem = null;
  16901. // Are we in doughnut mode which has a different data type
  16902. me.doughnutMode = false;
  16903. },
  16904. // These methods are ordered by lifecycle. Utilities then follow.
  16905. // Any function defined here is inherited by all legend types.
  16906. // Any function can be extended by the legend type
  16907. beforeUpdate: noop$1,
  16908. update: function(maxWidth, maxHeight, margins) {
  16909. var me = this;
  16910. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  16911. me.beforeUpdate();
  16912. // Absorb the master measurements
  16913. me.maxWidth = maxWidth;
  16914. me.maxHeight = maxHeight;
  16915. me.margins = margins;
  16916. // Dimensions
  16917. me.beforeSetDimensions();
  16918. me.setDimensions();
  16919. me.afterSetDimensions();
  16920. // Labels
  16921. me.beforeBuildLabels();
  16922. me.buildLabels();
  16923. me.afterBuildLabels();
  16924. // Fit
  16925. me.beforeFit();
  16926. me.fit();
  16927. me.afterFit();
  16928. //
  16929. me.afterUpdate();
  16930. return me.minSize;
  16931. },
  16932. afterUpdate: noop$1,
  16933. //
  16934. beforeSetDimensions: noop$1,
  16935. setDimensions: function() {
  16936. var me = this;
  16937. // Set the unconstrained dimension before label rotation
  16938. if (me.isHorizontal()) {
  16939. // Reset position before calculating rotation
  16940. me.width = me.maxWidth;
  16941. me.left = 0;
  16942. me.right = me.width;
  16943. } else {
  16944. me.height = me.maxHeight;
  16945. // Reset position before calculating rotation
  16946. me.top = 0;
  16947. me.bottom = me.height;
  16948. }
  16949. // Reset padding
  16950. me.paddingLeft = 0;
  16951. me.paddingTop = 0;
  16952. me.paddingRight = 0;
  16953. me.paddingBottom = 0;
  16954. // Reset minSize
  16955. me.minSize = {
  16956. width: 0,
  16957. height: 0
  16958. };
  16959. },
  16960. afterSetDimensions: noop$1,
  16961. //
  16962. beforeBuildLabels: noop$1,
  16963. buildLabels: function() {
  16964. var me = this;
  16965. var labelOpts = me.options.labels || {};
  16966. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  16967. if (labelOpts.filter) {
  16968. legendItems = legendItems.filter(function(item) {
  16969. return labelOpts.filter(item, me.chart.data);
  16970. });
  16971. }
  16972. if (me.options.reverse) {
  16973. legendItems.reverse();
  16974. }
  16975. me.legendItems = legendItems;
  16976. },
  16977. afterBuildLabels: noop$1,
  16978. //
  16979. beforeFit: noop$1,
  16980. fit: function() {
  16981. var me = this;
  16982. var opts = me.options;
  16983. var labelOpts = opts.labels;
  16984. var display = opts.display;
  16985. var ctx = me.ctx;
  16986. var labelFont = helpers$1.options._parseFont(labelOpts);
  16987. var fontSize = labelFont.size;
  16988. // Reset hit boxes
  16989. var hitboxes = me.legendHitBoxes = [];
  16990. var minSize = me.minSize;
  16991. var isHorizontal = me.isHorizontal();
  16992. if (isHorizontal) {
  16993. minSize.width = me.maxWidth; // fill all the width
  16994. minSize.height = display ? 10 : 0;
  16995. } else {
  16996. minSize.width = display ? 10 : 0;
  16997. minSize.height = me.maxHeight; // fill all the height
  16998. }
  16999. // Increase sizes here
  17000. if (!display) {
  17001. me.width = minSize.width = me.height = minSize.height = 0;
  17002. return;
  17003. }
  17004. ctx.font = labelFont.string;
  17005. if (isHorizontal) {
  17006. // Labels
  17007. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  17008. var lineWidths = me.lineWidths = [0];
  17009. var totalHeight = 0;
  17010. ctx.textAlign = 'left';
  17011. ctx.textBaseline = 'middle';
  17012. helpers$1.each(me.legendItems, function(legendItem, i) {
  17013. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17014. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  17015. if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {
  17016. totalHeight += fontSize + labelOpts.padding;
  17017. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  17018. }
  17019. // Store the hitbox width and height here. Final position will be updated in `draw`
  17020. hitboxes[i] = {
  17021. left: 0,
  17022. top: 0,
  17023. width: width,
  17024. height: fontSize
  17025. };
  17026. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  17027. });
  17028. minSize.height += totalHeight;
  17029. } else {
  17030. var vPadding = labelOpts.padding;
  17031. var columnWidths = me.columnWidths = [];
  17032. var columnHeights = me.columnHeights = [];
  17033. var totalWidth = labelOpts.padding;
  17034. var currentColWidth = 0;
  17035. var currentColHeight = 0;
  17036. helpers$1.each(me.legendItems, function(legendItem, i) {
  17037. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17038. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  17039. // If too tall, go to new column
  17040. if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) {
  17041. totalWidth += currentColWidth + labelOpts.padding;
  17042. columnWidths.push(currentColWidth); // previous column width
  17043. columnHeights.push(currentColHeight);
  17044. currentColWidth = 0;
  17045. currentColHeight = 0;
  17046. }
  17047. // Get max width
  17048. currentColWidth = Math.max(currentColWidth, itemWidth);
  17049. currentColHeight += fontSize + vPadding;
  17050. // Store the hitbox width and height here. Final position will be updated in `draw`
  17051. hitboxes[i] = {
  17052. left: 0,
  17053. top: 0,
  17054. width: itemWidth,
  17055. height: fontSize
  17056. };
  17057. });
  17058. totalWidth += currentColWidth;
  17059. columnWidths.push(currentColWidth);
  17060. columnHeights.push(currentColHeight);
  17061. minSize.width += totalWidth;
  17062. }
  17063. me.width = minSize.width;
  17064. me.height = minSize.height;
  17065. },
  17066. afterFit: noop$1,
  17067. // Shared Methods
  17068. isHorizontal: function() {
  17069. return this.options.position === 'top' || this.options.position === 'bottom';
  17070. },
  17071. // Actually draw the legend on the canvas
  17072. draw: function() {
  17073. var me = this;
  17074. var opts = me.options;
  17075. var labelOpts = opts.labels;
  17076. var globalDefaults = core_defaults.global;
  17077. var defaultColor = globalDefaults.defaultColor;
  17078. var lineDefault = globalDefaults.elements.line;
  17079. var legendHeight = me.height;
  17080. var columnHeights = me.columnHeights;
  17081. var legendWidth = me.width;
  17082. var lineWidths = me.lineWidths;
  17083. if (!opts.display) {
  17084. return;
  17085. }
  17086. var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);
  17087. var ctx = me.ctx;
  17088. var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);
  17089. var labelFont = helpers$1.options._parseFont(labelOpts);
  17090. var fontSize = labelFont.size;
  17091. var cursor;
  17092. // Canvas setup
  17093. ctx.textAlign = rtlHelper.textAlign('left');
  17094. ctx.textBaseline = 'middle';
  17095. ctx.lineWidth = 0.5;
  17096. ctx.strokeStyle = fontColor; // for strikethrough effect
  17097. ctx.fillStyle = fontColor; // render in correct colour
  17098. ctx.font = labelFont.string;
  17099. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17100. var hitboxes = me.legendHitBoxes;
  17101. // current position
  17102. var drawLegendBox = function(x, y, legendItem) {
  17103. if (isNaN(boxWidth) || boxWidth <= 0) {
  17104. return;
  17105. }
  17106. // Set the ctx for the box
  17107. ctx.save();
  17108. var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);
  17109. ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);
  17110. ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);
  17111. ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  17112. ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);
  17113. ctx.lineWidth = lineWidth;
  17114. ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);
  17115. if (ctx.setLineDash) {
  17116. // IE 9 and 10 do not support line dash
  17117. ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));
  17118. }
  17119. if (labelOpts && labelOpts.usePointStyle) {
  17120. // Recalculate x and y for drawPoint() because its expecting
  17121. // x and y to be center of figure (instead of top left)
  17122. var radius = boxWidth * Math.SQRT2 / 2;
  17123. var centerX = rtlHelper.xPlus(x, boxWidth / 2);
  17124. var centerY = y + fontSize / 2;
  17125. // Draw pointStyle as legend symbol
  17126. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
  17127. } else {
  17128. // Draw box as legend symbol
  17129. ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  17130. if (lineWidth !== 0) {
  17131. ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  17132. }
  17133. }
  17134. ctx.restore();
  17135. };
  17136. var fillText = function(x, y, legendItem, textWidth) {
  17137. var halfFontSize = fontSize / 2;
  17138. var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
  17139. var yMiddle = y + halfFontSize;
  17140. ctx.fillText(legendItem.text, xLeft, yMiddle);
  17141. if (legendItem.hidden) {
  17142. // Strikethrough the text if hidden
  17143. ctx.beginPath();
  17144. ctx.lineWidth = 2;
  17145. ctx.moveTo(xLeft, yMiddle);
  17146. ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);
  17147. ctx.stroke();
  17148. }
  17149. };
  17150. var alignmentOffset = function(dimension, blockSize) {
  17151. switch (opts.align) {
  17152. case 'start':
  17153. return labelOpts.padding;
  17154. case 'end':
  17155. return dimension - blockSize;
  17156. default: // center
  17157. return (dimension - blockSize + labelOpts.padding) / 2;
  17158. }
  17159. };
  17160. // Horizontal
  17161. var isHorizontal = me.isHorizontal();
  17162. if (isHorizontal) {
  17163. cursor = {
  17164. x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
  17165. y: me.top + labelOpts.padding,
  17166. line: 0
  17167. };
  17168. } else {
  17169. cursor = {
  17170. x: me.left + labelOpts.padding,
  17171. y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
  17172. line: 0
  17173. };
  17174. }
  17175. helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);
  17176. var itemHeight = fontSize + labelOpts.padding;
  17177. helpers$1.each(me.legendItems, function(legendItem, i) {
  17178. var textWidth = ctx.measureText(legendItem.text).width;
  17179. var width = boxWidth + (fontSize / 2) + textWidth;
  17180. var x = cursor.x;
  17181. var y = cursor.y;
  17182. rtlHelper.setWidth(me.minSize.width);
  17183. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  17184. // instead of me.right and me.bottom because me.width and me.height
  17185. // may have been changed since me.minSize was calculated
  17186. if (isHorizontal) {
  17187. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  17188. y = cursor.y += itemHeight;
  17189. cursor.line++;
  17190. x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
  17191. }
  17192. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  17193. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  17194. cursor.line++;
  17195. y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
  17196. }
  17197. var realX = rtlHelper.x(x);
  17198. drawLegendBox(realX, y, legendItem);
  17199. hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);
  17200. hitboxes[i].top = y;
  17201. // Fill the actual label
  17202. fillText(realX, y, legendItem, textWidth);
  17203. if (isHorizontal) {
  17204. cursor.x += width + labelOpts.padding;
  17205. } else {
  17206. cursor.y += itemHeight;
  17207. }
  17208. });
  17209. helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);
  17210. },
  17211. /**
  17212. * @private
  17213. */
  17214. _getLegendItemAt: function(x, y) {
  17215. var me = this;
  17216. var i, hitBox, lh;
  17217. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  17218. // See if we are touching one of the dataset boxes
  17219. lh = me.legendHitBoxes;
  17220. for (i = 0; i < lh.length; ++i) {
  17221. hitBox = lh[i];
  17222. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  17223. // Touching an element
  17224. return me.legendItems[i];
  17225. }
  17226. }
  17227. }
  17228. return null;
  17229. },
  17230. /**
  17231. * Handle an event
  17232. * @private
  17233. * @param {IEvent} event - The event to handle
  17234. */
  17235. handleEvent: function(e) {
  17236. var me = this;
  17237. var opts = me.options;
  17238. var type = e.type === 'mouseup' ? 'click' : e.type;
  17239. var hoveredItem;
  17240. if (type === 'mousemove') {
  17241. if (!opts.onHover && !opts.onLeave) {
  17242. return;
  17243. }
  17244. } else if (type === 'click') {
  17245. if (!opts.onClick) {
  17246. return;
  17247. }
  17248. } else {
  17249. return;
  17250. }
  17251. // Chart event already has relative position in it
  17252. hoveredItem = me._getLegendItemAt(e.x, e.y);
  17253. if (type === 'click') {
  17254. if (hoveredItem && opts.onClick) {
  17255. // use e.native for backwards compatibility
  17256. opts.onClick.call(me, e.native, hoveredItem);
  17257. }
  17258. } else {
  17259. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  17260. if (me._hoveredItem) {
  17261. opts.onLeave.call(me, e.native, me._hoveredItem);
  17262. }
  17263. me._hoveredItem = hoveredItem;
  17264. }
  17265. if (opts.onHover && hoveredItem) {
  17266. // use e.native for backwards compatibility
  17267. opts.onHover.call(me, e.native, hoveredItem);
  17268. }
  17269. }
  17270. }
  17271. });
  17272. function createNewLegendAndAttach(chart, legendOpts) {
  17273. var legend = new Legend({
  17274. ctx: chart.ctx,
  17275. options: legendOpts,
  17276. chart: chart
  17277. });
  17278. core_layouts.configure(chart, legend, legendOpts);
  17279. core_layouts.addBox(chart, legend);
  17280. chart.legend = legend;
  17281. }
  17282. var plugin_legend = {
  17283. id: 'legend',
  17284. /**
  17285. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  17286. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  17287. * the plugin, which one will be re-exposed in the chart.js file.
  17288. * https://github.com/chartjs/Chart.js/pull/2640
  17289. * @private
  17290. */
  17291. _element: Legend,
  17292. beforeInit: function(chart) {
  17293. var legendOpts = chart.options.legend;
  17294. if (legendOpts) {
  17295. createNewLegendAndAttach(chart, legendOpts);
  17296. }
  17297. },
  17298. beforeUpdate: function(chart) {
  17299. var legendOpts = chart.options.legend;
  17300. var legend = chart.legend;
  17301. if (legendOpts) {
  17302. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  17303. if (legend) {
  17304. core_layouts.configure(chart, legend, legendOpts);
  17305. legend.options = legendOpts;
  17306. } else {
  17307. createNewLegendAndAttach(chart, legendOpts);
  17308. }
  17309. } else if (legend) {
  17310. core_layouts.removeBox(chart, legend);
  17311. delete chart.legend;
  17312. }
  17313. },
  17314. afterEvent: function(chart, e) {
  17315. var legend = chart.legend;
  17316. if (legend) {
  17317. legend.handleEvent(e);
  17318. }
  17319. }
  17320. };
  17321. var noop$2 = helpers$1.noop;
  17322. core_defaults._set('global', {
  17323. title: {
  17324. display: false,
  17325. fontStyle: 'bold',
  17326. fullWidth: true,
  17327. padding: 10,
  17328. position: 'top',
  17329. text: '',
  17330. weight: 2000 // by default greater than legend (1000) to be above
  17331. }
  17332. });
  17333. /**
  17334. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  17335. */
  17336. var Title = core_element.extend({
  17337. initialize: function(config) {
  17338. var me = this;
  17339. helpers$1.extend(me, config);
  17340. // Contains hit boxes for each dataset (in dataset order)
  17341. me.legendHitBoxes = [];
  17342. },
  17343. // These methods are ordered by lifecycle. Utilities then follow.
  17344. beforeUpdate: noop$2,
  17345. update: function(maxWidth, maxHeight, margins) {
  17346. var me = this;
  17347. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  17348. me.beforeUpdate();
  17349. // Absorb the master measurements
  17350. me.maxWidth = maxWidth;
  17351. me.maxHeight = maxHeight;
  17352. me.margins = margins;
  17353. // Dimensions
  17354. me.beforeSetDimensions();
  17355. me.setDimensions();
  17356. me.afterSetDimensions();
  17357. // Labels
  17358. me.beforeBuildLabels();
  17359. me.buildLabels();
  17360. me.afterBuildLabels();
  17361. // Fit
  17362. me.beforeFit();
  17363. me.fit();
  17364. me.afterFit();
  17365. //
  17366. me.afterUpdate();
  17367. return me.minSize;
  17368. },
  17369. afterUpdate: noop$2,
  17370. //
  17371. beforeSetDimensions: noop$2,
  17372. setDimensions: function() {
  17373. var me = this;
  17374. // Set the unconstrained dimension before label rotation
  17375. if (me.isHorizontal()) {
  17376. // Reset position before calculating rotation
  17377. me.width = me.maxWidth;
  17378. me.left = 0;
  17379. me.right = me.width;
  17380. } else {
  17381. me.height = me.maxHeight;
  17382. // Reset position before calculating rotation
  17383. me.top = 0;
  17384. me.bottom = me.height;
  17385. }
  17386. // Reset padding
  17387. me.paddingLeft = 0;
  17388. me.paddingTop = 0;
  17389. me.paddingRight = 0;
  17390. me.paddingBottom = 0;
  17391. // Reset minSize
  17392. me.minSize = {
  17393. width: 0,
  17394. height: 0
  17395. };
  17396. },
  17397. afterSetDimensions: noop$2,
  17398. //
  17399. beforeBuildLabels: noop$2,
  17400. buildLabels: noop$2,
  17401. afterBuildLabels: noop$2,
  17402. //
  17403. beforeFit: noop$2,
  17404. fit: function() {
  17405. var me = this;
  17406. var opts = me.options;
  17407. var minSize = me.minSize = {};
  17408. var isHorizontal = me.isHorizontal();
  17409. var lineCount, textSize;
  17410. if (!opts.display) {
  17411. me.width = minSize.width = me.height = minSize.height = 0;
  17412. return;
  17413. }
  17414. lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  17415. textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;
  17416. me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
  17417. me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
  17418. },
  17419. afterFit: noop$2,
  17420. // Shared Methods
  17421. isHorizontal: function() {
  17422. var pos = this.options.position;
  17423. return pos === 'top' || pos === 'bottom';
  17424. },
  17425. // Actually draw the title block on the canvas
  17426. draw: function() {
  17427. var me = this;
  17428. var ctx = me.ctx;
  17429. var opts = me.options;
  17430. if (!opts.display) {
  17431. return;
  17432. }
  17433. var fontOpts = helpers$1.options._parseFont(opts);
  17434. var lineHeight = fontOpts.lineHeight;
  17435. var offset = lineHeight / 2 + opts.padding;
  17436. var rotation = 0;
  17437. var top = me.top;
  17438. var left = me.left;
  17439. var bottom = me.bottom;
  17440. var right = me.right;
  17441. var maxWidth, titleX, titleY;
  17442. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  17443. ctx.font = fontOpts.string;
  17444. // Horizontal
  17445. if (me.isHorizontal()) {
  17446. titleX = left + ((right - left) / 2); // midpoint of the width
  17447. titleY = top + offset;
  17448. maxWidth = right - left;
  17449. } else {
  17450. titleX = opts.position === 'left' ? left + offset : right - offset;
  17451. titleY = top + ((bottom - top) / 2);
  17452. maxWidth = bottom - top;
  17453. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  17454. }
  17455. ctx.save();
  17456. ctx.translate(titleX, titleY);
  17457. ctx.rotate(rotation);
  17458. ctx.textAlign = 'center';
  17459. ctx.textBaseline = 'middle';
  17460. var text = opts.text;
  17461. if (helpers$1.isArray(text)) {
  17462. var y = 0;
  17463. for (var i = 0; i < text.length; ++i) {
  17464. ctx.fillText(text[i], 0, y, maxWidth);
  17465. y += lineHeight;
  17466. }
  17467. } else {
  17468. ctx.fillText(text, 0, 0, maxWidth);
  17469. }
  17470. ctx.restore();
  17471. }
  17472. });
  17473. function createNewTitleBlockAndAttach(chart, titleOpts) {
  17474. var title = new Title({
  17475. ctx: chart.ctx,
  17476. options: titleOpts,
  17477. chart: chart
  17478. });
  17479. core_layouts.configure(chart, title, titleOpts);
  17480. core_layouts.addBox(chart, title);
  17481. chart.titleBlock = title;
  17482. }
  17483. var plugin_title = {
  17484. id: 'title',
  17485. /**
  17486. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  17487. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  17488. * the plugin, which one will be re-exposed in the chart.js file.
  17489. * https://github.com/chartjs/Chart.js/pull/2640
  17490. * @private
  17491. */
  17492. _element: Title,
  17493. beforeInit: function(chart) {
  17494. var titleOpts = chart.options.title;
  17495. if (titleOpts) {
  17496. createNewTitleBlockAndAttach(chart, titleOpts);
  17497. }
  17498. },
  17499. beforeUpdate: function(chart) {
  17500. var titleOpts = chart.options.title;
  17501. var titleBlock = chart.titleBlock;
  17502. if (titleOpts) {
  17503. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  17504. if (titleBlock) {
  17505. core_layouts.configure(chart, titleBlock, titleOpts);
  17506. titleBlock.options = titleOpts;
  17507. } else {
  17508. createNewTitleBlockAndAttach(chart, titleOpts);
  17509. }
  17510. } else if (titleBlock) {
  17511. core_layouts.removeBox(chart, titleBlock);
  17512. delete chart.titleBlock;
  17513. }
  17514. }
  17515. };
  17516. var plugins = {};
  17517. var filler = plugin_filler;
  17518. var legend = plugin_legend;
  17519. var title = plugin_title;
  17520. plugins.filler = filler;
  17521. plugins.legend = legend;
  17522. plugins.title = title;
  17523. /**
  17524. * @namespace Chart
  17525. */
  17526. core_controller.helpers = helpers$1;
  17527. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  17528. core_helpers();
  17529. core_controller._adapters = core_adapters;
  17530. core_controller.Animation = core_animation;
  17531. core_controller.animationService = core_animations;
  17532. core_controller.controllers = controllers;
  17533. core_controller.DatasetController = core_datasetController;
  17534. core_controller.defaults = core_defaults;
  17535. core_controller.Element = core_element;
  17536. core_controller.elements = elements;
  17537. core_controller.Interaction = core_interaction;
  17538. core_controller.layouts = core_layouts;
  17539. core_controller.platform = platform;
  17540. core_controller.plugins = core_plugins;
  17541. core_controller.Scale = core_scale;
  17542. core_controller.scaleService = core_scaleService;
  17543. core_controller.Ticks = core_ticks;
  17544. core_controller.Tooltip = core_tooltip;
  17545. // Register built-in scales
  17546. core_controller.helpers.each(scales, function(scale, type) {
  17547. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  17548. });
  17549. // Load to register built-in adapters (as side effects)
  17550. // Loading built-in plugins
  17551. for (var k in plugins) {
  17552. if (plugins.hasOwnProperty(k)) {
  17553. core_controller.plugins.register(plugins[k]);
  17554. }
  17555. }
  17556. core_controller.platform.initialize();
  17557. var src = core_controller;
  17558. if (typeof window !== 'undefined') {
  17559. window.Chart = core_controller;
  17560. }
  17561. // DEPRECATIONS
  17562. /**
  17563. * Provided for backward compatibility, not available anymore
  17564. * @namespace Chart.Chart
  17565. * @deprecated since version 2.8.0
  17566. * @todo remove at version 3
  17567. * @private
  17568. */
  17569. core_controller.Chart = core_controller;
  17570. /**
  17571. * Provided for backward compatibility, not available anymore
  17572. * @namespace Chart.Legend
  17573. * @deprecated since version 2.1.5
  17574. * @todo remove at version 3
  17575. * @private
  17576. */
  17577. core_controller.Legend = plugins.legend._element;
  17578. /**
  17579. * Provided for backward compatibility, not available anymore
  17580. * @namespace Chart.Title
  17581. * @deprecated since version 2.1.5
  17582. * @todo remove at version 3
  17583. * @private
  17584. */
  17585. core_controller.Title = plugins.title._element;
  17586. /**
  17587. * Provided for backward compatibility, use Chart.plugins instead
  17588. * @namespace Chart.pluginService
  17589. * @deprecated since version 2.1.5
  17590. * @todo remove at version 3
  17591. * @private
  17592. */
  17593. core_controller.pluginService = core_controller.plugins;
  17594. /**
  17595. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  17596. * effect, instead simply create/register plugins via plain JavaScript objects.
  17597. * @interface Chart.PluginBase
  17598. * @deprecated since version 2.5.0
  17599. * @todo remove at version 3
  17600. * @private
  17601. */
  17602. core_controller.PluginBase = core_controller.Element.extend({});
  17603. /**
  17604. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  17605. * @namespace Chart.canvasHelpers
  17606. * @deprecated since version 2.6.0
  17607. * @todo remove at version 3
  17608. * @private
  17609. */
  17610. core_controller.canvasHelpers = core_controller.helpers.canvas;
  17611. /**
  17612. * Provided for backward compatibility, use Chart.layouts instead.
  17613. * @namespace Chart.layoutService
  17614. * @deprecated since version 2.7.3
  17615. * @todo remove at version 3
  17616. * @private
  17617. */
  17618. core_controller.layoutService = core_controller.layouts;
  17619. /**
  17620. * Provided for backward compatibility, not available anymore.
  17621. * @namespace Chart.LinearScaleBase
  17622. * @deprecated since version 2.8
  17623. * @todo remove at version 3
  17624. * @private
  17625. */
  17626. core_controller.LinearScaleBase = scale_linearbase;
  17627. /**
  17628. * Provided for backward compatibility, instead we should create a new Chart
  17629. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  17630. * @deprecated since version 2.8.0
  17631. * @todo remove at version 3
  17632. */
  17633. core_controller.helpers.each(
  17634. [
  17635. 'Bar',
  17636. 'Bubble',
  17637. 'Doughnut',
  17638. 'Line',
  17639. 'PolarArea',
  17640. 'Radar',
  17641. 'Scatter'
  17642. ],
  17643. function(klass) {
  17644. core_controller[klass] = function(ctx, cfg) {
  17645. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  17646. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  17647. }));
  17648. };
  17649. }
  17650. );
  17651. return src;
  17652. })));