hls-demo.js 751 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578
  1. (function (factory) {
  2. typeof define === 'function' && define.amd ? define(factory) :
  3. factory();
  4. })((function () { 'use strict';
  5. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  6. function getDefaultExportFromCjs (x) {
  7. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  8. }
  9. /**
  10. * Create test stream
  11. * @param {string} url
  12. * @param {string} description
  13. * @param {boolean} [live]
  14. * @param {boolean} [abr]
  15. * @param {string[]} [skip_ua]
  16. * @returns {{url: string, description: string, live: boolean, abr: boolean, skip_ua: string[]}}
  17. */
  18. function createTestStream(url, description, live, abr, skip_ua) {
  19. if (live === void 0) {
  20. live = false;
  21. }
  22. if (abr === void 0) {
  23. abr = true;
  24. }
  25. if (skip_ua === void 0) {
  26. skip_ua = [];
  27. }
  28. return {
  29. url: url,
  30. description: description,
  31. live: live,
  32. abr: abr,
  33. skip_ua: skip_ua
  34. };
  35. }
  36. /**
  37. * @param {Object} target
  38. * @param {Object} [config]
  39. * @returns {{url: string, description: string, live: boolean, abr: boolean, skip_ua: string[]}}
  40. */
  41. function createTestStreamWithConfig(target, config) {
  42. if (typeof target !== 'object') {
  43. throw new Error('target should be object');
  44. }
  45. var testStream = createTestStream(target.url, target.description, target.live, target.abr, target.skip_ua);
  46. testStream.config = config;
  47. return testStream;
  48. }
  49. var testStreams$1 = {
  50. bbb: {
  51. url: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
  52. description: 'Big Buck Bunny - adaptive qualities',
  53. abr: true
  54. },
  55. fdr: {
  56. url: 'https://cdn.jwplayer.com/manifests/pZxWPRg4.m3u8',
  57. description: 'FDR - CDN packaged, 4s segments, 180p - 1080p',
  58. abr: true
  59. },
  60. bigBuckBunny480p: {
  61. url: 'https://test-streams.mux.dev/x36xhzz/url_6/193039199_mp4_h264_aac_hq_7.m3u8',
  62. description: 'Big Buck Bunny - 480p only',
  63. abr: false
  64. },
  65. arte: {
  66. url: 'https://test-streams.mux.dev/test_001/stream.m3u8',
  67. description: 'ARTE China,ABR',
  68. abr: true
  69. },
  70. deltatreDAI: {
  71. url: 'https://test-streams.mux.dev/dai-discontinuity-deltatre/manifest.m3u8',
  72. description: 'Ad-insertion in event stream',
  73. abr: false
  74. },
  75. issue666: {
  76. url: 'https://playertest.longtailvideo.com/adaptive/issue666/playlists/cisq0gim60007xzvi505emlxx.m3u8',
  77. description: 'Surveillance footage - https://github.com/video-dev/hls.js/issues/666',
  78. abr: false
  79. },
  80. closedCaptions: {
  81. url: 'https://playertest.longtailvideo.com/adaptive/captions/playlist.m3u8',
  82. description: 'CNN special report, with CC',
  83. abr: false
  84. },
  85. customIvBadDts: {
  86. url: 'https://playertest.longtailvideo.com/adaptive/customIV/prog_index.m3u8',
  87. description: 'Custom IV with bad PTS DTS',
  88. abr: false
  89. },
  90. oceansAES: {
  91. url: 'https://playertest.longtailvideo.com/adaptive/oceans_aes/oceans_aes.m3u8',
  92. description: 'AES-128 encrypted, ABR',
  93. abr: true
  94. },
  95. tracksWithAES: {
  96. url: 'https://playertest.longtailvideo.com/adaptive/aes-with-tracks/master.m3u8',
  97. description: 'AES-128 encrypted, TS main with AAC audio track',
  98. abr: false
  99. },
  100. mp3Audio: {
  101. url: 'https://playertest.longtailvideo.com/adaptive/vod-with-mp3/manifest.m3u8',
  102. description: 'MP3 VOD demo',
  103. abr: false
  104. },
  105. mpegAudioOnly: {
  106. url: 'https://pl.streamingvideoprovider.com/mp3-playlist/playlist.m3u8',
  107. description: 'MPEG Audio Only demo',
  108. abr: false,
  109. skip_ua: ['MicrosoftEdge', 'firefox']
  110. },
  111. fmp4: {
  112. url: 'https://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8',
  113. description: 'HLS fMP4 Angel-One multiple audio-tracks',
  114. abr: true
  115. },
  116. fmp4Bitmovin: {
  117. url: 'https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s-fmp4/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8',
  118. description: 'HLS fMP4 by Bitmovin',
  119. abr: true
  120. },
  121. fmp4BitmovinHevc: {
  122. url: 'https://bitmovin-a.akamaihd.net/content/dataset/multi-codec/hevc/stream_fmp4.m3u8',
  123. description: 'HLS HEVC fMP4 by Bitmovin (Safari and Edge? only as of 2020-08)',
  124. abr: true,
  125. skipFunctionalTests: true
  126. },
  127. offset_pts: {
  128. url: 'https://test-streams.mux.dev/pts_shift/master.m3u8',
  129. description: 'DK Turntable, PTS shifted by 2.3s',
  130. abr: true
  131. },
  132. angelOneShakaWidevine: createTestStreamWithConfig({
  133. url: 'https://storage.googleapis.com/shaka-demo-assets/angel-one-widevine-hls/hls.m3u8',
  134. description: 'Shaka-packager Widevine DRM (EME) HLS-fMP4 - Angel One Demo',
  135. abr: true,
  136. skip_ua: ['firefox', 'safari', {
  137. name: 'chrome',
  138. version: '75.0'
  139. }, {
  140. name: 'chrome',
  141. version: '79.0'
  142. }]
  143. }, {
  144. widevineLicenseUrl: 'https://cwip-shaka-proxy.appspot.com/no_auth',
  145. emeEnabled: true
  146. }),
  147. audioOnlyMultipleLevels: {
  148. url: 'https://s3.amazonaws.com/qa.jwplayer.com/~alex/121628/new_master.m3u8',
  149. description: 'Multiple non-alternate audio levels',
  150. abr: true
  151. },
  152. pdtDuplicate: {
  153. url: 'https://playertest.longtailvideo.com/adaptive/artbeats/manifest.m3u8',
  154. description: 'Duplicate sequential PDT values',
  155. abr: false
  156. },
  157. pdtLargeGap: {
  158. url: 'https://playertest.longtailvideo.com/adaptive/boxee/playlist.m3u8',
  159. description: 'PDTs with large gaps following discontinuities',
  160. abr: false
  161. },
  162. pdtBadValues: {
  163. url: 'https://playertest.longtailvideo.com/adaptive/progdatime/playlist2.m3u8',
  164. description: 'PDTs with bad values',
  165. abr: false
  166. },
  167. pdtOneValue: {
  168. url: 'https://playertest.longtailvideo.com/adaptive/aviion/manifest.m3u8',
  169. description: 'One PDT, no discontinuities',
  170. abr: false
  171. },
  172. noTrackIntersection: createTestStreamWithConfig({
  173. url: 'https://s3.amazonaws.com/qa.jwplayer.com/~alex/123633/new_master.m3u8',
  174. description: 'Audio/video track PTS values do not intersect; 10 second start gap',
  175. abr: false
  176. }, {
  177. avBufferOffset: 10.5
  178. }),
  179. altAudioAndTracks: {
  180. // url: 'https://wowzaec2demo.streamlock.net/vod-multitrack/_definst_/smil:ElephantsDream/elephantsdream2.smil/playlist.m3u',
  181. url: 'https://playertest.longtailvideo.com/adaptive/elephants_dream_v4/index.m3u8',
  182. description: 'Alternate audio tracks, and multiple VTT tracks',
  183. vendor: 'wowza',
  184. abr: true
  185. },
  186. altAudioAudioOnly: createTestStreamWithConfig({
  187. url: 'https://playertest.longtailvideo.com/adaptive/alt-audio-no-video/sintel/playlist.m3u8',
  188. description: 'Audio only with alternate audio track (Sintel)',
  189. abr: false
  190. }, {
  191. // the playlist segment durations are longer than the media. So much so, that when seeking near the end,
  192. // the timeline shifts roughly 10 seconds seconds back, and as a result buffering skips several segments
  193. // to adjust for the currentTime now being places at the very end of the stream.
  194. allowedBufferedRangesInSeekTest: 3
  195. }),
  196. altAudioMultiAudioOnly: {
  197. url: 'https://playertest.longtailvideo.com/adaptive/alt-audio-no-video/angel-one.m3u8',
  198. description: 'Audio only with multiple alternate audio tracks (Angel One)',
  199. abr: false
  200. },
  201. muxedFmp4: {
  202. url: 'https://s3.amazonaws.com/qa.jwplayer.com/hlsjs/muxed-fmp4/hls.m3u8',
  203. description: 'Muxed av fmp4 - appended to "audiovideo" SourceBuffer',
  204. abr: false
  205. },
  206. altAudioWithPdtAndStartGap: {
  207. url: 'https://playertest.longtailvideo.com/adaptive/hls-test-streams/test-audio-pdt/playlist.m3u8',
  208. description: 'PDT before each segment, 1.59s start gap',
  209. // Disable smooth switch on this stream. Test is flakey because of what looks like (auto)play issue. To be expected with this large a gap (for now).
  210. // abr: true,
  211. startSeek: true
  212. },
  213. AppleAdvancedHevcAvcHls: {
  214. url: 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/master.m3u8',
  215. description: 'Advanced stream (HEVC/H.264, AC-3/AAC, WebVTT, fMP4 segments)'
  216. },
  217. MuxLowLatencyHls: {
  218. url: 'https://stream.mux.com/v69RSHhFelSm4701snP22dYz2jICy4E4FUyk02rW4gxRM.m3u8',
  219. description: 'Low-Latency HLS sample of Big Buck Bunny loop and a timer. Restarts every 12 hours. (fMP4 segments)',
  220. live: true
  221. },
  222. // AppleLowLatencyHls: {
  223. // url: 'https://ll-hls-test.apple.com/master.m3u8',
  224. // description: 'Apple Low-Latency HLS sample (TS segments)',
  225. // live: true,
  226. // },
  227. // AppleLowLatencyCmafHls: {
  228. // url: 'https://ll-hls-test.apple.com/cmaf/master.m3u8',
  229. // description: 'Apple Low-Latency HLS sample (fMP4 segments)',
  230. // live: true,
  231. // },
  232. groupIds: {
  233. url: 'https://mtoczko.github.io/hls-test-streams/test-group/playlist.m3u8',
  234. description: 'Group-id: subtitle and audio',
  235. abr: true,
  236. skipFunctionalTests: true
  237. },
  238. redundantLevelsWithTrackGroups: {
  239. url: 'https://playertest.longtailvideo.com/adaptive/elephants_dream_v4/redundant.m3u8',
  240. description: 'Redundant levels with subtitle and audio track groups',
  241. abr: true,
  242. skipFunctionalTests: true
  243. },
  244. startDelimiterOverlappingBetweenPESPackets: {
  245. url: 'https://hlsjs-test-streams-wistia.s3.amazonaws.com/start-delimiter.m3u8',
  246. description: "A stream with the start delimiter overlapping between PES packets.\n Related to https://github.com/video-dev/hls.js/issues/3834, where Apple Silicon chips throw decoding errors if\n NAL units are not starting right at the beginning of the PES packet when using hardware accelerated decoding.",
  247. abr: false
  248. }
  249. };
  250. var main = {};
  251. /*
  252. Copyright (c) 2013, Rodrigo González, Sapienlab All Rights Reserved.
  253. Available via MIT LICENSE. See https://github.com/roro89/jsonpack/blob/master/LICENSE.md for details.
  254. */
  255. (function (exports) {
  256. (function(define) {
  257. define([], function() {
  258. var TOKEN_TRUE = -1;
  259. var TOKEN_FALSE = -2;
  260. var TOKEN_NULL = -3;
  261. var TOKEN_EMPTY_STRING = -4;
  262. var TOKEN_UNDEFINED = -5;
  263. var pack = function(json, options) {
  264. // Canonizes the options
  265. options = options || {};
  266. // A shorthand for debugging
  267. var verbose = options.verbose || false;
  268. verbose && console.log('Normalize the JSON Object');
  269. // JSON as Javascript Object (Not string representation)
  270. json = typeof json === 'string' ? this.JSON.parse(json) : json;
  271. verbose && console.log('Creating a empty dictionary');
  272. // The dictionary
  273. var dictionary = {
  274. strings : [],
  275. integers : [],
  276. floats : []
  277. };
  278. verbose && console.log('Creating the AST');
  279. // The AST
  280. var ast = (function recursiveAstBuilder(item) {
  281. verbose && console.log('Calling recursiveAstBuilder with ' + this.JSON.stringify(item));
  282. // The type of the item
  283. var type = typeof item;
  284. // Case 7: The item is null
  285. if (item === null) {
  286. return {
  287. type : 'null',
  288. index : TOKEN_NULL
  289. };
  290. }
  291. //add undefined
  292. if (typeof item === 'undefined') {
  293. return {
  294. type : 'undefined',
  295. index : TOKEN_UNDEFINED
  296. };
  297. }
  298. // Case 1: The item is Array Object
  299. if ( item instanceof Array) {
  300. // Create a new sub-AST of type Array (@)
  301. var ast = ['@'];
  302. // Add each items
  303. for (var i in item) {
  304. if (!item.hasOwnProperty(i)) continue;
  305. ast.push(recursiveAstBuilder(item[i]));
  306. }
  307. // And return
  308. return ast;
  309. }
  310. // Case 2: The item is Object
  311. if (type === 'object') {
  312. // Create a new sub-AST of type Object ($)
  313. var ast = ['$'];
  314. // Add each items
  315. for (var key in item) {
  316. if (!item.hasOwnProperty(key))
  317. continue;
  318. ast.push(recursiveAstBuilder(key));
  319. ast.push(recursiveAstBuilder(item[key]));
  320. }
  321. // And return
  322. return ast;
  323. }
  324. // Case 3: The item empty string
  325. if (item === '') {
  326. return {
  327. type : 'empty',
  328. index : TOKEN_EMPTY_STRING
  329. };
  330. }
  331. // Case 4: The item is String
  332. if (type === 'string') {
  333. // The index of that word in the dictionary
  334. var index = _indexOf.call(dictionary.strings, item);
  335. // If not, add to the dictionary and actualize the index
  336. if (index == -1) {
  337. dictionary.strings.push(_encode(item));
  338. index = dictionary.strings.length - 1;
  339. }
  340. // Return the token
  341. return {
  342. type : 'strings',
  343. index : index
  344. };
  345. }
  346. // Case 5: The item is integer
  347. if (type === 'number' && item % 1 === 0) {
  348. // The index of that number in the dictionary
  349. var index = _indexOf.call(dictionary.integers, item);
  350. // If not, add to the dictionary and actualize the index
  351. if (index == -1) {
  352. dictionary.integers.push(_base10To36(item));
  353. index = dictionary.integers.length - 1;
  354. }
  355. // Return the token
  356. return {
  357. type : 'integers',
  358. index : index
  359. };
  360. }
  361. // Case 6: The item is float
  362. if (type === 'number') {
  363. // The index of that number in the dictionary
  364. var index = _indexOf.call(dictionary.floats, item);
  365. // If not, add to the dictionary and actualize the index
  366. if (index == -1) {
  367. // Float not use base 36
  368. dictionary.floats.push(item);
  369. index = dictionary.floats.length - 1;
  370. }
  371. // Return the token
  372. return {
  373. type : 'floats',
  374. index : index
  375. };
  376. }
  377. // Case 7: The item is boolean
  378. if (type === 'boolean') {
  379. return {
  380. type : 'boolean',
  381. index : item ? TOKEN_TRUE : TOKEN_FALSE
  382. };
  383. }
  384. // Default
  385. throw new Error('Unexpected argument of type ' + typeof (item));
  386. })(json);
  387. // A set of shorthands proxies for the length of the dictionaries
  388. var stringLength = dictionary.strings.length;
  389. var integerLength = dictionary.integers.length;
  390. dictionary.floats.length;
  391. verbose && console.log('Parsing the dictionary');
  392. // Create a raw dictionary
  393. var packed = dictionary.strings.join('|');
  394. packed += '^' + dictionary.integers.join('|');
  395. packed += '^' + dictionary.floats.join('|');
  396. verbose && console.log('Parsing the structure');
  397. // And add the structure
  398. packed += '^' + (function recursiveParser(item) {
  399. verbose && console.log('Calling a recursiveParser with ' + this.JSON.stringify(item));
  400. // If the item is Array, then is a object of
  401. // type [object Object] or [object Array]
  402. if ( item instanceof Array) {
  403. // The packed resulting
  404. var packed = item.shift();
  405. for (var i in item) {
  406. if (!item.hasOwnProperty(i))
  407. continue;
  408. packed += recursiveParser(item[i]) + '|';
  409. }
  410. return (packed[packed.length - 1] === '|' ? packed.slice(0, -1) : packed) + ']';
  411. }
  412. // A shorthand proxies
  413. var type = item.type, index = item.index;
  414. if (type === 'strings') {
  415. // Just return the base 36 of index
  416. return _base10To36(index);
  417. }
  418. if (type === 'integers') {
  419. // Return a base 36 of index plus stringLength offset
  420. return _base10To36(stringLength + index);
  421. }
  422. if (type === 'floats') {
  423. // Return a base 36 of index plus stringLength and integerLength offset
  424. return _base10To36(stringLength + integerLength + index);
  425. }
  426. if (type === 'boolean') {
  427. return item.index;
  428. }
  429. if (type === 'null') {
  430. return TOKEN_NULL;
  431. }
  432. if (type === 'undefined') {
  433. return TOKEN_UNDEFINED;
  434. }
  435. if (type === 'empty') {
  436. return TOKEN_EMPTY_STRING;
  437. }
  438. throw new TypeError('The item is alien!');
  439. })(ast);
  440. verbose && console.log('Ending parser');
  441. // If debug, return a internal representation of dictionary and stuff
  442. if (options.debug)
  443. return {
  444. dictionary : dictionary,
  445. ast : ast,
  446. packed : packed
  447. };
  448. return packed;
  449. };
  450. var unpack = function(packed, options) {
  451. // Canonizes the options
  452. options = options || {};
  453. // A raw buffer
  454. var rawBuffers = packed.split('^');
  455. // Create a dictionary
  456. options.verbose && console.log('Building dictionary');
  457. var dictionary = [];
  458. // Add the strings values
  459. var buffer = rawBuffers[0];
  460. if (buffer !== '') {
  461. buffer = buffer.split('|');
  462. options.verbose && console.log('Parse the strings dictionary');
  463. for (var i=0, n=buffer.length; i<n; i++){
  464. dictionary.push(_decode(buffer[i]));
  465. }
  466. }
  467. // Add the integers values
  468. buffer = rawBuffers[1];
  469. if (buffer !== '') {
  470. buffer = buffer.split('|');
  471. options.verbose && console.log('Parse the integers dictionary');
  472. for (var i=0, n=buffer.length; i<n; i++){
  473. dictionary.push(_base36To10(buffer[i]));
  474. }
  475. }
  476. // Add the floats values
  477. buffer = rawBuffers[2];
  478. if (buffer !== '') {
  479. buffer = buffer.split('|');
  480. options.verbose && console.log('Parse the floats dictionary');
  481. for (var i=0, n=buffer.length; i<n; i++){
  482. dictionary.push(parseFloat(buffer[i]));
  483. }
  484. }
  485. // Free memory
  486. buffer = null;
  487. options.verbose && console.log('Tokenizing the structure');
  488. // Tokenizer the structure
  489. var number36 = '';
  490. var tokens = [];
  491. var len=rawBuffers[3].length;
  492. for (var i = 0; i < len; i++) {
  493. var symbol = rawBuffers[3].charAt(i);
  494. if (symbol === '|' || symbol === '$' || symbol === '@' || symbol === ']') {
  495. if (number36) {
  496. tokens.push(_base36To10(number36));
  497. number36 = '';
  498. }
  499. symbol !== '|' && tokens.push(symbol);
  500. } else {
  501. number36 += symbol;
  502. }
  503. }
  504. // A shorthand proxy for tokens.length
  505. var tokensLength = tokens.length;
  506. // The index of the next token to read
  507. var tokensIndex = 0;
  508. options.verbose && console.log('Starting recursive parser');
  509. return (function recursiveUnpackerParser() {
  510. // Maybe '$' (object) or '@' (array)
  511. var type = tokens[tokensIndex++];
  512. options.verbose && console.log('Reading collection type ' + (type === '$' ? 'object' : 'Array'));
  513. // Parse an array
  514. if (type === '@') {
  515. var node = [];
  516. for (; tokensIndex < tokensLength; tokensIndex++) {
  517. var value = tokens[tokensIndex];
  518. options.verbose && console.log('Read ' + value + ' symbol');
  519. if (value === ']')
  520. return node;
  521. if (value === '@' || value === '$') {
  522. node.push(recursiveUnpackerParser());
  523. } else {
  524. switch(value) {
  525. case TOKEN_TRUE:
  526. node.push(true);
  527. break;
  528. case TOKEN_FALSE:
  529. node.push(false);
  530. break;
  531. case TOKEN_NULL:
  532. node.push(null);
  533. break;
  534. case TOKEN_UNDEFINED:
  535. node.push(undefined);
  536. break;
  537. case TOKEN_EMPTY_STRING:
  538. node.push('');
  539. break;
  540. default:
  541. node.push(dictionary[value]);
  542. }
  543. }
  544. }
  545. options.verbose && console.log('Parsed ' + this.JSON.stringify(node));
  546. return node;
  547. }
  548. // Parse a object
  549. if (type === '$') {
  550. var node = {};
  551. for (; tokensIndex < tokensLength; tokensIndex++) {
  552. var key = tokens[tokensIndex];
  553. if (key === ']')
  554. return node;
  555. if (key === TOKEN_EMPTY_STRING)
  556. key = '';
  557. else
  558. key = dictionary[key];
  559. var value = tokens[++tokensIndex];
  560. if (value === '@' || value === '$') {
  561. node[key] = recursiveUnpackerParser();
  562. } else {
  563. switch(value) {
  564. case TOKEN_TRUE:
  565. node[key] = true;
  566. break;
  567. case TOKEN_FALSE:
  568. node[key] = false;
  569. break;
  570. case TOKEN_NULL:
  571. node[key] = null;
  572. break;
  573. case TOKEN_UNDEFINED:
  574. node[key] = undefined;
  575. break;
  576. case TOKEN_EMPTY_STRING:
  577. node[key] = '';
  578. break;
  579. default:
  580. node[key] = dictionary[value];
  581. }
  582. }
  583. }
  584. options.verbose && console.log('Parsed ' + this.JSON.stringify(node));
  585. return node;
  586. }
  587. throw new TypeError('Bad token ' + type + ' isn\'t a type');
  588. })();
  589. };
  590. var _encode = function(str) {
  591. if ( typeof str !== 'string')
  592. return str;
  593. return str.replace(/[\+ \|\^\%]/g, function(a) {
  594. return ({
  595. ' ' : '+',
  596. '+' : '%2B',
  597. '|' : '%7C',
  598. '^' : '%5E',
  599. '%' : '%25'
  600. })[a]
  601. });
  602. };
  603. var _decode = function(str) {
  604. if ( typeof str !== 'string')
  605. return str;
  606. return str.replace(/\+|%2B|%7C|%5E|%25/g, function(a) {
  607. return ({
  608. '+' : ' ',
  609. '%2B' : '+',
  610. '%7C' : '|',
  611. '%5E' : '^',
  612. '%25' : '%'
  613. })[a]
  614. })
  615. };
  616. var _base10To36 = function(number) {
  617. return Number.prototype.toString.call(number, 36).toUpperCase();
  618. };
  619. var _base36To10 = function(number) {
  620. return parseInt(number, 36);
  621. };
  622. var _indexOf = Array.prototype.indexOf ||
  623. function(obj, start) {
  624. for (var i = (start || 0), j = this.length; i < j; i++) {
  625. if (this[i] === obj) {
  626. return i;
  627. }
  628. }
  629. return -1;
  630. };
  631. return {
  632. JSON : JSON,
  633. pack : pack,
  634. unpack : unpack
  635. };
  636. });
  637. })( function(deps, factory) {
  638. var jsonpack = factory();
  639. for (var key in jsonpack)
  640. exports[key] = jsonpack[key];
  641. } );
  642. } (main));
  643. /**
  644. * @this {Promise}
  645. */
  646. function finallyConstructor(callback) {
  647. var constructor = this.constructor;
  648. return this.then(
  649. function(value) {
  650. // @ts-ignore
  651. return constructor.resolve(callback()).then(function() {
  652. return value;
  653. });
  654. },
  655. function(reason) {
  656. // @ts-ignore
  657. return constructor.resolve(callback()).then(function() {
  658. // @ts-ignore
  659. return constructor.reject(reason);
  660. });
  661. }
  662. );
  663. }
  664. function allSettled(arr) {
  665. var P = this;
  666. return new P(function(resolve, reject) {
  667. if (!(arr && typeof arr.length !== 'undefined')) {
  668. return reject(
  669. new TypeError(
  670. typeof arr +
  671. ' ' +
  672. arr +
  673. ' is not iterable(cannot read property Symbol(Symbol.iterator))'
  674. )
  675. );
  676. }
  677. var args = Array.prototype.slice.call(arr);
  678. if (args.length === 0) return resolve([]);
  679. var remaining = args.length;
  680. function res(i, val) {
  681. if (val && (typeof val === 'object' || typeof val === 'function')) {
  682. var then = val.then;
  683. if (typeof then === 'function') {
  684. then.call(
  685. val,
  686. function(val) {
  687. res(i, val);
  688. },
  689. function(e) {
  690. args[i] = { status: 'rejected', reason: e };
  691. if (--remaining === 0) {
  692. resolve(args);
  693. }
  694. }
  695. );
  696. return;
  697. }
  698. }
  699. args[i] = { status: 'fulfilled', value: val };
  700. if (--remaining === 0) {
  701. resolve(args);
  702. }
  703. }
  704. for (var i = 0; i < args.length; i++) {
  705. res(i, args[i]);
  706. }
  707. });
  708. }
  709. /**
  710. * @constructor
  711. */
  712. function AggregateError(errors, message) {
  713. (this.name = 'AggregateError'), (this.errors = errors);
  714. this.message = message || '';
  715. }
  716. AggregateError.prototype = Error.prototype;
  717. function any(arr) {
  718. var P = this;
  719. return new P(function(resolve, reject) {
  720. if (!(arr && typeof arr.length !== 'undefined')) {
  721. return reject(new TypeError('Promise.any accepts an array'));
  722. }
  723. var args = Array.prototype.slice.call(arr);
  724. if (args.length === 0) return reject();
  725. var rejectionReasons = [];
  726. for (var i = 0; i < args.length; i++) {
  727. try {
  728. P.resolve(args[i])
  729. .then(resolve)
  730. .catch(function(error) {
  731. rejectionReasons.push(error);
  732. if (rejectionReasons.length === args.length) {
  733. reject(
  734. new AggregateError(
  735. rejectionReasons,
  736. 'All promises were rejected'
  737. )
  738. );
  739. }
  740. });
  741. } catch (ex) {
  742. reject(ex);
  743. }
  744. }
  745. });
  746. }
  747. // Store setTimeout reference so promise-polyfill will be unaffected by
  748. // other code modifying setTimeout (like sinon.useFakeTimers())
  749. var setTimeoutFunc = setTimeout;
  750. function isArray(x) {
  751. return Boolean(x && typeof x.length !== 'undefined');
  752. }
  753. function noop() {}
  754. // Polyfill for Function.prototype.bind
  755. function bind(fn, thisArg) {
  756. return function() {
  757. fn.apply(thisArg, arguments);
  758. };
  759. }
  760. /**
  761. * @constructor
  762. * @param {Function} fn
  763. */
  764. function Promise$1(fn) {
  765. if (!(this instanceof Promise$1))
  766. throw new TypeError('Promises must be constructed via new');
  767. if (typeof fn !== 'function') throw new TypeError('not a function');
  768. /** @type {!number} */
  769. this._state = 0;
  770. /** @type {!boolean} */
  771. this._handled = false;
  772. /** @type {Promise|undefined} */
  773. this._value = undefined;
  774. /** @type {!Array<!Function>} */
  775. this._deferreds = [];
  776. doResolve(fn, this);
  777. }
  778. function handle(self, deferred) {
  779. while (self._state === 3) {
  780. self = self._value;
  781. }
  782. if (self._state === 0) {
  783. self._deferreds.push(deferred);
  784. return;
  785. }
  786. self._handled = true;
  787. Promise$1._immediateFn(function() {
  788. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  789. if (cb === null) {
  790. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  791. return;
  792. }
  793. var ret;
  794. try {
  795. ret = cb(self._value);
  796. } catch (e) {
  797. reject(deferred.promise, e);
  798. return;
  799. }
  800. resolve(deferred.promise, ret);
  801. });
  802. }
  803. function resolve(self, newValue) {
  804. try {
  805. // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  806. if (newValue === self)
  807. throw new TypeError('A promise cannot be resolved with itself.');
  808. if (
  809. newValue &&
  810. (typeof newValue === 'object' || typeof newValue === 'function')
  811. ) {
  812. var then = newValue.then;
  813. if (newValue instanceof Promise$1) {
  814. self._state = 3;
  815. self._value = newValue;
  816. finale(self);
  817. return;
  818. } else if (typeof then === 'function') {
  819. doResolve(bind(then, newValue), self);
  820. return;
  821. }
  822. }
  823. self._state = 1;
  824. self._value = newValue;
  825. finale(self);
  826. } catch (e) {
  827. reject(self, e);
  828. }
  829. }
  830. function reject(self, newValue) {
  831. self._state = 2;
  832. self._value = newValue;
  833. finale(self);
  834. }
  835. function finale(self) {
  836. if (self._state === 2 && self._deferreds.length === 0) {
  837. Promise$1._immediateFn(function() {
  838. if (!self._handled) {
  839. Promise$1._unhandledRejectionFn(self._value);
  840. }
  841. });
  842. }
  843. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  844. handle(self, self._deferreds[i]);
  845. }
  846. self._deferreds = null;
  847. }
  848. /**
  849. * @constructor
  850. */
  851. function Handler(onFulfilled, onRejected, promise) {
  852. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  853. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  854. this.promise = promise;
  855. }
  856. /**
  857. * Take a potentially misbehaving resolver function and make sure
  858. * onFulfilled and onRejected are only called once.
  859. *
  860. * Makes no guarantees about asynchrony.
  861. */
  862. function doResolve(fn, self) {
  863. var done = false;
  864. try {
  865. fn(
  866. function(value) {
  867. if (done) return;
  868. done = true;
  869. resolve(self, value);
  870. },
  871. function(reason) {
  872. if (done) return;
  873. done = true;
  874. reject(self, reason);
  875. }
  876. );
  877. } catch (ex) {
  878. if (done) return;
  879. done = true;
  880. reject(self, ex);
  881. }
  882. }
  883. Promise$1.prototype['catch'] = function(onRejected) {
  884. return this.then(null, onRejected);
  885. };
  886. Promise$1.prototype.then = function(onFulfilled, onRejected) {
  887. // @ts-ignore
  888. var prom = new this.constructor(noop);
  889. handle(this, new Handler(onFulfilled, onRejected, prom));
  890. return prom;
  891. };
  892. Promise$1.prototype['finally'] = finallyConstructor;
  893. Promise$1.all = function(arr) {
  894. return new Promise$1(function(resolve, reject) {
  895. if (!isArray(arr)) {
  896. return reject(new TypeError('Promise.all accepts an array'));
  897. }
  898. var args = Array.prototype.slice.call(arr);
  899. if (args.length === 0) return resolve([]);
  900. var remaining = args.length;
  901. function res(i, val) {
  902. try {
  903. if (val && (typeof val === 'object' || typeof val === 'function')) {
  904. var then = val.then;
  905. if (typeof then === 'function') {
  906. then.call(
  907. val,
  908. function(val) {
  909. res(i, val);
  910. },
  911. reject
  912. );
  913. return;
  914. }
  915. }
  916. args[i] = val;
  917. if (--remaining === 0) {
  918. resolve(args);
  919. }
  920. } catch (ex) {
  921. reject(ex);
  922. }
  923. }
  924. for (var i = 0; i < args.length; i++) {
  925. res(i, args[i]);
  926. }
  927. });
  928. };
  929. Promise$1.any = any;
  930. Promise$1.allSettled = allSettled;
  931. Promise$1.resolve = function(value) {
  932. if (value && typeof value === 'object' && value.constructor === Promise$1) {
  933. return value;
  934. }
  935. return new Promise$1(function(resolve) {
  936. resolve(value);
  937. });
  938. };
  939. Promise$1.reject = function(value) {
  940. return new Promise$1(function(resolve, reject) {
  941. reject(value);
  942. });
  943. };
  944. Promise$1.race = function(arr) {
  945. return new Promise$1(function(resolve, reject) {
  946. if (!isArray(arr)) {
  947. return reject(new TypeError('Promise.race accepts an array'));
  948. }
  949. for (var i = 0, len = arr.length; i < len; i++) {
  950. Promise$1.resolve(arr[i]).then(resolve, reject);
  951. }
  952. });
  953. };
  954. // Use polyfill for setImmediate for performance gains
  955. Promise$1._immediateFn =
  956. // @ts-ignore
  957. (typeof setImmediate === 'function' &&
  958. function(fn) {
  959. // @ts-ignore
  960. setImmediate(fn);
  961. }) ||
  962. function(fn) {
  963. setTimeoutFunc(fn, 0);
  964. };
  965. Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  966. if (typeof console !== 'undefined' && console) {
  967. console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  968. }
  969. };
  970. /** @suppress {undefinedVars} */
  971. var globalNS = (function() {
  972. // the only reliable means to get the global object is
  973. // `Function('return this')()`
  974. // However, this causes CSP violations in Chrome apps.
  975. if (typeof self !== 'undefined') {
  976. return self;
  977. }
  978. if (typeof window !== 'undefined') {
  979. return window;
  980. }
  981. if (typeof global !== 'undefined') {
  982. return global;
  983. }
  984. throw new Error('unable to locate global object');
  985. })();
  986. // Expose the polyfill if Promise is undefined or set to a
  987. // non-function value. The latter can be due to a named HTMLElement
  988. // being exposed by browsers for legacy reasons.
  989. // https://github.com/taylorhakes/promise-polyfill/issues/114
  990. if (typeof globalNS['Promise'] !== 'function') {
  991. globalNS['Promise'] = Promise$1;
  992. } else {
  993. if (!globalNS.Promise.prototype['finally']) {
  994. globalNS.Promise.prototype['finally'] = finallyConstructor;
  995. }
  996. if (!globalNS.Promise.allSettled) {
  997. globalNS.Promise.allSettled = allSettled;
  998. }
  999. if (!globalNS.Promise.any) {
  1000. globalNS.Promise.any = any;
  1001. }
  1002. }
  1003. function sortObject(obj) {
  1004. if (typeof obj !== 'object') {
  1005. return obj;
  1006. }
  1007. var temp = {};
  1008. var keys = [];
  1009. for (var key in obj) {
  1010. keys.push(key);
  1011. }
  1012. keys.sort();
  1013. for (var index in keys) {
  1014. temp[keys[index]] = sortObject(obj[keys[index]]);
  1015. }
  1016. return temp;
  1017. }
  1018. function copyTextToClipboard(text) {
  1019. var textArea = document.createElement('textarea');
  1020. textArea.value = text;
  1021. document.body.appendChild(textArea);
  1022. textArea.select();
  1023. try {
  1024. var successful = document.execCommand('copy');
  1025. var msg = successful ? 'successful' : 'unsuccessful';
  1026. console.log('Copying text command was ' + msg);
  1027. } catch (err) {
  1028. console.log('Oops, unable to copy');
  1029. }
  1030. document.body.removeChild(textArea);
  1031. }
  1032. function _toPrimitive(t, r) {
  1033. if ("object" != typeof t || !t) return t;
  1034. var e = t[Symbol.toPrimitive];
  1035. if (void 0 !== e) {
  1036. var i = e.call(t, r || "default");
  1037. if ("object" != typeof i) return i;
  1038. throw new TypeError("@@toPrimitive must return a primitive value.");
  1039. }
  1040. return ("string" === r ? String : Number)(t);
  1041. }
  1042. function _toPropertyKey(t) {
  1043. var i = _toPrimitive(t, "string");
  1044. return "symbol" == typeof i ? i : String(i);
  1045. }
  1046. function _defineProperties(target, props) {
  1047. for (var i = 0; i < props.length; i++) {
  1048. var descriptor = props[i];
  1049. descriptor.enumerable = descriptor.enumerable || false;
  1050. descriptor.configurable = true;
  1051. if ("value" in descriptor) descriptor.writable = true;
  1052. Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
  1053. }
  1054. }
  1055. function _createClass(Constructor, protoProps, staticProps) {
  1056. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  1057. if (staticProps) _defineProperties(Constructor, staticProps);
  1058. Object.defineProperty(Constructor, "prototype", {
  1059. writable: false
  1060. });
  1061. return Constructor;
  1062. }
  1063. function _extends() {
  1064. _extends = Object.assign ? Object.assign.bind() : function (target) {
  1065. for (var i = 1; i < arguments.length; i++) {
  1066. var source = arguments[i];
  1067. for (var key in source) {
  1068. if (Object.prototype.hasOwnProperty.call(source, key)) {
  1069. target[key] = source[key];
  1070. }
  1071. }
  1072. }
  1073. return target;
  1074. };
  1075. return _extends.apply(this, arguments);
  1076. }
  1077. var Chart$1 = {exports: {}};
  1078. function commonjsRequire(path) {
  1079. throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  1080. }
  1081. var moment = {exports: {}};
  1082. var hasRequiredMoment;
  1083. function requireMoment () {
  1084. if (hasRequiredMoment) return moment.exports;
  1085. hasRequiredMoment = 1;
  1086. (function (module, exports) {
  1087. (function (global, factory) {
  1088. module.exports = factory() ;
  1089. }(commonjsGlobal, (function () {
  1090. var hookCallback;
  1091. function hooks() {
  1092. return hookCallback.apply(null, arguments);
  1093. }
  1094. // This is done to register the method called with moment()
  1095. // without creating circular dependencies.
  1096. function setHookCallback(callback) {
  1097. hookCallback = callback;
  1098. }
  1099. function isArray(input) {
  1100. return (
  1101. input instanceof Array ||
  1102. Object.prototype.toString.call(input) === '[object Array]'
  1103. );
  1104. }
  1105. function isObject(input) {
  1106. // IE8 will treat undefined and null as object if it wasn't for
  1107. // input != null
  1108. return (
  1109. input != null &&
  1110. Object.prototype.toString.call(input) === '[object Object]'
  1111. );
  1112. }
  1113. function hasOwnProp(a, b) {
  1114. return Object.prototype.hasOwnProperty.call(a, b);
  1115. }
  1116. function isObjectEmpty(obj) {
  1117. if (Object.getOwnPropertyNames) {
  1118. return Object.getOwnPropertyNames(obj).length === 0;
  1119. } else {
  1120. var k;
  1121. for (k in obj) {
  1122. if (hasOwnProp(obj, k)) {
  1123. return false;
  1124. }
  1125. }
  1126. return true;
  1127. }
  1128. }
  1129. function isUndefined(input) {
  1130. return input === void 0;
  1131. }
  1132. function isNumber(input) {
  1133. return (
  1134. typeof input === 'number' ||
  1135. Object.prototype.toString.call(input) === '[object Number]'
  1136. );
  1137. }
  1138. function isDate(input) {
  1139. return (
  1140. input instanceof Date ||
  1141. Object.prototype.toString.call(input) === '[object Date]'
  1142. );
  1143. }
  1144. function map(arr, fn) {
  1145. var res = [],
  1146. i,
  1147. arrLen = arr.length;
  1148. for (i = 0; i < arrLen; ++i) {
  1149. res.push(fn(arr[i], i));
  1150. }
  1151. return res;
  1152. }
  1153. function extend(a, b) {
  1154. for (var i in b) {
  1155. if (hasOwnProp(b, i)) {
  1156. a[i] = b[i];
  1157. }
  1158. }
  1159. if (hasOwnProp(b, 'toString')) {
  1160. a.toString = b.toString;
  1161. }
  1162. if (hasOwnProp(b, 'valueOf')) {
  1163. a.valueOf = b.valueOf;
  1164. }
  1165. return a;
  1166. }
  1167. function createUTC(input, format, locale, strict) {
  1168. return createLocalOrUTC(input, format, locale, strict, true).utc();
  1169. }
  1170. function defaultParsingFlags() {
  1171. // We need to deep clone this object.
  1172. return {
  1173. empty: false,
  1174. unusedTokens: [],
  1175. unusedInput: [],
  1176. overflow: -2,
  1177. charsLeftOver: 0,
  1178. nullInput: false,
  1179. invalidEra: null,
  1180. invalidMonth: null,
  1181. invalidFormat: false,
  1182. userInvalidated: false,
  1183. iso: false,
  1184. parsedDateParts: [],
  1185. era: null,
  1186. meridiem: null,
  1187. rfc2822: false,
  1188. weekdayMismatch: false,
  1189. };
  1190. }
  1191. function getParsingFlags(m) {
  1192. if (m._pf == null) {
  1193. m._pf = defaultParsingFlags();
  1194. }
  1195. return m._pf;
  1196. }
  1197. var some;
  1198. if (Array.prototype.some) {
  1199. some = Array.prototype.some;
  1200. } else {
  1201. some = function (fun) {
  1202. var t = Object(this),
  1203. len = t.length >>> 0,
  1204. i;
  1205. for (i = 0; i < len; i++) {
  1206. if (i in t && fun.call(this, t[i], i, t)) {
  1207. return true;
  1208. }
  1209. }
  1210. return false;
  1211. };
  1212. }
  1213. function isValid(m) {
  1214. if (m._isValid == null) {
  1215. var flags = getParsingFlags(m),
  1216. parsedParts = some.call(flags.parsedDateParts, function (i) {
  1217. return i != null;
  1218. }),
  1219. isNowValid =
  1220. !isNaN(m._d.getTime()) &&
  1221. flags.overflow < 0 &&
  1222. !flags.empty &&
  1223. !flags.invalidEra &&
  1224. !flags.invalidMonth &&
  1225. !flags.invalidWeekday &&
  1226. !flags.weekdayMismatch &&
  1227. !flags.nullInput &&
  1228. !flags.invalidFormat &&
  1229. !flags.userInvalidated &&
  1230. (!flags.meridiem || (flags.meridiem && parsedParts));
  1231. if (m._strict) {
  1232. isNowValid =
  1233. isNowValid &&
  1234. flags.charsLeftOver === 0 &&
  1235. flags.unusedTokens.length === 0 &&
  1236. flags.bigHour === undefined;
  1237. }
  1238. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  1239. m._isValid = isNowValid;
  1240. } else {
  1241. return isNowValid;
  1242. }
  1243. }
  1244. return m._isValid;
  1245. }
  1246. function createInvalid(flags) {
  1247. var m = createUTC(NaN);
  1248. if (flags != null) {
  1249. extend(getParsingFlags(m), flags);
  1250. } else {
  1251. getParsingFlags(m).userInvalidated = true;
  1252. }
  1253. return m;
  1254. }
  1255. // Plugins that add properties should also add the key here (null value),
  1256. // so we can properly clone ourselves.
  1257. var momentProperties = (hooks.momentProperties = []),
  1258. updateInProgress = false;
  1259. function copyConfig(to, from) {
  1260. var i,
  1261. prop,
  1262. val,
  1263. momentPropertiesLen = momentProperties.length;
  1264. if (!isUndefined(from._isAMomentObject)) {
  1265. to._isAMomentObject = from._isAMomentObject;
  1266. }
  1267. if (!isUndefined(from._i)) {
  1268. to._i = from._i;
  1269. }
  1270. if (!isUndefined(from._f)) {
  1271. to._f = from._f;
  1272. }
  1273. if (!isUndefined(from._l)) {
  1274. to._l = from._l;
  1275. }
  1276. if (!isUndefined(from._strict)) {
  1277. to._strict = from._strict;
  1278. }
  1279. if (!isUndefined(from._tzm)) {
  1280. to._tzm = from._tzm;
  1281. }
  1282. if (!isUndefined(from._isUTC)) {
  1283. to._isUTC = from._isUTC;
  1284. }
  1285. if (!isUndefined(from._offset)) {
  1286. to._offset = from._offset;
  1287. }
  1288. if (!isUndefined(from._pf)) {
  1289. to._pf = getParsingFlags(from);
  1290. }
  1291. if (!isUndefined(from._locale)) {
  1292. to._locale = from._locale;
  1293. }
  1294. if (momentPropertiesLen > 0) {
  1295. for (i = 0; i < momentPropertiesLen; i++) {
  1296. prop = momentProperties[i];
  1297. val = from[prop];
  1298. if (!isUndefined(val)) {
  1299. to[prop] = val;
  1300. }
  1301. }
  1302. }
  1303. return to;
  1304. }
  1305. // Moment prototype object
  1306. function Moment(config) {
  1307. copyConfig(this, config);
  1308. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  1309. if (!this.isValid()) {
  1310. this._d = new Date(NaN);
  1311. }
  1312. // Prevent infinite loop in case updateOffset creates new moment
  1313. // objects.
  1314. if (updateInProgress === false) {
  1315. updateInProgress = true;
  1316. hooks.updateOffset(this);
  1317. updateInProgress = false;
  1318. }
  1319. }
  1320. function isMoment(obj) {
  1321. return (
  1322. obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
  1323. );
  1324. }
  1325. function warn(msg) {
  1326. if (
  1327. hooks.suppressDeprecationWarnings === false &&
  1328. typeof console !== 'undefined' &&
  1329. console.warn
  1330. ) {
  1331. console.warn('Deprecation warning: ' + msg);
  1332. }
  1333. }
  1334. function deprecate(msg, fn) {
  1335. var firstTime = true;
  1336. return extend(function () {
  1337. if (hooks.deprecationHandler != null) {
  1338. hooks.deprecationHandler(null, msg);
  1339. }
  1340. if (firstTime) {
  1341. var args = [],
  1342. arg,
  1343. i,
  1344. key,
  1345. argLen = arguments.length;
  1346. for (i = 0; i < argLen; i++) {
  1347. arg = '';
  1348. if (typeof arguments[i] === 'object') {
  1349. arg += '\n[' + i + '] ';
  1350. for (key in arguments[0]) {
  1351. if (hasOwnProp(arguments[0], key)) {
  1352. arg += key + ': ' + arguments[0][key] + ', ';
  1353. }
  1354. }
  1355. arg = arg.slice(0, -2); // Remove trailing comma and space
  1356. } else {
  1357. arg = arguments[i];
  1358. }
  1359. args.push(arg);
  1360. }
  1361. warn(
  1362. msg +
  1363. '\nArguments: ' +
  1364. Array.prototype.slice.call(args).join('') +
  1365. '\n' +
  1366. new Error().stack
  1367. );
  1368. firstTime = false;
  1369. }
  1370. return fn.apply(this, arguments);
  1371. }, fn);
  1372. }
  1373. var deprecations = {};
  1374. function deprecateSimple(name, msg) {
  1375. if (hooks.deprecationHandler != null) {
  1376. hooks.deprecationHandler(name, msg);
  1377. }
  1378. if (!deprecations[name]) {
  1379. warn(msg);
  1380. deprecations[name] = true;
  1381. }
  1382. }
  1383. hooks.suppressDeprecationWarnings = false;
  1384. hooks.deprecationHandler = null;
  1385. function isFunction(input) {
  1386. return (
  1387. (typeof Function !== 'undefined' && input instanceof Function) ||
  1388. Object.prototype.toString.call(input) === '[object Function]'
  1389. );
  1390. }
  1391. function set(config) {
  1392. var prop, i;
  1393. for (i in config) {
  1394. if (hasOwnProp(config, i)) {
  1395. prop = config[i];
  1396. if (isFunction(prop)) {
  1397. this[i] = prop;
  1398. } else {
  1399. this['_' + i] = prop;
  1400. }
  1401. }
  1402. }
  1403. this._config = config;
  1404. // Lenient ordinal parsing accepts just a number in addition to
  1405. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  1406. // TODO: Remove "ordinalParse" fallback in next major release.
  1407. this._dayOfMonthOrdinalParseLenient = new RegExp(
  1408. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  1409. '|' +
  1410. /\d{1,2}/.source
  1411. );
  1412. }
  1413. function mergeConfigs(parentConfig, childConfig) {
  1414. var res = extend({}, parentConfig),
  1415. prop;
  1416. for (prop in childConfig) {
  1417. if (hasOwnProp(childConfig, prop)) {
  1418. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  1419. res[prop] = {};
  1420. extend(res[prop], parentConfig[prop]);
  1421. extend(res[prop], childConfig[prop]);
  1422. } else if (childConfig[prop] != null) {
  1423. res[prop] = childConfig[prop];
  1424. } else {
  1425. delete res[prop];
  1426. }
  1427. }
  1428. }
  1429. for (prop in parentConfig) {
  1430. if (
  1431. hasOwnProp(parentConfig, prop) &&
  1432. !hasOwnProp(childConfig, prop) &&
  1433. isObject(parentConfig[prop])
  1434. ) {
  1435. // make sure changes to properties don't modify parent config
  1436. res[prop] = extend({}, res[prop]);
  1437. }
  1438. }
  1439. return res;
  1440. }
  1441. function Locale(config) {
  1442. if (config != null) {
  1443. this.set(config);
  1444. }
  1445. }
  1446. var keys;
  1447. if (Object.keys) {
  1448. keys = Object.keys;
  1449. } else {
  1450. keys = function (obj) {
  1451. var i,
  1452. res = [];
  1453. for (i in obj) {
  1454. if (hasOwnProp(obj, i)) {
  1455. res.push(i);
  1456. }
  1457. }
  1458. return res;
  1459. };
  1460. }
  1461. var defaultCalendar = {
  1462. sameDay: '[Today at] LT',
  1463. nextDay: '[Tomorrow at] LT',
  1464. nextWeek: 'dddd [at] LT',
  1465. lastDay: '[Yesterday at] LT',
  1466. lastWeek: '[Last] dddd [at] LT',
  1467. sameElse: 'L',
  1468. };
  1469. function calendar(key, mom, now) {
  1470. var output = this._calendar[key] || this._calendar['sameElse'];
  1471. return isFunction(output) ? output.call(mom, now) : output;
  1472. }
  1473. function zeroFill(number, targetLength, forceSign) {
  1474. var absNumber = '' + Math.abs(number),
  1475. zerosToFill = targetLength - absNumber.length,
  1476. sign = number >= 0;
  1477. return (
  1478. (sign ? (forceSign ? '+' : '') : '-') +
  1479. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
  1480. absNumber
  1481. );
  1482. }
  1483. var formattingTokens =
  1484. /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,
  1485. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
  1486. formatFunctions = {},
  1487. formatTokenFunctions = {};
  1488. // token: 'M'
  1489. // padded: ['MM', 2]
  1490. // ordinal: 'Mo'
  1491. // callback: function () { this.month() + 1 }
  1492. function addFormatToken(token, padded, ordinal, callback) {
  1493. var func = callback;
  1494. if (typeof callback === 'string') {
  1495. func = function () {
  1496. return this[callback]();
  1497. };
  1498. }
  1499. if (token) {
  1500. formatTokenFunctions[token] = func;
  1501. }
  1502. if (padded) {
  1503. formatTokenFunctions[padded[0]] = function () {
  1504. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  1505. };
  1506. }
  1507. if (ordinal) {
  1508. formatTokenFunctions[ordinal] = function () {
  1509. return this.localeData().ordinal(
  1510. func.apply(this, arguments),
  1511. token
  1512. );
  1513. };
  1514. }
  1515. }
  1516. function removeFormattingTokens(input) {
  1517. if (input.match(/\[[\s\S]/)) {
  1518. return input.replace(/^\[|\]$/g, '');
  1519. }
  1520. return input.replace(/\\/g, '');
  1521. }
  1522. function makeFormatFunction(format) {
  1523. var array = format.match(formattingTokens),
  1524. i,
  1525. length;
  1526. for (i = 0, length = array.length; i < length; i++) {
  1527. if (formatTokenFunctions[array[i]]) {
  1528. array[i] = formatTokenFunctions[array[i]];
  1529. } else {
  1530. array[i] = removeFormattingTokens(array[i]);
  1531. }
  1532. }
  1533. return function (mom) {
  1534. var output = '',
  1535. i;
  1536. for (i = 0; i < length; i++) {
  1537. output += isFunction(array[i])
  1538. ? array[i].call(mom, format)
  1539. : array[i];
  1540. }
  1541. return output;
  1542. };
  1543. }
  1544. // format date using native date object
  1545. function formatMoment(m, format) {
  1546. if (!m.isValid()) {
  1547. return m.localeData().invalidDate();
  1548. }
  1549. format = expandFormat(format, m.localeData());
  1550. formatFunctions[format] =
  1551. formatFunctions[format] || makeFormatFunction(format);
  1552. return formatFunctions[format](m);
  1553. }
  1554. function expandFormat(format, locale) {
  1555. var i = 5;
  1556. function replaceLongDateFormatTokens(input) {
  1557. return locale.longDateFormat(input) || input;
  1558. }
  1559. localFormattingTokens.lastIndex = 0;
  1560. while (i >= 0 && localFormattingTokens.test(format)) {
  1561. format = format.replace(
  1562. localFormattingTokens,
  1563. replaceLongDateFormatTokens
  1564. );
  1565. localFormattingTokens.lastIndex = 0;
  1566. i -= 1;
  1567. }
  1568. return format;
  1569. }
  1570. var defaultLongDateFormat = {
  1571. LTS: 'h:mm:ss A',
  1572. LT: 'h:mm A',
  1573. L: 'MM/DD/YYYY',
  1574. LL: 'MMMM D, YYYY',
  1575. LLL: 'MMMM D, YYYY h:mm A',
  1576. LLLL: 'dddd, MMMM D, YYYY h:mm A',
  1577. };
  1578. function longDateFormat(key) {
  1579. var format = this._longDateFormat[key],
  1580. formatUpper = this._longDateFormat[key.toUpperCase()];
  1581. if (format || !formatUpper) {
  1582. return format;
  1583. }
  1584. this._longDateFormat[key] = formatUpper
  1585. .match(formattingTokens)
  1586. .map(function (tok) {
  1587. if (
  1588. tok === 'MMMM' ||
  1589. tok === 'MM' ||
  1590. tok === 'DD' ||
  1591. tok === 'dddd'
  1592. ) {
  1593. return tok.slice(1);
  1594. }
  1595. return tok;
  1596. })
  1597. .join('');
  1598. return this._longDateFormat[key];
  1599. }
  1600. var defaultInvalidDate = 'Invalid date';
  1601. function invalidDate() {
  1602. return this._invalidDate;
  1603. }
  1604. var defaultOrdinal = '%d',
  1605. defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  1606. function ordinal(number) {
  1607. return this._ordinal.replace('%d', number);
  1608. }
  1609. var defaultRelativeTime = {
  1610. future: 'in %s',
  1611. past: '%s ago',
  1612. s: 'a few seconds',
  1613. ss: '%d seconds',
  1614. m: 'a minute',
  1615. mm: '%d minutes',
  1616. h: 'an hour',
  1617. hh: '%d hours',
  1618. d: 'a day',
  1619. dd: '%d days',
  1620. w: 'a week',
  1621. ww: '%d weeks',
  1622. M: 'a month',
  1623. MM: '%d months',
  1624. y: 'a year',
  1625. yy: '%d years',
  1626. };
  1627. function relativeTime(number, withoutSuffix, string, isFuture) {
  1628. var output = this._relativeTime[string];
  1629. return isFunction(output)
  1630. ? output(number, withoutSuffix, string, isFuture)
  1631. : output.replace(/%d/i, number);
  1632. }
  1633. function pastFuture(diff, output) {
  1634. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  1635. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  1636. }
  1637. var aliases = {};
  1638. function addUnitAlias(unit, shorthand) {
  1639. var lowerCase = unit.toLowerCase();
  1640. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  1641. }
  1642. function normalizeUnits(units) {
  1643. return typeof units === 'string'
  1644. ? aliases[units] || aliases[units.toLowerCase()]
  1645. : undefined;
  1646. }
  1647. function normalizeObjectUnits(inputObject) {
  1648. var normalizedInput = {},
  1649. normalizedProp,
  1650. prop;
  1651. for (prop in inputObject) {
  1652. if (hasOwnProp(inputObject, prop)) {
  1653. normalizedProp = normalizeUnits(prop);
  1654. if (normalizedProp) {
  1655. normalizedInput[normalizedProp] = inputObject[prop];
  1656. }
  1657. }
  1658. }
  1659. return normalizedInput;
  1660. }
  1661. var priorities = {};
  1662. function addUnitPriority(unit, priority) {
  1663. priorities[unit] = priority;
  1664. }
  1665. function getPrioritizedUnits(unitsObj) {
  1666. var units = [],
  1667. u;
  1668. for (u in unitsObj) {
  1669. if (hasOwnProp(unitsObj, u)) {
  1670. units.push({ unit: u, priority: priorities[u] });
  1671. }
  1672. }
  1673. units.sort(function (a, b) {
  1674. return a.priority - b.priority;
  1675. });
  1676. return units;
  1677. }
  1678. function isLeapYear(year) {
  1679. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  1680. }
  1681. function absFloor(number) {
  1682. if (number < 0) {
  1683. // -0 -> 0
  1684. return Math.ceil(number) || 0;
  1685. } else {
  1686. return Math.floor(number);
  1687. }
  1688. }
  1689. function toInt(argumentForCoercion) {
  1690. var coercedNumber = +argumentForCoercion,
  1691. value = 0;
  1692. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  1693. value = absFloor(coercedNumber);
  1694. }
  1695. return value;
  1696. }
  1697. function makeGetSet(unit, keepTime) {
  1698. return function (value) {
  1699. if (value != null) {
  1700. set$1(this, unit, value);
  1701. hooks.updateOffset(this, keepTime);
  1702. return this;
  1703. } else {
  1704. return get(this, unit);
  1705. }
  1706. };
  1707. }
  1708. function get(mom, unit) {
  1709. return mom.isValid()
  1710. ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
  1711. : NaN;
  1712. }
  1713. function set$1(mom, unit, value) {
  1714. if (mom.isValid() && !isNaN(value)) {
  1715. if (
  1716. unit === 'FullYear' &&
  1717. isLeapYear(mom.year()) &&
  1718. mom.month() === 1 &&
  1719. mom.date() === 29
  1720. ) {
  1721. value = toInt(value);
  1722. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
  1723. value,
  1724. mom.month(),
  1725. daysInMonth(value, mom.month())
  1726. );
  1727. } else {
  1728. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  1729. }
  1730. }
  1731. }
  1732. // MOMENTS
  1733. function stringGet(units) {
  1734. units = normalizeUnits(units);
  1735. if (isFunction(this[units])) {
  1736. return this[units]();
  1737. }
  1738. return this;
  1739. }
  1740. function stringSet(units, value) {
  1741. if (typeof units === 'object') {
  1742. units = normalizeObjectUnits(units);
  1743. var prioritized = getPrioritizedUnits(units),
  1744. i,
  1745. prioritizedLen = prioritized.length;
  1746. for (i = 0; i < prioritizedLen; i++) {
  1747. this[prioritized[i].unit](units[prioritized[i].unit]);
  1748. }
  1749. } else {
  1750. units = normalizeUnits(units);
  1751. if (isFunction(this[units])) {
  1752. return this[units](value);
  1753. }
  1754. }
  1755. return this;
  1756. }
  1757. var match1 = /\d/, // 0 - 9
  1758. match2 = /\d\d/, // 00 - 99
  1759. match3 = /\d{3}/, // 000 - 999
  1760. match4 = /\d{4}/, // 0000 - 9999
  1761. match6 = /[+-]?\d{6}/, // -999999 - 999999
  1762. match1to2 = /\d\d?/, // 0 - 99
  1763. match3to4 = /\d\d\d\d?/, // 999 - 9999
  1764. match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
  1765. match1to3 = /\d{1,3}/, // 0 - 999
  1766. match1to4 = /\d{1,4}/, // 0 - 9999
  1767. match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
  1768. matchUnsigned = /\d+/, // 0 - inf
  1769. matchSigned = /[+-]?\d+/, // -inf - inf
  1770. matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  1771. matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  1772. matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  1773. // any word (or two) characters or numbers including two/three word month in arabic.
  1774. // includes scottish gaelic two word and hyphenated months
  1775. matchWord =
  1776. /[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,
  1777. regexes;
  1778. regexes = {};
  1779. function addRegexToken(token, regex, strictRegex) {
  1780. regexes[token] = isFunction(regex)
  1781. ? regex
  1782. : function (isStrict, localeData) {
  1783. return isStrict && strictRegex ? strictRegex : regex;
  1784. };
  1785. }
  1786. function getParseRegexForToken(token, config) {
  1787. if (!hasOwnProp(regexes, token)) {
  1788. return new RegExp(unescapeFormat(token));
  1789. }
  1790. return regexes[token](config._strict, config._locale);
  1791. }
  1792. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  1793. function unescapeFormat(s) {
  1794. return regexEscape(
  1795. s
  1796. .replace('\\', '')
  1797. .replace(
  1798. /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,
  1799. function (matched, p1, p2, p3, p4) {
  1800. return p1 || p2 || p3 || p4;
  1801. }
  1802. )
  1803. );
  1804. }
  1805. function regexEscape(s) {
  1806. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  1807. }
  1808. var tokens = {};
  1809. function addParseToken(token, callback) {
  1810. var i,
  1811. func = callback,
  1812. tokenLen;
  1813. if (typeof token === 'string') {
  1814. token = [token];
  1815. }
  1816. if (isNumber(callback)) {
  1817. func = function (input, array) {
  1818. array[callback] = toInt(input);
  1819. };
  1820. }
  1821. tokenLen = token.length;
  1822. for (i = 0; i < tokenLen; i++) {
  1823. tokens[token[i]] = func;
  1824. }
  1825. }
  1826. function addWeekParseToken(token, callback) {
  1827. addParseToken(token, function (input, array, config, token) {
  1828. config._w = config._w || {};
  1829. callback(input, config._w, config, token);
  1830. });
  1831. }
  1832. function addTimeToArrayFromToken(token, input, config) {
  1833. if (input != null && hasOwnProp(tokens, token)) {
  1834. tokens[token](input, config._a, config, token);
  1835. }
  1836. }
  1837. var YEAR = 0,
  1838. MONTH = 1,
  1839. DATE = 2,
  1840. HOUR = 3,
  1841. MINUTE = 4,
  1842. SECOND = 5,
  1843. MILLISECOND = 6,
  1844. WEEK = 7,
  1845. WEEKDAY = 8;
  1846. function mod(n, x) {
  1847. return ((n % x) + x) % x;
  1848. }
  1849. var indexOf;
  1850. if (Array.prototype.indexOf) {
  1851. indexOf = Array.prototype.indexOf;
  1852. } else {
  1853. indexOf = function (o) {
  1854. // I know
  1855. var i;
  1856. for (i = 0; i < this.length; ++i) {
  1857. if (this[i] === o) {
  1858. return i;
  1859. }
  1860. }
  1861. return -1;
  1862. };
  1863. }
  1864. function daysInMonth(year, month) {
  1865. if (isNaN(year) || isNaN(month)) {
  1866. return NaN;
  1867. }
  1868. var modMonth = mod(month, 12);
  1869. year += (month - modMonth) / 12;
  1870. return modMonth === 1
  1871. ? isLeapYear(year)
  1872. ? 29
  1873. : 28
  1874. : 31 - ((modMonth % 7) % 2);
  1875. }
  1876. // FORMATTING
  1877. addFormatToken('M', ['MM', 2], 'Mo', function () {
  1878. return this.month() + 1;
  1879. });
  1880. addFormatToken('MMM', 0, 0, function (format) {
  1881. return this.localeData().monthsShort(this, format);
  1882. });
  1883. addFormatToken('MMMM', 0, 0, function (format) {
  1884. return this.localeData().months(this, format);
  1885. });
  1886. // ALIASES
  1887. addUnitAlias('month', 'M');
  1888. // PRIORITY
  1889. addUnitPriority('month', 8);
  1890. // PARSING
  1891. addRegexToken('M', match1to2);
  1892. addRegexToken('MM', match1to2, match2);
  1893. addRegexToken('MMM', function (isStrict, locale) {
  1894. return locale.monthsShortRegex(isStrict);
  1895. });
  1896. addRegexToken('MMMM', function (isStrict, locale) {
  1897. return locale.monthsRegex(isStrict);
  1898. });
  1899. addParseToken(['M', 'MM'], function (input, array) {
  1900. array[MONTH] = toInt(input) - 1;
  1901. });
  1902. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  1903. var month = config._locale.monthsParse(input, token, config._strict);
  1904. // if we didn't find a month name, mark the date as invalid.
  1905. if (month != null) {
  1906. array[MONTH] = month;
  1907. } else {
  1908. getParsingFlags(config).invalidMonth = input;
  1909. }
  1910. });
  1911. // LOCALES
  1912. var defaultLocaleMonths =
  1913. 'January_February_March_April_May_June_July_August_September_October_November_December'.split(
  1914. '_'
  1915. ),
  1916. defaultLocaleMonthsShort =
  1917. 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
  1918. MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
  1919. defaultMonthsShortRegex = matchWord,
  1920. defaultMonthsRegex = matchWord;
  1921. function localeMonths(m, format) {
  1922. if (!m) {
  1923. return isArray(this._months)
  1924. ? this._months
  1925. : this._months['standalone'];
  1926. }
  1927. return isArray(this._months)
  1928. ? this._months[m.month()]
  1929. : this._months[
  1930. (this._months.isFormat || MONTHS_IN_FORMAT).test(format)
  1931. ? 'format'
  1932. : 'standalone'
  1933. ][m.month()];
  1934. }
  1935. function localeMonthsShort(m, format) {
  1936. if (!m) {
  1937. return isArray(this._monthsShort)
  1938. ? this._monthsShort
  1939. : this._monthsShort['standalone'];
  1940. }
  1941. return isArray(this._monthsShort)
  1942. ? this._monthsShort[m.month()]
  1943. : this._monthsShort[
  1944. MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
  1945. ][m.month()];
  1946. }
  1947. function handleStrictParse(monthName, format, strict) {
  1948. var i,
  1949. ii,
  1950. mom,
  1951. llc = monthName.toLocaleLowerCase();
  1952. if (!this._monthsParse) {
  1953. // this is not used
  1954. this._monthsParse = [];
  1955. this._longMonthsParse = [];
  1956. this._shortMonthsParse = [];
  1957. for (i = 0; i < 12; ++i) {
  1958. mom = createUTC([2000, i]);
  1959. this._shortMonthsParse[i] = this.monthsShort(
  1960. mom,
  1961. ''
  1962. ).toLocaleLowerCase();
  1963. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  1964. }
  1965. }
  1966. if (strict) {
  1967. if (format === 'MMM') {
  1968. ii = indexOf.call(this._shortMonthsParse, llc);
  1969. return ii !== -1 ? ii : null;
  1970. } else {
  1971. ii = indexOf.call(this._longMonthsParse, llc);
  1972. return ii !== -1 ? ii : null;
  1973. }
  1974. } else {
  1975. if (format === 'MMM') {
  1976. ii = indexOf.call(this._shortMonthsParse, llc);
  1977. if (ii !== -1) {
  1978. return ii;
  1979. }
  1980. ii = indexOf.call(this._longMonthsParse, llc);
  1981. return ii !== -1 ? ii : null;
  1982. } else {
  1983. ii = indexOf.call(this._longMonthsParse, llc);
  1984. if (ii !== -1) {
  1985. return ii;
  1986. }
  1987. ii = indexOf.call(this._shortMonthsParse, llc);
  1988. return ii !== -1 ? ii : null;
  1989. }
  1990. }
  1991. }
  1992. function localeMonthsParse(monthName, format, strict) {
  1993. var i, mom, regex;
  1994. if (this._monthsParseExact) {
  1995. return handleStrictParse.call(this, monthName, format, strict);
  1996. }
  1997. if (!this._monthsParse) {
  1998. this._monthsParse = [];
  1999. this._longMonthsParse = [];
  2000. this._shortMonthsParse = [];
  2001. }
  2002. // TODO: add sorting
  2003. // Sorting makes sure if one month (or abbr) is a prefix of another
  2004. // see sorting in computeMonthsParse
  2005. for (i = 0; i < 12; i++) {
  2006. // make the regex if we don't have it already
  2007. mom = createUTC([2000, i]);
  2008. if (strict && !this._longMonthsParse[i]) {
  2009. this._longMonthsParse[i] = new RegExp(
  2010. '^' + this.months(mom, '').replace('.', '') + '$',
  2011. 'i'
  2012. );
  2013. this._shortMonthsParse[i] = new RegExp(
  2014. '^' + this.monthsShort(mom, '').replace('.', '') + '$',
  2015. 'i'
  2016. );
  2017. }
  2018. if (!strict && !this._monthsParse[i]) {
  2019. regex =
  2020. '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  2021. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  2022. }
  2023. // test the regex
  2024. if (
  2025. strict &&
  2026. format === 'MMMM' &&
  2027. this._longMonthsParse[i].test(monthName)
  2028. ) {
  2029. return i;
  2030. } else if (
  2031. strict &&
  2032. format === 'MMM' &&
  2033. this._shortMonthsParse[i].test(monthName)
  2034. ) {
  2035. return i;
  2036. } else if (!strict && this._monthsParse[i].test(monthName)) {
  2037. return i;
  2038. }
  2039. }
  2040. }
  2041. // MOMENTS
  2042. function setMonth(mom, value) {
  2043. var dayOfMonth;
  2044. if (!mom.isValid()) {
  2045. // No op
  2046. return mom;
  2047. }
  2048. if (typeof value === 'string') {
  2049. if (/^\d+$/.test(value)) {
  2050. value = toInt(value);
  2051. } else {
  2052. value = mom.localeData().monthsParse(value);
  2053. // TODO: Another silent failure?
  2054. if (!isNumber(value)) {
  2055. return mom;
  2056. }
  2057. }
  2058. }
  2059. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  2060. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  2061. return mom;
  2062. }
  2063. function getSetMonth(value) {
  2064. if (value != null) {
  2065. setMonth(this, value);
  2066. hooks.updateOffset(this, true);
  2067. return this;
  2068. } else {
  2069. return get(this, 'Month');
  2070. }
  2071. }
  2072. function getDaysInMonth() {
  2073. return daysInMonth(this.year(), this.month());
  2074. }
  2075. function monthsShortRegex(isStrict) {
  2076. if (this._monthsParseExact) {
  2077. if (!hasOwnProp(this, '_monthsRegex')) {
  2078. computeMonthsParse.call(this);
  2079. }
  2080. if (isStrict) {
  2081. return this._monthsShortStrictRegex;
  2082. } else {
  2083. return this._monthsShortRegex;
  2084. }
  2085. } else {
  2086. if (!hasOwnProp(this, '_monthsShortRegex')) {
  2087. this._monthsShortRegex = defaultMonthsShortRegex;
  2088. }
  2089. return this._monthsShortStrictRegex && isStrict
  2090. ? this._monthsShortStrictRegex
  2091. : this._monthsShortRegex;
  2092. }
  2093. }
  2094. function monthsRegex(isStrict) {
  2095. if (this._monthsParseExact) {
  2096. if (!hasOwnProp(this, '_monthsRegex')) {
  2097. computeMonthsParse.call(this);
  2098. }
  2099. if (isStrict) {
  2100. return this._monthsStrictRegex;
  2101. } else {
  2102. return this._monthsRegex;
  2103. }
  2104. } else {
  2105. if (!hasOwnProp(this, '_monthsRegex')) {
  2106. this._monthsRegex = defaultMonthsRegex;
  2107. }
  2108. return this._monthsStrictRegex && isStrict
  2109. ? this._monthsStrictRegex
  2110. : this._monthsRegex;
  2111. }
  2112. }
  2113. function computeMonthsParse() {
  2114. function cmpLenRev(a, b) {
  2115. return b.length - a.length;
  2116. }
  2117. var shortPieces = [],
  2118. longPieces = [],
  2119. mixedPieces = [],
  2120. i,
  2121. mom;
  2122. for (i = 0; i < 12; i++) {
  2123. // make the regex if we don't have it already
  2124. mom = createUTC([2000, i]);
  2125. shortPieces.push(this.monthsShort(mom, ''));
  2126. longPieces.push(this.months(mom, ''));
  2127. mixedPieces.push(this.months(mom, ''));
  2128. mixedPieces.push(this.monthsShort(mom, ''));
  2129. }
  2130. // Sorting makes sure if one month (or abbr) is a prefix of another it
  2131. // will match the longer piece.
  2132. shortPieces.sort(cmpLenRev);
  2133. longPieces.sort(cmpLenRev);
  2134. mixedPieces.sort(cmpLenRev);
  2135. for (i = 0; i < 12; i++) {
  2136. shortPieces[i] = regexEscape(shortPieces[i]);
  2137. longPieces[i] = regexEscape(longPieces[i]);
  2138. }
  2139. for (i = 0; i < 24; i++) {
  2140. mixedPieces[i] = regexEscape(mixedPieces[i]);
  2141. }
  2142. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  2143. this._monthsShortRegex = this._monthsRegex;
  2144. this._monthsStrictRegex = new RegExp(
  2145. '^(' + longPieces.join('|') + ')',
  2146. 'i'
  2147. );
  2148. this._monthsShortStrictRegex = new RegExp(
  2149. '^(' + shortPieces.join('|') + ')',
  2150. 'i'
  2151. );
  2152. }
  2153. // FORMATTING
  2154. addFormatToken('Y', 0, 0, function () {
  2155. var y = this.year();
  2156. return y <= 9999 ? zeroFill(y, 4) : '+' + y;
  2157. });
  2158. addFormatToken(0, ['YY', 2], 0, function () {
  2159. return this.year() % 100;
  2160. });
  2161. addFormatToken(0, ['YYYY', 4], 0, 'year');
  2162. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  2163. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  2164. // ALIASES
  2165. addUnitAlias('year', 'y');
  2166. // PRIORITIES
  2167. addUnitPriority('year', 1);
  2168. // PARSING
  2169. addRegexToken('Y', matchSigned);
  2170. addRegexToken('YY', match1to2, match2);
  2171. addRegexToken('YYYY', match1to4, match4);
  2172. addRegexToken('YYYYY', match1to6, match6);
  2173. addRegexToken('YYYYYY', match1to6, match6);
  2174. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  2175. addParseToken('YYYY', function (input, array) {
  2176. array[YEAR] =
  2177. input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  2178. });
  2179. addParseToken('YY', function (input, array) {
  2180. array[YEAR] = hooks.parseTwoDigitYear(input);
  2181. });
  2182. addParseToken('Y', function (input, array) {
  2183. array[YEAR] = parseInt(input, 10);
  2184. });
  2185. // HELPERS
  2186. function daysInYear(year) {
  2187. return isLeapYear(year) ? 366 : 365;
  2188. }
  2189. // HOOKS
  2190. hooks.parseTwoDigitYear = function (input) {
  2191. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  2192. };
  2193. // MOMENTS
  2194. var getSetYear = makeGetSet('FullYear', true);
  2195. function getIsLeapYear() {
  2196. return isLeapYear(this.year());
  2197. }
  2198. function createDate(y, m, d, h, M, s, ms) {
  2199. // can't just apply() to create a date:
  2200. // https://stackoverflow.com/q/181348
  2201. var date;
  2202. // the date constructor remaps years 0-99 to 1900-1999
  2203. if (y < 100 && y >= 0) {
  2204. // preserve leap years using a full 400 year cycle, then reset
  2205. date = new Date(y + 400, m, d, h, M, s, ms);
  2206. if (isFinite(date.getFullYear())) {
  2207. date.setFullYear(y);
  2208. }
  2209. } else {
  2210. date = new Date(y, m, d, h, M, s, ms);
  2211. }
  2212. return date;
  2213. }
  2214. function createUTCDate(y) {
  2215. var date, args;
  2216. // the Date.UTC function remaps years 0-99 to 1900-1999
  2217. if (y < 100 && y >= 0) {
  2218. args = Array.prototype.slice.call(arguments);
  2219. // preserve leap years using a full 400 year cycle, then reset
  2220. args[0] = y + 400;
  2221. date = new Date(Date.UTC.apply(null, args));
  2222. if (isFinite(date.getUTCFullYear())) {
  2223. date.setUTCFullYear(y);
  2224. }
  2225. } else {
  2226. date = new Date(Date.UTC.apply(null, arguments));
  2227. }
  2228. return date;
  2229. }
  2230. // start-of-first-week - start-of-year
  2231. function firstWeekOffset(year, dow, doy) {
  2232. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  2233. fwd = 7 + dow - doy,
  2234. // first-week day local weekday -- which local weekday is fwd
  2235. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  2236. return -fwdlw + fwd - 1;
  2237. }
  2238. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  2239. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  2240. var localWeekday = (7 + weekday - dow) % 7,
  2241. weekOffset = firstWeekOffset(year, dow, doy),
  2242. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  2243. resYear,
  2244. resDayOfYear;
  2245. if (dayOfYear <= 0) {
  2246. resYear = year - 1;
  2247. resDayOfYear = daysInYear(resYear) + dayOfYear;
  2248. } else if (dayOfYear > daysInYear(year)) {
  2249. resYear = year + 1;
  2250. resDayOfYear = dayOfYear - daysInYear(year);
  2251. } else {
  2252. resYear = year;
  2253. resDayOfYear = dayOfYear;
  2254. }
  2255. return {
  2256. year: resYear,
  2257. dayOfYear: resDayOfYear,
  2258. };
  2259. }
  2260. function weekOfYear(mom, dow, doy) {
  2261. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  2262. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  2263. resWeek,
  2264. resYear;
  2265. if (week < 1) {
  2266. resYear = mom.year() - 1;
  2267. resWeek = week + weeksInYear(resYear, dow, doy);
  2268. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  2269. resWeek = week - weeksInYear(mom.year(), dow, doy);
  2270. resYear = mom.year() + 1;
  2271. } else {
  2272. resYear = mom.year();
  2273. resWeek = week;
  2274. }
  2275. return {
  2276. week: resWeek,
  2277. year: resYear,
  2278. };
  2279. }
  2280. function weeksInYear(year, dow, doy) {
  2281. var weekOffset = firstWeekOffset(year, dow, doy),
  2282. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  2283. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  2284. }
  2285. // FORMATTING
  2286. addFormatToken('w', ['ww', 2], 'wo', 'week');
  2287. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  2288. // ALIASES
  2289. addUnitAlias('week', 'w');
  2290. addUnitAlias('isoWeek', 'W');
  2291. // PRIORITIES
  2292. addUnitPriority('week', 5);
  2293. addUnitPriority('isoWeek', 5);
  2294. // PARSING
  2295. addRegexToken('w', match1to2);
  2296. addRegexToken('ww', match1to2, match2);
  2297. addRegexToken('W', match1to2);
  2298. addRegexToken('WW', match1to2, match2);
  2299. addWeekParseToken(
  2300. ['w', 'ww', 'W', 'WW'],
  2301. function (input, week, config, token) {
  2302. week[token.substr(0, 1)] = toInt(input);
  2303. }
  2304. );
  2305. // HELPERS
  2306. // LOCALES
  2307. function localeWeek(mom) {
  2308. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  2309. }
  2310. var defaultLocaleWeek = {
  2311. dow: 0, // Sunday is the first day of the week.
  2312. doy: 6, // The week that contains Jan 6th is the first week of the year.
  2313. };
  2314. function localeFirstDayOfWeek() {
  2315. return this._week.dow;
  2316. }
  2317. function localeFirstDayOfYear() {
  2318. return this._week.doy;
  2319. }
  2320. // MOMENTS
  2321. function getSetWeek(input) {
  2322. var week = this.localeData().week(this);
  2323. return input == null ? week : this.add((input - week) * 7, 'd');
  2324. }
  2325. function getSetISOWeek(input) {
  2326. var week = weekOfYear(this, 1, 4).week;
  2327. return input == null ? week : this.add((input - week) * 7, 'd');
  2328. }
  2329. // FORMATTING
  2330. addFormatToken('d', 0, 'do', 'day');
  2331. addFormatToken('dd', 0, 0, function (format) {
  2332. return this.localeData().weekdaysMin(this, format);
  2333. });
  2334. addFormatToken('ddd', 0, 0, function (format) {
  2335. return this.localeData().weekdaysShort(this, format);
  2336. });
  2337. addFormatToken('dddd', 0, 0, function (format) {
  2338. return this.localeData().weekdays(this, format);
  2339. });
  2340. addFormatToken('e', 0, 0, 'weekday');
  2341. addFormatToken('E', 0, 0, 'isoWeekday');
  2342. // ALIASES
  2343. addUnitAlias('day', 'd');
  2344. addUnitAlias('weekday', 'e');
  2345. addUnitAlias('isoWeekday', 'E');
  2346. // PRIORITY
  2347. addUnitPriority('day', 11);
  2348. addUnitPriority('weekday', 11);
  2349. addUnitPriority('isoWeekday', 11);
  2350. // PARSING
  2351. addRegexToken('d', match1to2);
  2352. addRegexToken('e', match1to2);
  2353. addRegexToken('E', match1to2);
  2354. addRegexToken('dd', function (isStrict, locale) {
  2355. return locale.weekdaysMinRegex(isStrict);
  2356. });
  2357. addRegexToken('ddd', function (isStrict, locale) {
  2358. return locale.weekdaysShortRegex(isStrict);
  2359. });
  2360. addRegexToken('dddd', function (isStrict, locale) {
  2361. return locale.weekdaysRegex(isStrict);
  2362. });
  2363. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  2364. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  2365. // if we didn't get a weekday name, mark the date as invalid
  2366. if (weekday != null) {
  2367. week.d = weekday;
  2368. } else {
  2369. getParsingFlags(config).invalidWeekday = input;
  2370. }
  2371. });
  2372. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  2373. week[token] = toInt(input);
  2374. });
  2375. // HELPERS
  2376. function parseWeekday(input, locale) {
  2377. if (typeof input !== 'string') {
  2378. return input;
  2379. }
  2380. if (!isNaN(input)) {
  2381. return parseInt(input, 10);
  2382. }
  2383. input = locale.weekdaysParse(input);
  2384. if (typeof input === 'number') {
  2385. return input;
  2386. }
  2387. return null;
  2388. }
  2389. function parseIsoWeekday(input, locale) {
  2390. if (typeof input === 'string') {
  2391. return locale.weekdaysParse(input) % 7 || 7;
  2392. }
  2393. return isNaN(input) ? null : input;
  2394. }
  2395. // LOCALES
  2396. function shiftWeekdays(ws, n) {
  2397. return ws.slice(n, 7).concat(ws.slice(0, n));
  2398. }
  2399. var defaultLocaleWeekdays =
  2400. 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
  2401. defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  2402. defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  2403. defaultWeekdaysRegex = matchWord,
  2404. defaultWeekdaysShortRegex = matchWord,
  2405. defaultWeekdaysMinRegex = matchWord;
  2406. function localeWeekdays(m, format) {
  2407. var weekdays = isArray(this._weekdays)
  2408. ? this._weekdays
  2409. : this._weekdays[
  2410. m && m !== true && this._weekdays.isFormat.test(format)
  2411. ? 'format'
  2412. : 'standalone'
  2413. ];
  2414. return m === true
  2415. ? shiftWeekdays(weekdays, this._week.dow)
  2416. : m
  2417. ? weekdays[m.day()]
  2418. : weekdays;
  2419. }
  2420. function localeWeekdaysShort(m) {
  2421. return m === true
  2422. ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  2423. : m
  2424. ? this._weekdaysShort[m.day()]
  2425. : this._weekdaysShort;
  2426. }
  2427. function localeWeekdaysMin(m) {
  2428. return m === true
  2429. ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  2430. : m
  2431. ? this._weekdaysMin[m.day()]
  2432. : this._weekdaysMin;
  2433. }
  2434. function handleStrictParse$1(weekdayName, format, strict) {
  2435. var i,
  2436. ii,
  2437. mom,
  2438. llc = weekdayName.toLocaleLowerCase();
  2439. if (!this._weekdaysParse) {
  2440. this._weekdaysParse = [];
  2441. this._shortWeekdaysParse = [];
  2442. this._minWeekdaysParse = [];
  2443. for (i = 0; i < 7; ++i) {
  2444. mom = createUTC([2000, 1]).day(i);
  2445. this._minWeekdaysParse[i] = this.weekdaysMin(
  2446. mom,
  2447. ''
  2448. ).toLocaleLowerCase();
  2449. this._shortWeekdaysParse[i] = this.weekdaysShort(
  2450. mom,
  2451. ''
  2452. ).toLocaleLowerCase();
  2453. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  2454. }
  2455. }
  2456. if (strict) {
  2457. if (format === 'dddd') {
  2458. ii = indexOf.call(this._weekdaysParse, llc);
  2459. return ii !== -1 ? ii : null;
  2460. } else if (format === 'ddd') {
  2461. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2462. return ii !== -1 ? ii : null;
  2463. } else {
  2464. ii = indexOf.call(this._minWeekdaysParse, llc);
  2465. return ii !== -1 ? ii : null;
  2466. }
  2467. } else {
  2468. if (format === 'dddd') {
  2469. ii = indexOf.call(this._weekdaysParse, llc);
  2470. if (ii !== -1) {
  2471. return ii;
  2472. }
  2473. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2474. if (ii !== -1) {
  2475. return ii;
  2476. }
  2477. ii = indexOf.call(this._minWeekdaysParse, llc);
  2478. return ii !== -1 ? ii : null;
  2479. } else if (format === 'ddd') {
  2480. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2481. if (ii !== -1) {
  2482. return ii;
  2483. }
  2484. ii = indexOf.call(this._weekdaysParse, llc);
  2485. if (ii !== -1) {
  2486. return ii;
  2487. }
  2488. ii = indexOf.call(this._minWeekdaysParse, llc);
  2489. return ii !== -1 ? ii : null;
  2490. } else {
  2491. ii = indexOf.call(this._minWeekdaysParse, llc);
  2492. if (ii !== -1) {
  2493. return ii;
  2494. }
  2495. ii = indexOf.call(this._weekdaysParse, llc);
  2496. if (ii !== -1) {
  2497. return ii;
  2498. }
  2499. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2500. return ii !== -1 ? ii : null;
  2501. }
  2502. }
  2503. }
  2504. function localeWeekdaysParse(weekdayName, format, strict) {
  2505. var i, mom, regex;
  2506. if (this._weekdaysParseExact) {
  2507. return handleStrictParse$1.call(this, weekdayName, format, strict);
  2508. }
  2509. if (!this._weekdaysParse) {
  2510. this._weekdaysParse = [];
  2511. this._minWeekdaysParse = [];
  2512. this._shortWeekdaysParse = [];
  2513. this._fullWeekdaysParse = [];
  2514. }
  2515. for (i = 0; i < 7; i++) {
  2516. // make the regex if we don't have it already
  2517. mom = createUTC([2000, 1]).day(i);
  2518. if (strict && !this._fullWeekdaysParse[i]) {
  2519. this._fullWeekdaysParse[i] = new RegExp(
  2520. '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
  2521. 'i'
  2522. );
  2523. this._shortWeekdaysParse[i] = new RegExp(
  2524. '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
  2525. 'i'
  2526. );
  2527. this._minWeekdaysParse[i] = new RegExp(
  2528. '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
  2529. 'i'
  2530. );
  2531. }
  2532. if (!this._weekdaysParse[i]) {
  2533. regex =
  2534. '^' +
  2535. this.weekdays(mom, '') +
  2536. '|^' +
  2537. this.weekdaysShort(mom, '') +
  2538. '|^' +
  2539. this.weekdaysMin(mom, '');
  2540. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  2541. }
  2542. // test the regex
  2543. if (
  2544. strict &&
  2545. format === 'dddd' &&
  2546. this._fullWeekdaysParse[i].test(weekdayName)
  2547. ) {
  2548. return i;
  2549. } else if (
  2550. strict &&
  2551. format === 'ddd' &&
  2552. this._shortWeekdaysParse[i].test(weekdayName)
  2553. ) {
  2554. return i;
  2555. } else if (
  2556. strict &&
  2557. format === 'dd' &&
  2558. this._minWeekdaysParse[i].test(weekdayName)
  2559. ) {
  2560. return i;
  2561. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  2562. return i;
  2563. }
  2564. }
  2565. }
  2566. // MOMENTS
  2567. function getSetDayOfWeek(input) {
  2568. if (!this.isValid()) {
  2569. return input != null ? this : NaN;
  2570. }
  2571. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  2572. if (input != null) {
  2573. input = parseWeekday(input, this.localeData());
  2574. return this.add(input - day, 'd');
  2575. } else {
  2576. return day;
  2577. }
  2578. }
  2579. function getSetLocaleDayOfWeek(input) {
  2580. if (!this.isValid()) {
  2581. return input != null ? this : NaN;
  2582. }
  2583. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  2584. return input == null ? weekday : this.add(input - weekday, 'd');
  2585. }
  2586. function getSetISODayOfWeek(input) {
  2587. if (!this.isValid()) {
  2588. return input != null ? this : NaN;
  2589. }
  2590. // behaves the same as moment#day except
  2591. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  2592. // as a setter, sunday should belong to the previous week.
  2593. if (input != null) {
  2594. var weekday = parseIsoWeekday(input, this.localeData());
  2595. return this.day(this.day() % 7 ? weekday : weekday - 7);
  2596. } else {
  2597. return this.day() || 7;
  2598. }
  2599. }
  2600. function weekdaysRegex(isStrict) {
  2601. if (this._weekdaysParseExact) {
  2602. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2603. computeWeekdaysParse.call(this);
  2604. }
  2605. if (isStrict) {
  2606. return this._weekdaysStrictRegex;
  2607. } else {
  2608. return this._weekdaysRegex;
  2609. }
  2610. } else {
  2611. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2612. this._weekdaysRegex = defaultWeekdaysRegex;
  2613. }
  2614. return this._weekdaysStrictRegex && isStrict
  2615. ? this._weekdaysStrictRegex
  2616. : this._weekdaysRegex;
  2617. }
  2618. }
  2619. function weekdaysShortRegex(isStrict) {
  2620. if (this._weekdaysParseExact) {
  2621. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2622. computeWeekdaysParse.call(this);
  2623. }
  2624. if (isStrict) {
  2625. return this._weekdaysShortStrictRegex;
  2626. } else {
  2627. return this._weekdaysShortRegex;
  2628. }
  2629. } else {
  2630. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  2631. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  2632. }
  2633. return this._weekdaysShortStrictRegex && isStrict
  2634. ? this._weekdaysShortStrictRegex
  2635. : this._weekdaysShortRegex;
  2636. }
  2637. }
  2638. function weekdaysMinRegex(isStrict) {
  2639. if (this._weekdaysParseExact) {
  2640. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2641. computeWeekdaysParse.call(this);
  2642. }
  2643. if (isStrict) {
  2644. return this._weekdaysMinStrictRegex;
  2645. } else {
  2646. return this._weekdaysMinRegex;
  2647. }
  2648. } else {
  2649. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  2650. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  2651. }
  2652. return this._weekdaysMinStrictRegex && isStrict
  2653. ? this._weekdaysMinStrictRegex
  2654. : this._weekdaysMinRegex;
  2655. }
  2656. }
  2657. function computeWeekdaysParse() {
  2658. function cmpLenRev(a, b) {
  2659. return b.length - a.length;
  2660. }
  2661. var minPieces = [],
  2662. shortPieces = [],
  2663. longPieces = [],
  2664. mixedPieces = [],
  2665. i,
  2666. mom,
  2667. minp,
  2668. shortp,
  2669. longp;
  2670. for (i = 0; i < 7; i++) {
  2671. // make the regex if we don't have it already
  2672. mom = createUTC([2000, 1]).day(i);
  2673. minp = regexEscape(this.weekdaysMin(mom, ''));
  2674. shortp = regexEscape(this.weekdaysShort(mom, ''));
  2675. longp = regexEscape(this.weekdays(mom, ''));
  2676. minPieces.push(minp);
  2677. shortPieces.push(shortp);
  2678. longPieces.push(longp);
  2679. mixedPieces.push(minp);
  2680. mixedPieces.push(shortp);
  2681. mixedPieces.push(longp);
  2682. }
  2683. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  2684. // will match the longer piece.
  2685. minPieces.sort(cmpLenRev);
  2686. shortPieces.sort(cmpLenRev);
  2687. longPieces.sort(cmpLenRev);
  2688. mixedPieces.sort(cmpLenRev);
  2689. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  2690. this._weekdaysShortRegex = this._weekdaysRegex;
  2691. this._weekdaysMinRegex = this._weekdaysRegex;
  2692. this._weekdaysStrictRegex = new RegExp(
  2693. '^(' + longPieces.join('|') + ')',
  2694. 'i'
  2695. );
  2696. this._weekdaysShortStrictRegex = new RegExp(
  2697. '^(' + shortPieces.join('|') + ')',
  2698. 'i'
  2699. );
  2700. this._weekdaysMinStrictRegex = new RegExp(
  2701. '^(' + minPieces.join('|') + ')',
  2702. 'i'
  2703. );
  2704. }
  2705. // FORMATTING
  2706. function hFormat() {
  2707. return this.hours() % 12 || 12;
  2708. }
  2709. function kFormat() {
  2710. return this.hours() || 24;
  2711. }
  2712. addFormatToken('H', ['HH', 2], 0, 'hour');
  2713. addFormatToken('h', ['hh', 2], 0, hFormat);
  2714. addFormatToken('k', ['kk', 2], 0, kFormat);
  2715. addFormatToken('hmm', 0, 0, function () {
  2716. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  2717. });
  2718. addFormatToken('hmmss', 0, 0, function () {
  2719. return (
  2720. '' +
  2721. hFormat.apply(this) +
  2722. zeroFill(this.minutes(), 2) +
  2723. zeroFill(this.seconds(), 2)
  2724. );
  2725. });
  2726. addFormatToken('Hmm', 0, 0, function () {
  2727. return '' + this.hours() + zeroFill(this.minutes(), 2);
  2728. });
  2729. addFormatToken('Hmmss', 0, 0, function () {
  2730. return (
  2731. '' +
  2732. this.hours() +
  2733. zeroFill(this.minutes(), 2) +
  2734. zeroFill(this.seconds(), 2)
  2735. );
  2736. });
  2737. function meridiem(token, lowercase) {
  2738. addFormatToken(token, 0, 0, function () {
  2739. return this.localeData().meridiem(
  2740. this.hours(),
  2741. this.minutes(),
  2742. lowercase
  2743. );
  2744. });
  2745. }
  2746. meridiem('a', true);
  2747. meridiem('A', false);
  2748. // ALIASES
  2749. addUnitAlias('hour', 'h');
  2750. // PRIORITY
  2751. addUnitPriority('hour', 13);
  2752. // PARSING
  2753. function matchMeridiem(isStrict, locale) {
  2754. return locale._meridiemParse;
  2755. }
  2756. addRegexToken('a', matchMeridiem);
  2757. addRegexToken('A', matchMeridiem);
  2758. addRegexToken('H', match1to2);
  2759. addRegexToken('h', match1to2);
  2760. addRegexToken('k', match1to2);
  2761. addRegexToken('HH', match1to2, match2);
  2762. addRegexToken('hh', match1to2, match2);
  2763. addRegexToken('kk', match1to2, match2);
  2764. addRegexToken('hmm', match3to4);
  2765. addRegexToken('hmmss', match5to6);
  2766. addRegexToken('Hmm', match3to4);
  2767. addRegexToken('Hmmss', match5to6);
  2768. addParseToken(['H', 'HH'], HOUR);
  2769. addParseToken(['k', 'kk'], function (input, array, config) {
  2770. var kInput = toInt(input);
  2771. array[HOUR] = kInput === 24 ? 0 : kInput;
  2772. });
  2773. addParseToken(['a', 'A'], function (input, array, config) {
  2774. config._isPm = config._locale.isPM(input);
  2775. config._meridiem = input;
  2776. });
  2777. addParseToken(['h', 'hh'], function (input, array, config) {
  2778. array[HOUR] = toInt(input);
  2779. getParsingFlags(config).bigHour = true;
  2780. });
  2781. addParseToken('hmm', function (input, array, config) {
  2782. var pos = input.length - 2;
  2783. array[HOUR] = toInt(input.substr(0, pos));
  2784. array[MINUTE] = toInt(input.substr(pos));
  2785. getParsingFlags(config).bigHour = true;
  2786. });
  2787. addParseToken('hmmss', function (input, array, config) {
  2788. var pos1 = input.length - 4,
  2789. pos2 = input.length - 2;
  2790. array[HOUR] = toInt(input.substr(0, pos1));
  2791. array[MINUTE] = toInt(input.substr(pos1, 2));
  2792. array[SECOND] = toInt(input.substr(pos2));
  2793. getParsingFlags(config).bigHour = true;
  2794. });
  2795. addParseToken('Hmm', function (input, array, config) {
  2796. var pos = input.length - 2;
  2797. array[HOUR] = toInt(input.substr(0, pos));
  2798. array[MINUTE] = toInt(input.substr(pos));
  2799. });
  2800. addParseToken('Hmmss', function (input, array, config) {
  2801. var pos1 = input.length - 4,
  2802. pos2 = input.length - 2;
  2803. array[HOUR] = toInt(input.substr(0, pos1));
  2804. array[MINUTE] = toInt(input.substr(pos1, 2));
  2805. array[SECOND] = toInt(input.substr(pos2));
  2806. });
  2807. // LOCALES
  2808. function localeIsPM(input) {
  2809. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  2810. // Using charAt should be more compatible.
  2811. return (input + '').toLowerCase().charAt(0) === 'p';
  2812. }
  2813. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
  2814. // Setting the hour should keep the time, because the user explicitly
  2815. // specified which hour they want. So trying to maintain the same hour (in
  2816. // a new timezone) makes sense. Adding/subtracting hours does not follow
  2817. // this rule.
  2818. getSetHour = makeGetSet('Hours', true);
  2819. function localeMeridiem(hours, minutes, isLower) {
  2820. if (hours > 11) {
  2821. return isLower ? 'pm' : 'PM';
  2822. } else {
  2823. return isLower ? 'am' : 'AM';
  2824. }
  2825. }
  2826. var baseConfig = {
  2827. calendar: defaultCalendar,
  2828. longDateFormat: defaultLongDateFormat,
  2829. invalidDate: defaultInvalidDate,
  2830. ordinal: defaultOrdinal,
  2831. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  2832. relativeTime: defaultRelativeTime,
  2833. months: defaultLocaleMonths,
  2834. monthsShort: defaultLocaleMonthsShort,
  2835. week: defaultLocaleWeek,
  2836. weekdays: defaultLocaleWeekdays,
  2837. weekdaysMin: defaultLocaleWeekdaysMin,
  2838. weekdaysShort: defaultLocaleWeekdaysShort,
  2839. meridiemParse: defaultLocaleMeridiemParse,
  2840. };
  2841. // internal storage for locale config files
  2842. var locales = {},
  2843. localeFamilies = {},
  2844. globalLocale;
  2845. function commonPrefix(arr1, arr2) {
  2846. var i,
  2847. minl = Math.min(arr1.length, arr2.length);
  2848. for (i = 0; i < minl; i += 1) {
  2849. if (arr1[i] !== arr2[i]) {
  2850. return i;
  2851. }
  2852. }
  2853. return minl;
  2854. }
  2855. function normalizeLocale(key) {
  2856. return key ? key.toLowerCase().replace('_', '-') : key;
  2857. }
  2858. // pick the locale from the array
  2859. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  2860. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  2861. function chooseLocale(names) {
  2862. var i = 0,
  2863. j,
  2864. next,
  2865. locale,
  2866. split;
  2867. while (i < names.length) {
  2868. split = normalizeLocale(names[i]).split('-');
  2869. j = split.length;
  2870. next = normalizeLocale(names[i + 1]);
  2871. next = next ? next.split('-') : null;
  2872. while (j > 0) {
  2873. locale = loadLocale(split.slice(0, j).join('-'));
  2874. if (locale) {
  2875. return locale;
  2876. }
  2877. if (
  2878. next &&
  2879. next.length >= j &&
  2880. commonPrefix(split, next) >= j - 1
  2881. ) {
  2882. //the next array item is better than a shallower substring of this one
  2883. break;
  2884. }
  2885. j--;
  2886. }
  2887. i++;
  2888. }
  2889. return globalLocale;
  2890. }
  2891. function isLocaleNameSane(name) {
  2892. // Prevent names that look like filesystem paths, i.e contain '/' or '\'
  2893. return name.match('^[^/\\\\]*$') != null;
  2894. }
  2895. function loadLocale(name) {
  2896. var oldLocale = null,
  2897. aliasedRequire;
  2898. // TODO: Find a better way to register and load all the locales in Node
  2899. if (
  2900. locales[name] === undefined &&
  2901. 'object' !== 'undefined' &&
  2902. module &&
  2903. module.exports &&
  2904. isLocaleNameSane(name)
  2905. ) {
  2906. try {
  2907. oldLocale = globalLocale._abbr;
  2908. aliasedRequire = commonjsRequire;
  2909. aliasedRequire('./locale/' + name);
  2910. getSetGlobalLocale(oldLocale);
  2911. } catch (e) {
  2912. // mark as not found to avoid repeating expensive file require call causing high CPU
  2913. // when trying to find en-US, en_US, en-us for every format call
  2914. locales[name] = null; // null means not found
  2915. }
  2916. }
  2917. return locales[name];
  2918. }
  2919. // This function will load locale and then set the global locale. If
  2920. // no arguments are passed in, it will simply return the current global
  2921. // locale key.
  2922. function getSetGlobalLocale(key, values) {
  2923. var data;
  2924. if (key) {
  2925. if (isUndefined(values)) {
  2926. data = getLocale(key);
  2927. } else {
  2928. data = defineLocale(key, values);
  2929. }
  2930. if (data) {
  2931. // moment.duration._locale = moment._locale = data;
  2932. globalLocale = data;
  2933. } else {
  2934. if (typeof console !== 'undefined' && console.warn) {
  2935. //warn user if arguments are passed but the locale could not be set
  2936. console.warn(
  2937. 'Locale ' + key + ' not found. Did you forget to load it?'
  2938. );
  2939. }
  2940. }
  2941. }
  2942. return globalLocale._abbr;
  2943. }
  2944. function defineLocale(name, config) {
  2945. if (config !== null) {
  2946. var locale,
  2947. parentConfig = baseConfig;
  2948. config.abbr = name;
  2949. if (locales[name] != null) {
  2950. deprecateSimple(
  2951. 'defineLocaleOverride',
  2952. 'use moment.updateLocale(localeName, config) to change ' +
  2953. 'an existing locale. moment.defineLocale(localeName, ' +
  2954. 'config) should only be used for creating a new locale ' +
  2955. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
  2956. );
  2957. parentConfig = locales[name]._config;
  2958. } else if (config.parentLocale != null) {
  2959. if (locales[config.parentLocale] != null) {
  2960. parentConfig = locales[config.parentLocale]._config;
  2961. } else {
  2962. locale = loadLocale(config.parentLocale);
  2963. if (locale != null) {
  2964. parentConfig = locale._config;
  2965. } else {
  2966. if (!localeFamilies[config.parentLocale]) {
  2967. localeFamilies[config.parentLocale] = [];
  2968. }
  2969. localeFamilies[config.parentLocale].push({
  2970. name: name,
  2971. config: config,
  2972. });
  2973. return null;
  2974. }
  2975. }
  2976. }
  2977. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  2978. if (localeFamilies[name]) {
  2979. localeFamilies[name].forEach(function (x) {
  2980. defineLocale(x.name, x.config);
  2981. });
  2982. }
  2983. // backwards compat for now: also set the locale
  2984. // make sure we set the locale AFTER all child locales have been
  2985. // created, so we won't end up with the child locale set.
  2986. getSetGlobalLocale(name);
  2987. return locales[name];
  2988. } else {
  2989. // useful for testing
  2990. delete locales[name];
  2991. return null;
  2992. }
  2993. }
  2994. function updateLocale(name, config) {
  2995. if (config != null) {
  2996. var locale,
  2997. tmpLocale,
  2998. parentConfig = baseConfig;
  2999. if (locales[name] != null && locales[name].parentLocale != null) {
  3000. // Update existing child locale in-place to avoid memory-leaks
  3001. locales[name].set(mergeConfigs(locales[name]._config, config));
  3002. } else {
  3003. // MERGE
  3004. tmpLocale = loadLocale(name);
  3005. if (tmpLocale != null) {
  3006. parentConfig = tmpLocale._config;
  3007. }
  3008. config = mergeConfigs(parentConfig, config);
  3009. if (tmpLocale == null) {
  3010. // updateLocale is called for creating a new locale
  3011. // Set abbr so it will have a name (getters return
  3012. // undefined otherwise).
  3013. config.abbr = name;
  3014. }
  3015. locale = new Locale(config);
  3016. locale.parentLocale = locales[name];
  3017. locales[name] = locale;
  3018. }
  3019. // backwards compat for now: also set the locale
  3020. getSetGlobalLocale(name);
  3021. } else {
  3022. // pass null for config to unupdate, useful for tests
  3023. if (locales[name] != null) {
  3024. if (locales[name].parentLocale != null) {
  3025. locales[name] = locales[name].parentLocale;
  3026. if (name === getSetGlobalLocale()) {
  3027. getSetGlobalLocale(name);
  3028. }
  3029. } else if (locales[name] != null) {
  3030. delete locales[name];
  3031. }
  3032. }
  3033. }
  3034. return locales[name];
  3035. }
  3036. // returns locale data
  3037. function getLocale(key) {
  3038. var locale;
  3039. if (key && key._locale && key._locale._abbr) {
  3040. key = key._locale._abbr;
  3041. }
  3042. if (!key) {
  3043. return globalLocale;
  3044. }
  3045. if (!isArray(key)) {
  3046. //short-circuit everything else
  3047. locale = loadLocale(key);
  3048. if (locale) {
  3049. return locale;
  3050. }
  3051. key = [key];
  3052. }
  3053. return chooseLocale(key);
  3054. }
  3055. function listLocales() {
  3056. return keys(locales);
  3057. }
  3058. function checkOverflow(m) {
  3059. var overflow,
  3060. a = m._a;
  3061. if (a && getParsingFlags(m).overflow === -2) {
  3062. overflow =
  3063. a[MONTH] < 0 || a[MONTH] > 11
  3064. ? MONTH
  3065. : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
  3066. ? DATE
  3067. : a[HOUR] < 0 ||
  3068. a[HOUR] > 24 ||
  3069. (a[HOUR] === 24 &&
  3070. (a[MINUTE] !== 0 ||
  3071. a[SECOND] !== 0 ||
  3072. a[MILLISECOND] !== 0))
  3073. ? HOUR
  3074. : a[MINUTE] < 0 || a[MINUTE] > 59
  3075. ? MINUTE
  3076. : a[SECOND] < 0 || a[SECOND] > 59
  3077. ? SECOND
  3078. : a[MILLISECOND] < 0 || a[MILLISECOND] > 999
  3079. ? MILLISECOND
  3080. : -1;
  3081. if (
  3082. getParsingFlags(m)._overflowDayOfYear &&
  3083. (overflow < YEAR || overflow > DATE)
  3084. ) {
  3085. overflow = DATE;
  3086. }
  3087. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  3088. overflow = WEEK;
  3089. }
  3090. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  3091. overflow = WEEKDAY;
  3092. }
  3093. getParsingFlags(m).overflow = overflow;
  3094. }
  3095. return m;
  3096. }
  3097. // iso 8601 regex
  3098. // 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)
  3099. var extendedIsoRegex =
  3100. /^\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)?)?$/,
  3101. basicIsoRegex =
  3102. /^\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)?)?$/,
  3103. tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
  3104. isoDates = [
  3105. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  3106. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  3107. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  3108. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  3109. ['YYYY-DDD', /\d{4}-\d{3}/],
  3110. ['YYYY-MM', /\d{4}-\d\d/, false],
  3111. ['YYYYYYMMDD', /[+-]\d{10}/],
  3112. ['YYYYMMDD', /\d{8}/],
  3113. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  3114. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  3115. ['YYYYDDD', /\d{7}/],
  3116. ['YYYYMM', /\d{6}/, false],
  3117. ['YYYY', /\d{4}/, false],
  3118. ],
  3119. // iso time formats and regexes
  3120. isoTimes = [
  3121. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  3122. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  3123. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  3124. ['HH:mm', /\d\d:\d\d/],
  3125. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  3126. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  3127. ['HHmmss', /\d\d\d\d\d\d/],
  3128. ['HHmm', /\d\d\d\d/],
  3129. ['HH', /\d\d/],
  3130. ],
  3131. aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
  3132. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  3133. rfc2822 =
  3134. /^(?:(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}))$/,
  3135. obsOffsets = {
  3136. UT: 0,
  3137. GMT: 0,
  3138. EDT: -4 * 60,
  3139. EST: -5 * 60,
  3140. CDT: -5 * 60,
  3141. CST: -6 * 60,
  3142. MDT: -6 * 60,
  3143. MST: -7 * 60,
  3144. PDT: -7 * 60,
  3145. PST: -8 * 60,
  3146. };
  3147. // date from iso format
  3148. function configFromISO(config) {
  3149. var i,
  3150. l,
  3151. string = config._i,
  3152. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  3153. allowTime,
  3154. dateFormat,
  3155. timeFormat,
  3156. tzFormat,
  3157. isoDatesLen = isoDates.length,
  3158. isoTimesLen = isoTimes.length;
  3159. if (match) {
  3160. getParsingFlags(config).iso = true;
  3161. for (i = 0, l = isoDatesLen; i < l; i++) {
  3162. if (isoDates[i][1].exec(match[1])) {
  3163. dateFormat = isoDates[i][0];
  3164. allowTime = isoDates[i][2] !== false;
  3165. break;
  3166. }
  3167. }
  3168. if (dateFormat == null) {
  3169. config._isValid = false;
  3170. return;
  3171. }
  3172. if (match[3]) {
  3173. for (i = 0, l = isoTimesLen; i < l; i++) {
  3174. if (isoTimes[i][1].exec(match[3])) {
  3175. // match[2] should be 'T' or space
  3176. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  3177. break;
  3178. }
  3179. }
  3180. if (timeFormat == null) {
  3181. config._isValid = false;
  3182. return;
  3183. }
  3184. }
  3185. if (!allowTime && timeFormat != null) {
  3186. config._isValid = false;
  3187. return;
  3188. }
  3189. if (match[4]) {
  3190. if (tzRegex.exec(match[4])) {
  3191. tzFormat = 'Z';
  3192. } else {
  3193. config._isValid = false;
  3194. return;
  3195. }
  3196. }
  3197. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  3198. configFromStringAndFormat(config);
  3199. } else {
  3200. config._isValid = false;
  3201. }
  3202. }
  3203. function extractFromRFC2822Strings(
  3204. yearStr,
  3205. monthStr,
  3206. dayStr,
  3207. hourStr,
  3208. minuteStr,
  3209. secondStr
  3210. ) {
  3211. var result = [
  3212. untruncateYear(yearStr),
  3213. defaultLocaleMonthsShort.indexOf(monthStr),
  3214. parseInt(dayStr, 10),
  3215. parseInt(hourStr, 10),
  3216. parseInt(minuteStr, 10),
  3217. ];
  3218. if (secondStr) {
  3219. result.push(parseInt(secondStr, 10));
  3220. }
  3221. return result;
  3222. }
  3223. function untruncateYear(yearStr) {
  3224. var year = parseInt(yearStr, 10);
  3225. if (year <= 49) {
  3226. return 2000 + year;
  3227. } else if (year <= 999) {
  3228. return 1900 + year;
  3229. }
  3230. return year;
  3231. }
  3232. function preprocessRFC2822(s) {
  3233. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  3234. return s
  3235. .replace(/\([^()]*\)|[\n\t]/g, ' ')
  3236. .replace(/(\s\s+)/g, ' ')
  3237. .replace(/^\s\s*/, '')
  3238. .replace(/\s\s*$/, '');
  3239. }
  3240. function checkWeekday(weekdayStr, parsedInput, config) {
  3241. if (weekdayStr) {
  3242. // TODO: Replace the vanilla JS Date object with an independent day-of-week check.
  3243. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  3244. weekdayActual = new Date(
  3245. parsedInput[0],
  3246. parsedInput[1],
  3247. parsedInput[2]
  3248. ).getDay();
  3249. if (weekdayProvided !== weekdayActual) {
  3250. getParsingFlags(config).weekdayMismatch = true;
  3251. config._isValid = false;
  3252. return false;
  3253. }
  3254. }
  3255. return true;
  3256. }
  3257. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  3258. if (obsOffset) {
  3259. return obsOffsets[obsOffset];
  3260. } else if (militaryOffset) {
  3261. // the only allowed military tz is Z
  3262. return 0;
  3263. } else {
  3264. var hm = parseInt(numOffset, 10),
  3265. m = hm % 100,
  3266. h = (hm - m) / 100;
  3267. return h * 60 + m;
  3268. }
  3269. }
  3270. // date and time from ref 2822 format
  3271. function configFromRFC2822(config) {
  3272. var match = rfc2822.exec(preprocessRFC2822(config._i)),
  3273. parsedArray;
  3274. if (match) {
  3275. parsedArray = extractFromRFC2822Strings(
  3276. match[4],
  3277. match[3],
  3278. match[2],
  3279. match[5],
  3280. match[6],
  3281. match[7]
  3282. );
  3283. if (!checkWeekday(match[1], parsedArray, config)) {
  3284. return;
  3285. }
  3286. config._a = parsedArray;
  3287. config._tzm = calculateOffset(match[8], match[9], match[10]);
  3288. config._d = createUTCDate.apply(null, config._a);
  3289. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  3290. getParsingFlags(config).rfc2822 = true;
  3291. } else {
  3292. config._isValid = false;
  3293. }
  3294. }
  3295. // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
  3296. function configFromString(config) {
  3297. var matched = aspNetJsonRegex.exec(config._i);
  3298. if (matched !== null) {
  3299. config._d = new Date(+matched[1]);
  3300. return;
  3301. }
  3302. configFromISO(config);
  3303. if (config._isValid === false) {
  3304. delete config._isValid;
  3305. } else {
  3306. return;
  3307. }
  3308. configFromRFC2822(config);
  3309. if (config._isValid === false) {
  3310. delete config._isValid;
  3311. } else {
  3312. return;
  3313. }
  3314. if (config._strict) {
  3315. config._isValid = false;
  3316. } else {
  3317. // Final attempt, use Input Fallback
  3318. hooks.createFromInputFallback(config);
  3319. }
  3320. }
  3321. hooks.createFromInputFallback = deprecate(
  3322. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  3323. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  3324. 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  3325. function (config) {
  3326. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  3327. }
  3328. );
  3329. // Pick the first defined of two or three arguments.
  3330. function defaults(a, b, c) {
  3331. if (a != null) {
  3332. return a;
  3333. }
  3334. if (b != null) {
  3335. return b;
  3336. }
  3337. return c;
  3338. }
  3339. function currentDateArray(config) {
  3340. // hooks is actually the exported moment object
  3341. var nowValue = new Date(hooks.now());
  3342. if (config._useUTC) {
  3343. return [
  3344. nowValue.getUTCFullYear(),
  3345. nowValue.getUTCMonth(),
  3346. nowValue.getUTCDate(),
  3347. ];
  3348. }
  3349. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  3350. }
  3351. // convert an array to a date.
  3352. // the array should mirror the parameters below
  3353. // note: all values past the year are optional and will default to the lowest possible value.
  3354. // [year, month, day , hour, minute, second, millisecond]
  3355. function configFromArray(config) {
  3356. var i,
  3357. date,
  3358. input = [],
  3359. currentDate,
  3360. expectedWeekday,
  3361. yearToUse;
  3362. if (config._d) {
  3363. return;
  3364. }
  3365. currentDate = currentDateArray(config);
  3366. //compute day of the year from weeks and weekdays
  3367. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  3368. dayOfYearFromWeekInfo(config);
  3369. }
  3370. //if the day of the year is set, figure out what it is
  3371. if (config._dayOfYear != null) {
  3372. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  3373. if (
  3374. config._dayOfYear > daysInYear(yearToUse) ||
  3375. config._dayOfYear === 0
  3376. ) {
  3377. getParsingFlags(config)._overflowDayOfYear = true;
  3378. }
  3379. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  3380. config._a[MONTH] = date.getUTCMonth();
  3381. config._a[DATE] = date.getUTCDate();
  3382. }
  3383. // Default to current date.
  3384. // * if no year, month, day of month are given, default to today
  3385. // * if day of month is given, default month and year
  3386. // * if month is given, default only year
  3387. // * if year is given, don't default anything
  3388. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  3389. config._a[i] = input[i] = currentDate[i];
  3390. }
  3391. // Zero out whatever was not defaulted, including time
  3392. for (; i < 7; i++) {
  3393. config._a[i] = input[i] =
  3394. config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
  3395. }
  3396. // Check for 24:00:00.000
  3397. if (
  3398. config._a[HOUR] === 24 &&
  3399. config._a[MINUTE] === 0 &&
  3400. config._a[SECOND] === 0 &&
  3401. config._a[MILLISECOND] === 0
  3402. ) {
  3403. config._nextDay = true;
  3404. config._a[HOUR] = 0;
  3405. }
  3406. config._d = (config._useUTC ? createUTCDate : createDate).apply(
  3407. null,
  3408. input
  3409. );
  3410. expectedWeekday = config._useUTC
  3411. ? config._d.getUTCDay()
  3412. : config._d.getDay();
  3413. // Apply timezone offset from input. The actual utcOffset can be changed
  3414. // with parseZone.
  3415. if (config._tzm != null) {
  3416. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  3417. }
  3418. if (config._nextDay) {
  3419. config._a[HOUR] = 24;
  3420. }
  3421. // check for mismatching day of week
  3422. if (
  3423. config._w &&
  3424. typeof config._w.d !== 'undefined' &&
  3425. config._w.d !== expectedWeekday
  3426. ) {
  3427. getParsingFlags(config).weekdayMismatch = true;
  3428. }
  3429. }
  3430. function dayOfYearFromWeekInfo(config) {
  3431. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
  3432. w = config._w;
  3433. if (w.GG != null || w.W != null || w.E != null) {
  3434. dow = 1;
  3435. doy = 4;
  3436. // TODO: We need to take the current isoWeekYear, but that depends on
  3437. // how we interpret now (local, utc, fixed offset). So create
  3438. // a now version of current config (take local/utc/offset flags, and
  3439. // create now).
  3440. weekYear = defaults(
  3441. w.GG,
  3442. config._a[YEAR],
  3443. weekOfYear(createLocal(), 1, 4).year
  3444. );
  3445. week = defaults(w.W, 1);
  3446. weekday = defaults(w.E, 1);
  3447. if (weekday < 1 || weekday > 7) {
  3448. weekdayOverflow = true;
  3449. }
  3450. } else {
  3451. dow = config._locale._week.dow;
  3452. doy = config._locale._week.doy;
  3453. curWeek = weekOfYear(createLocal(), dow, doy);
  3454. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  3455. // Default to current week.
  3456. week = defaults(w.w, curWeek.week);
  3457. if (w.d != null) {
  3458. // weekday -- low day numbers are considered next week
  3459. weekday = w.d;
  3460. if (weekday < 0 || weekday > 6) {
  3461. weekdayOverflow = true;
  3462. }
  3463. } else if (w.e != null) {
  3464. // local weekday -- counting starts from beginning of week
  3465. weekday = w.e + dow;
  3466. if (w.e < 0 || w.e > 6) {
  3467. weekdayOverflow = true;
  3468. }
  3469. } else {
  3470. // default to beginning of week
  3471. weekday = dow;
  3472. }
  3473. }
  3474. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  3475. getParsingFlags(config)._overflowWeeks = true;
  3476. } else if (weekdayOverflow != null) {
  3477. getParsingFlags(config)._overflowWeekday = true;
  3478. } else {
  3479. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  3480. config._a[YEAR] = temp.year;
  3481. config._dayOfYear = temp.dayOfYear;
  3482. }
  3483. }
  3484. // constant that refers to the ISO standard
  3485. hooks.ISO_8601 = function () {};
  3486. // constant that refers to the RFC 2822 form
  3487. hooks.RFC_2822 = function () {};
  3488. // date from string and format string
  3489. function configFromStringAndFormat(config) {
  3490. // TODO: Move this to another part of the creation flow to prevent circular deps
  3491. if (config._f === hooks.ISO_8601) {
  3492. configFromISO(config);
  3493. return;
  3494. }
  3495. if (config._f === hooks.RFC_2822) {
  3496. configFromRFC2822(config);
  3497. return;
  3498. }
  3499. config._a = [];
  3500. getParsingFlags(config).empty = true;
  3501. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  3502. var string = '' + config._i,
  3503. i,
  3504. parsedInput,
  3505. tokens,
  3506. token,
  3507. skipped,
  3508. stringLength = string.length,
  3509. totalParsedInputLength = 0,
  3510. era,
  3511. tokenLen;
  3512. tokens =
  3513. expandFormat(config._f, config._locale).match(formattingTokens) || [];
  3514. tokenLen = tokens.length;
  3515. for (i = 0; i < tokenLen; i++) {
  3516. token = tokens[i];
  3517. parsedInput = (string.match(getParseRegexForToken(token, config)) ||
  3518. [])[0];
  3519. if (parsedInput) {
  3520. skipped = string.substr(0, string.indexOf(parsedInput));
  3521. if (skipped.length > 0) {
  3522. getParsingFlags(config).unusedInput.push(skipped);
  3523. }
  3524. string = string.slice(
  3525. string.indexOf(parsedInput) + parsedInput.length
  3526. );
  3527. totalParsedInputLength += parsedInput.length;
  3528. }
  3529. // don't parse if it's not a known token
  3530. if (formatTokenFunctions[token]) {
  3531. if (parsedInput) {
  3532. getParsingFlags(config).empty = false;
  3533. } else {
  3534. getParsingFlags(config).unusedTokens.push(token);
  3535. }
  3536. addTimeToArrayFromToken(token, parsedInput, config);
  3537. } else if (config._strict && !parsedInput) {
  3538. getParsingFlags(config).unusedTokens.push(token);
  3539. }
  3540. }
  3541. // add remaining unparsed input length to the string
  3542. getParsingFlags(config).charsLeftOver =
  3543. stringLength - totalParsedInputLength;
  3544. if (string.length > 0) {
  3545. getParsingFlags(config).unusedInput.push(string);
  3546. }
  3547. // clear _12h flag if hour is <= 12
  3548. if (
  3549. config._a[HOUR] <= 12 &&
  3550. getParsingFlags(config).bigHour === true &&
  3551. config._a[HOUR] > 0
  3552. ) {
  3553. getParsingFlags(config).bigHour = undefined;
  3554. }
  3555. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  3556. getParsingFlags(config).meridiem = config._meridiem;
  3557. // handle meridiem
  3558. config._a[HOUR] = meridiemFixWrap(
  3559. config._locale,
  3560. config._a[HOUR],
  3561. config._meridiem
  3562. );
  3563. // handle era
  3564. era = getParsingFlags(config).era;
  3565. if (era !== null) {
  3566. config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
  3567. }
  3568. configFromArray(config);
  3569. checkOverflow(config);
  3570. }
  3571. function meridiemFixWrap(locale, hour, meridiem) {
  3572. var isPm;
  3573. if (meridiem == null) {
  3574. // nothing to do
  3575. return hour;
  3576. }
  3577. if (locale.meridiemHour != null) {
  3578. return locale.meridiemHour(hour, meridiem);
  3579. } else if (locale.isPM != null) {
  3580. // Fallback
  3581. isPm = locale.isPM(meridiem);
  3582. if (isPm && hour < 12) {
  3583. hour += 12;
  3584. }
  3585. if (!isPm && hour === 12) {
  3586. hour = 0;
  3587. }
  3588. return hour;
  3589. } else {
  3590. // this is not supposed to happen
  3591. return hour;
  3592. }
  3593. }
  3594. // date from string and array of format strings
  3595. function configFromStringAndArray(config) {
  3596. var tempConfig,
  3597. bestMoment,
  3598. scoreToBeat,
  3599. i,
  3600. currentScore,
  3601. validFormatFound,
  3602. bestFormatIsValid = false,
  3603. configfLen = config._f.length;
  3604. if (configfLen === 0) {
  3605. getParsingFlags(config).invalidFormat = true;
  3606. config._d = new Date(NaN);
  3607. return;
  3608. }
  3609. for (i = 0; i < configfLen; i++) {
  3610. currentScore = 0;
  3611. validFormatFound = false;
  3612. tempConfig = copyConfig({}, config);
  3613. if (config._useUTC != null) {
  3614. tempConfig._useUTC = config._useUTC;
  3615. }
  3616. tempConfig._f = config._f[i];
  3617. configFromStringAndFormat(tempConfig);
  3618. if (isValid(tempConfig)) {
  3619. validFormatFound = true;
  3620. }
  3621. // if there is any input that was not parsed add a penalty for that format
  3622. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  3623. //or tokens
  3624. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  3625. getParsingFlags(tempConfig).score = currentScore;
  3626. if (!bestFormatIsValid) {
  3627. if (
  3628. scoreToBeat == null ||
  3629. currentScore < scoreToBeat ||
  3630. validFormatFound
  3631. ) {
  3632. scoreToBeat = currentScore;
  3633. bestMoment = tempConfig;
  3634. if (validFormatFound) {
  3635. bestFormatIsValid = true;
  3636. }
  3637. }
  3638. } else {
  3639. if (currentScore < scoreToBeat) {
  3640. scoreToBeat = currentScore;
  3641. bestMoment = tempConfig;
  3642. }
  3643. }
  3644. }
  3645. extend(config, bestMoment || tempConfig);
  3646. }
  3647. function configFromObject(config) {
  3648. if (config._d) {
  3649. return;
  3650. }
  3651. var i = normalizeObjectUnits(config._i),
  3652. dayOrDate = i.day === undefined ? i.date : i.day;
  3653. config._a = map(
  3654. [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
  3655. function (obj) {
  3656. return obj && parseInt(obj, 10);
  3657. }
  3658. );
  3659. configFromArray(config);
  3660. }
  3661. function createFromConfig(config) {
  3662. var res = new Moment(checkOverflow(prepareConfig(config)));
  3663. if (res._nextDay) {
  3664. // Adding is smart enough around DST
  3665. res.add(1, 'd');
  3666. res._nextDay = undefined;
  3667. }
  3668. return res;
  3669. }
  3670. function prepareConfig(config) {
  3671. var input = config._i,
  3672. format = config._f;
  3673. config._locale = config._locale || getLocale(config._l);
  3674. if (input === null || (format === undefined && input === '')) {
  3675. return createInvalid({ nullInput: true });
  3676. }
  3677. if (typeof input === 'string') {
  3678. config._i = input = config._locale.preparse(input);
  3679. }
  3680. if (isMoment(input)) {
  3681. return new Moment(checkOverflow(input));
  3682. } else if (isDate(input)) {
  3683. config._d = input;
  3684. } else if (isArray(format)) {
  3685. configFromStringAndArray(config);
  3686. } else if (format) {
  3687. configFromStringAndFormat(config);
  3688. } else {
  3689. configFromInput(config);
  3690. }
  3691. if (!isValid(config)) {
  3692. config._d = null;
  3693. }
  3694. return config;
  3695. }
  3696. function configFromInput(config) {
  3697. var input = config._i;
  3698. if (isUndefined(input)) {
  3699. config._d = new Date(hooks.now());
  3700. } else if (isDate(input)) {
  3701. config._d = new Date(input.valueOf());
  3702. } else if (typeof input === 'string') {
  3703. configFromString(config);
  3704. } else if (isArray(input)) {
  3705. config._a = map(input.slice(0), function (obj) {
  3706. return parseInt(obj, 10);
  3707. });
  3708. configFromArray(config);
  3709. } else if (isObject(input)) {
  3710. configFromObject(config);
  3711. } else if (isNumber(input)) {
  3712. // from milliseconds
  3713. config._d = new Date(input);
  3714. } else {
  3715. hooks.createFromInputFallback(config);
  3716. }
  3717. }
  3718. function createLocalOrUTC(input, format, locale, strict, isUTC) {
  3719. var c = {};
  3720. if (format === true || format === false) {
  3721. strict = format;
  3722. format = undefined;
  3723. }
  3724. if (locale === true || locale === false) {
  3725. strict = locale;
  3726. locale = undefined;
  3727. }
  3728. if (
  3729. (isObject(input) && isObjectEmpty(input)) ||
  3730. (isArray(input) && input.length === 0)
  3731. ) {
  3732. input = undefined;
  3733. }
  3734. // object construction must be done this way.
  3735. // https://github.com/moment/moment/issues/1423
  3736. c._isAMomentObject = true;
  3737. c._useUTC = c._isUTC = isUTC;
  3738. c._l = locale;
  3739. c._i = input;
  3740. c._f = format;
  3741. c._strict = strict;
  3742. return createFromConfig(c);
  3743. }
  3744. function createLocal(input, format, locale, strict) {
  3745. return createLocalOrUTC(input, format, locale, strict, false);
  3746. }
  3747. var prototypeMin = deprecate(
  3748. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  3749. function () {
  3750. var other = createLocal.apply(null, arguments);
  3751. if (this.isValid() && other.isValid()) {
  3752. return other < this ? this : other;
  3753. } else {
  3754. return createInvalid();
  3755. }
  3756. }
  3757. ),
  3758. prototypeMax = deprecate(
  3759. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  3760. function () {
  3761. var other = createLocal.apply(null, arguments);
  3762. if (this.isValid() && other.isValid()) {
  3763. return other > this ? this : other;
  3764. } else {
  3765. return createInvalid();
  3766. }
  3767. }
  3768. );
  3769. // Pick a moment m from moments so that m[fn](other) is true for all
  3770. // other. This relies on the function fn to be transitive.
  3771. //
  3772. // moments should either be an array of moment objects or an array, whose
  3773. // first element is an array of moment objects.
  3774. function pickBy(fn, moments) {
  3775. var res, i;
  3776. if (moments.length === 1 && isArray(moments[0])) {
  3777. moments = moments[0];
  3778. }
  3779. if (!moments.length) {
  3780. return createLocal();
  3781. }
  3782. res = moments[0];
  3783. for (i = 1; i < moments.length; ++i) {
  3784. if (!moments[i].isValid() || moments[i][fn](res)) {
  3785. res = moments[i];
  3786. }
  3787. }
  3788. return res;
  3789. }
  3790. // TODO: Use [].sort instead?
  3791. function min() {
  3792. var args = [].slice.call(arguments, 0);
  3793. return pickBy('isBefore', args);
  3794. }
  3795. function max() {
  3796. var args = [].slice.call(arguments, 0);
  3797. return pickBy('isAfter', args);
  3798. }
  3799. var now = function () {
  3800. return Date.now ? Date.now() : +new Date();
  3801. };
  3802. var ordering = [
  3803. 'year',
  3804. 'quarter',
  3805. 'month',
  3806. 'week',
  3807. 'day',
  3808. 'hour',
  3809. 'minute',
  3810. 'second',
  3811. 'millisecond',
  3812. ];
  3813. function isDurationValid(m) {
  3814. var key,
  3815. unitHasDecimal = false,
  3816. i,
  3817. orderLen = ordering.length;
  3818. for (key in m) {
  3819. if (
  3820. hasOwnProp(m, key) &&
  3821. !(
  3822. indexOf.call(ordering, key) !== -1 &&
  3823. (m[key] == null || !isNaN(m[key]))
  3824. )
  3825. ) {
  3826. return false;
  3827. }
  3828. }
  3829. for (i = 0; i < orderLen; ++i) {
  3830. if (m[ordering[i]]) {
  3831. if (unitHasDecimal) {
  3832. return false; // only allow non-integers for smallest unit
  3833. }
  3834. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  3835. unitHasDecimal = true;
  3836. }
  3837. }
  3838. }
  3839. return true;
  3840. }
  3841. function isValid$1() {
  3842. return this._isValid;
  3843. }
  3844. function createInvalid$1() {
  3845. return createDuration(NaN);
  3846. }
  3847. function Duration(duration) {
  3848. var normalizedInput = normalizeObjectUnits(duration),
  3849. years = normalizedInput.year || 0,
  3850. quarters = normalizedInput.quarter || 0,
  3851. months = normalizedInput.month || 0,
  3852. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  3853. days = normalizedInput.day || 0,
  3854. hours = normalizedInput.hour || 0,
  3855. minutes = normalizedInput.minute || 0,
  3856. seconds = normalizedInput.second || 0,
  3857. milliseconds = normalizedInput.millisecond || 0;
  3858. this._isValid = isDurationValid(normalizedInput);
  3859. // representation for dateAddRemove
  3860. this._milliseconds =
  3861. +milliseconds +
  3862. seconds * 1e3 + // 1000
  3863. minutes * 6e4 + // 1000 * 60
  3864. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  3865. // Because of dateAddRemove treats 24 hours as different from a
  3866. // day when working around DST, we need to store them separately
  3867. this._days = +days + weeks * 7;
  3868. // It is impossible to translate months into days without knowing
  3869. // which months you are are talking about, so we have to store
  3870. // it separately.
  3871. this._months = +months + quarters * 3 + years * 12;
  3872. this._data = {};
  3873. this._locale = getLocale();
  3874. this._bubble();
  3875. }
  3876. function isDuration(obj) {
  3877. return obj instanceof Duration;
  3878. }
  3879. function absRound(number) {
  3880. if (number < 0) {
  3881. return Math.round(-1 * number) * -1;
  3882. } else {
  3883. return Math.round(number);
  3884. }
  3885. }
  3886. // compare two arrays, return the number of differences
  3887. function compareArrays(array1, array2, dontConvert) {
  3888. var len = Math.min(array1.length, array2.length),
  3889. lengthDiff = Math.abs(array1.length - array2.length),
  3890. diffs = 0,
  3891. i;
  3892. for (i = 0; i < len; i++) {
  3893. if (
  3894. (dontConvert && array1[i] !== array2[i]) ||
  3895. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
  3896. ) {
  3897. diffs++;
  3898. }
  3899. }
  3900. return diffs + lengthDiff;
  3901. }
  3902. // FORMATTING
  3903. function offset(token, separator) {
  3904. addFormatToken(token, 0, 0, function () {
  3905. var offset = this.utcOffset(),
  3906. sign = '+';
  3907. if (offset < 0) {
  3908. offset = -offset;
  3909. sign = '-';
  3910. }
  3911. return (
  3912. sign +
  3913. zeroFill(~~(offset / 60), 2) +
  3914. separator +
  3915. zeroFill(~~offset % 60, 2)
  3916. );
  3917. });
  3918. }
  3919. offset('Z', ':');
  3920. offset('ZZ', '');
  3921. // PARSING
  3922. addRegexToken('Z', matchShortOffset);
  3923. addRegexToken('ZZ', matchShortOffset);
  3924. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  3925. config._useUTC = true;
  3926. config._tzm = offsetFromString(matchShortOffset, input);
  3927. });
  3928. // HELPERS
  3929. // timezone chunker
  3930. // '+10:00' > ['10', '00']
  3931. // '-1530' > ['-15', '30']
  3932. var chunkOffset = /([\+\-]|\d\d)/gi;
  3933. function offsetFromString(matcher, string) {
  3934. var matches = (string || '').match(matcher),
  3935. chunk,
  3936. parts,
  3937. minutes;
  3938. if (matches === null) {
  3939. return null;
  3940. }
  3941. chunk = matches[matches.length - 1] || [];
  3942. parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  3943. minutes = +(parts[1] * 60) + toInt(parts[2]);
  3944. return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
  3945. }
  3946. // Return a moment from input, that is local/utc/zone equivalent to model.
  3947. function cloneWithOffset(input, model) {
  3948. var res, diff;
  3949. if (model._isUTC) {
  3950. res = model.clone();
  3951. diff =
  3952. (isMoment(input) || isDate(input)
  3953. ? input.valueOf()
  3954. : createLocal(input).valueOf()) - res.valueOf();
  3955. // Use low-level api, because this fn is low-level api.
  3956. res._d.setTime(res._d.valueOf() + diff);
  3957. hooks.updateOffset(res, false);
  3958. return res;
  3959. } else {
  3960. return createLocal(input).local();
  3961. }
  3962. }
  3963. function getDateOffset(m) {
  3964. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  3965. // https://github.com/moment/moment/pull/1871
  3966. return -Math.round(m._d.getTimezoneOffset());
  3967. }
  3968. // HOOKS
  3969. // This function will be called whenever a moment is mutated.
  3970. // It is intended to keep the offset in sync with the timezone.
  3971. hooks.updateOffset = function () {};
  3972. // MOMENTS
  3973. // keepLocalTime = true means only change the timezone, without
  3974. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  3975. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  3976. // +0200, so we adjust the time as needed, to be valid.
  3977. //
  3978. // Keeping the time actually adds/subtracts (one hour)
  3979. // from the actual represented time. That is why we call updateOffset
  3980. // a second time. In case it wants us to change the offset again
  3981. // _changeInProgress == true case, then we have to adjust, because
  3982. // there is no such time in the given timezone.
  3983. function getSetOffset(input, keepLocalTime, keepMinutes) {
  3984. var offset = this._offset || 0,
  3985. localAdjust;
  3986. if (!this.isValid()) {
  3987. return input != null ? this : NaN;
  3988. }
  3989. if (input != null) {
  3990. if (typeof input === 'string') {
  3991. input = offsetFromString(matchShortOffset, input);
  3992. if (input === null) {
  3993. return this;
  3994. }
  3995. } else if (Math.abs(input) < 16 && !keepMinutes) {
  3996. input = input * 60;
  3997. }
  3998. if (!this._isUTC && keepLocalTime) {
  3999. localAdjust = getDateOffset(this);
  4000. }
  4001. this._offset = input;
  4002. this._isUTC = true;
  4003. if (localAdjust != null) {
  4004. this.add(localAdjust, 'm');
  4005. }
  4006. if (offset !== input) {
  4007. if (!keepLocalTime || this._changeInProgress) {
  4008. addSubtract(
  4009. this,
  4010. createDuration(input - offset, 'm'),
  4011. 1,
  4012. false
  4013. );
  4014. } else if (!this._changeInProgress) {
  4015. this._changeInProgress = true;
  4016. hooks.updateOffset(this, true);
  4017. this._changeInProgress = null;
  4018. }
  4019. }
  4020. return this;
  4021. } else {
  4022. return this._isUTC ? offset : getDateOffset(this);
  4023. }
  4024. }
  4025. function getSetZone(input, keepLocalTime) {
  4026. if (input != null) {
  4027. if (typeof input !== 'string') {
  4028. input = -input;
  4029. }
  4030. this.utcOffset(input, keepLocalTime);
  4031. return this;
  4032. } else {
  4033. return -this.utcOffset();
  4034. }
  4035. }
  4036. function setOffsetToUTC(keepLocalTime) {
  4037. return this.utcOffset(0, keepLocalTime);
  4038. }
  4039. function setOffsetToLocal(keepLocalTime) {
  4040. if (this._isUTC) {
  4041. this.utcOffset(0, keepLocalTime);
  4042. this._isUTC = false;
  4043. if (keepLocalTime) {
  4044. this.subtract(getDateOffset(this), 'm');
  4045. }
  4046. }
  4047. return this;
  4048. }
  4049. function setOffsetToParsedOffset() {
  4050. if (this._tzm != null) {
  4051. this.utcOffset(this._tzm, false, true);
  4052. } else if (typeof this._i === 'string') {
  4053. var tZone = offsetFromString(matchOffset, this._i);
  4054. if (tZone != null) {
  4055. this.utcOffset(tZone);
  4056. } else {
  4057. this.utcOffset(0, true);
  4058. }
  4059. }
  4060. return this;
  4061. }
  4062. function hasAlignedHourOffset(input) {
  4063. if (!this.isValid()) {
  4064. return false;
  4065. }
  4066. input = input ? createLocal(input).utcOffset() : 0;
  4067. return (this.utcOffset() - input) % 60 === 0;
  4068. }
  4069. function isDaylightSavingTime() {
  4070. return (
  4071. this.utcOffset() > this.clone().month(0).utcOffset() ||
  4072. this.utcOffset() > this.clone().month(5).utcOffset()
  4073. );
  4074. }
  4075. function isDaylightSavingTimeShifted() {
  4076. if (!isUndefined(this._isDSTShifted)) {
  4077. return this._isDSTShifted;
  4078. }
  4079. var c = {},
  4080. other;
  4081. copyConfig(c, this);
  4082. c = prepareConfig(c);
  4083. if (c._a) {
  4084. other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  4085. this._isDSTShifted =
  4086. this.isValid() && compareArrays(c._a, other.toArray()) > 0;
  4087. } else {
  4088. this._isDSTShifted = false;
  4089. }
  4090. return this._isDSTShifted;
  4091. }
  4092. function isLocal() {
  4093. return this.isValid() ? !this._isUTC : false;
  4094. }
  4095. function isUtcOffset() {
  4096. return this.isValid() ? this._isUTC : false;
  4097. }
  4098. function isUtc() {
  4099. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  4100. }
  4101. // ASP.NET json date format regex
  4102. var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
  4103. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  4104. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  4105. // and further modified to allow for strings containing both week and day
  4106. isoRegex =
  4107. /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  4108. function createDuration(input, key) {
  4109. var duration = input,
  4110. // matching against regexp is expensive, do it on demand
  4111. match = null,
  4112. sign,
  4113. ret,
  4114. diffRes;
  4115. if (isDuration(input)) {
  4116. duration = {
  4117. ms: input._milliseconds,
  4118. d: input._days,
  4119. M: input._months,
  4120. };
  4121. } else if (isNumber(input) || !isNaN(+input)) {
  4122. duration = {};
  4123. if (key) {
  4124. duration[key] = +input;
  4125. } else {
  4126. duration.milliseconds = +input;
  4127. }
  4128. } else if ((match = aspNetRegex.exec(input))) {
  4129. sign = match[1] === '-' ? -1 : 1;
  4130. duration = {
  4131. y: 0,
  4132. d: toInt(match[DATE]) * sign,
  4133. h: toInt(match[HOUR]) * sign,
  4134. m: toInt(match[MINUTE]) * sign,
  4135. s: toInt(match[SECOND]) * sign,
  4136. ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
  4137. };
  4138. } else if ((match = isoRegex.exec(input))) {
  4139. sign = match[1] === '-' ? -1 : 1;
  4140. duration = {
  4141. y: parseIso(match[2], sign),
  4142. M: parseIso(match[3], sign),
  4143. w: parseIso(match[4], sign),
  4144. d: parseIso(match[5], sign),
  4145. h: parseIso(match[6], sign),
  4146. m: parseIso(match[7], sign),
  4147. s: parseIso(match[8], sign),
  4148. };
  4149. } else if (duration == null) {
  4150. // checks for null or undefined
  4151. duration = {};
  4152. } else if (
  4153. typeof duration === 'object' &&
  4154. ('from' in duration || 'to' in duration)
  4155. ) {
  4156. diffRes = momentsDifference(
  4157. createLocal(duration.from),
  4158. createLocal(duration.to)
  4159. );
  4160. duration = {};
  4161. duration.ms = diffRes.milliseconds;
  4162. duration.M = diffRes.months;
  4163. }
  4164. ret = new Duration(duration);
  4165. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  4166. ret._locale = input._locale;
  4167. }
  4168. if (isDuration(input) && hasOwnProp(input, '_isValid')) {
  4169. ret._isValid = input._isValid;
  4170. }
  4171. return ret;
  4172. }
  4173. createDuration.fn = Duration.prototype;
  4174. createDuration.invalid = createInvalid$1;
  4175. function parseIso(inp, sign) {
  4176. // We'd normally use ~~inp for this, but unfortunately it also
  4177. // converts floats to ints.
  4178. // inp may be undefined, so careful calling replace on it.
  4179. var res = inp && parseFloat(inp.replace(',', '.'));
  4180. // apply sign while we're at it
  4181. return (isNaN(res) ? 0 : res) * sign;
  4182. }
  4183. function positiveMomentsDifference(base, other) {
  4184. var res = {};
  4185. res.months =
  4186. other.month() - base.month() + (other.year() - base.year()) * 12;
  4187. if (base.clone().add(res.months, 'M').isAfter(other)) {
  4188. --res.months;
  4189. }
  4190. res.milliseconds = +other - +base.clone().add(res.months, 'M');
  4191. return res;
  4192. }
  4193. function momentsDifference(base, other) {
  4194. var res;
  4195. if (!(base.isValid() && other.isValid())) {
  4196. return { milliseconds: 0, months: 0 };
  4197. }
  4198. other = cloneWithOffset(other, base);
  4199. if (base.isBefore(other)) {
  4200. res = positiveMomentsDifference(base, other);
  4201. } else {
  4202. res = positiveMomentsDifference(other, base);
  4203. res.milliseconds = -res.milliseconds;
  4204. res.months = -res.months;
  4205. }
  4206. return res;
  4207. }
  4208. // TODO: remove 'name' arg after deprecation is removed
  4209. function createAdder(direction, name) {
  4210. return function (val, period) {
  4211. var dur, tmp;
  4212. //invert the arguments, but complain about it
  4213. if (period !== null && !isNaN(+period)) {
  4214. deprecateSimple(
  4215. name,
  4216. 'moment().' +
  4217. name +
  4218. '(period, number) is deprecated. Please use moment().' +
  4219. name +
  4220. '(number, period). ' +
  4221. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
  4222. );
  4223. tmp = val;
  4224. val = period;
  4225. period = tmp;
  4226. }
  4227. dur = createDuration(val, period);
  4228. addSubtract(this, dur, direction);
  4229. return this;
  4230. };
  4231. }
  4232. function addSubtract(mom, duration, isAdding, updateOffset) {
  4233. var milliseconds = duration._milliseconds,
  4234. days = absRound(duration._days),
  4235. months = absRound(duration._months);
  4236. if (!mom.isValid()) {
  4237. // No op
  4238. return;
  4239. }
  4240. updateOffset = updateOffset == null ? true : updateOffset;
  4241. if (months) {
  4242. setMonth(mom, get(mom, 'Month') + months * isAdding);
  4243. }
  4244. if (days) {
  4245. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  4246. }
  4247. if (milliseconds) {
  4248. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  4249. }
  4250. if (updateOffset) {
  4251. hooks.updateOffset(mom, days || months);
  4252. }
  4253. }
  4254. var add = createAdder(1, 'add'),
  4255. subtract = createAdder(-1, 'subtract');
  4256. function isString(input) {
  4257. return typeof input === 'string' || input instanceof String;
  4258. }
  4259. // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
  4260. function isMomentInput(input) {
  4261. return (
  4262. isMoment(input) ||
  4263. isDate(input) ||
  4264. isString(input) ||
  4265. isNumber(input) ||
  4266. isNumberOrStringArray(input) ||
  4267. isMomentInputObject(input) ||
  4268. input === null ||
  4269. input === undefined
  4270. );
  4271. }
  4272. function isMomentInputObject(input) {
  4273. var objectTest = isObject(input) && !isObjectEmpty(input),
  4274. propertyTest = false,
  4275. properties = [
  4276. 'years',
  4277. 'year',
  4278. 'y',
  4279. 'months',
  4280. 'month',
  4281. 'M',
  4282. 'days',
  4283. 'day',
  4284. 'd',
  4285. 'dates',
  4286. 'date',
  4287. 'D',
  4288. 'hours',
  4289. 'hour',
  4290. 'h',
  4291. 'minutes',
  4292. 'minute',
  4293. 'm',
  4294. 'seconds',
  4295. 'second',
  4296. 's',
  4297. 'milliseconds',
  4298. 'millisecond',
  4299. 'ms',
  4300. ],
  4301. i,
  4302. property,
  4303. propertyLen = properties.length;
  4304. for (i = 0; i < propertyLen; i += 1) {
  4305. property = properties[i];
  4306. propertyTest = propertyTest || hasOwnProp(input, property);
  4307. }
  4308. return objectTest && propertyTest;
  4309. }
  4310. function isNumberOrStringArray(input) {
  4311. var arrayTest = isArray(input),
  4312. dataTypeTest = false;
  4313. if (arrayTest) {
  4314. dataTypeTest =
  4315. input.filter(function (item) {
  4316. return !isNumber(item) && isString(input);
  4317. }).length === 0;
  4318. }
  4319. return arrayTest && dataTypeTest;
  4320. }
  4321. function isCalendarSpec(input) {
  4322. var objectTest = isObject(input) && !isObjectEmpty(input),
  4323. propertyTest = false,
  4324. properties = [
  4325. 'sameDay',
  4326. 'nextDay',
  4327. 'lastDay',
  4328. 'nextWeek',
  4329. 'lastWeek',
  4330. 'sameElse',
  4331. ],
  4332. i,
  4333. property;
  4334. for (i = 0; i < properties.length; i += 1) {
  4335. property = properties[i];
  4336. propertyTest = propertyTest || hasOwnProp(input, property);
  4337. }
  4338. return objectTest && propertyTest;
  4339. }
  4340. function getCalendarFormat(myMoment, now) {
  4341. var diff = myMoment.diff(now, 'days', true);
  4342. return diff < -6
  4343. ? 'sameElse'
  4344. : diff < -1
  4345. ? 'lastWeek'
  4346. : diff < 0
  4347. ? 'lastDay'
  4348. : diff < 1
  4349. ? 'sameDay'
  4350. : diff < 2
  4351. ? 'nextDay'
  4352. : diff < 7
  4353. ? 'nextWeek'
  4354. : 'sameElse';
  4355. }
  4356. function calendar$1(time, formats) {
  4357. // Support for single parameter, formats only overload to the calendar function
  4358. if (arguments.length === 1) {
  4359. if (!arguments[0]) {
  4360. time = undefined;
  4361. formats = undefined;
  4362. } else if (isMomentInput(arguments[0])) {
  4363. time = arguments[0];
  4364. formats = undefined;
  4365. } else if (isCalendarSpec(arguments[0])) {
  4366. formats = arguments[0];
  4367. time = undefined;
  4368. }
  4369. }
  4370. // We want to compare the start of today, vs this.
  4371. // Getting start-of-today depends on whether we're local/utc/offset or not.
  4372. var now = time || createLocal(),
  4373. sod = cloneWithOffset(now, this).startOf('day'),
  4374. format = hooks.calendarFormat(this, sod) || 'sameElse',
  4375. output =
  4376. formats &&
  4377. (isFunction(formats[format])
  4378. ? formats[format].call(this, now)
  4379. : formats[format]);
  4380. return this.format(
  4381. output || this.localeData().calendar(format, this, createLocal(now))
  4382. );
  4383. }
  4384. function clone() {
  4385. return new Moment(this);
  4386. }
  4387. function isAfter(input, units) {
  4388. var localInput = isMoment(input) ? input : createLocal(input);
  4389. if (!(this.isValid() && localInput.isValid())) {
  4390. return false;
  4391. }
  4392. units = normalizeUnits(units) || 'millisecond';
  4393. if (units === 'millisecond') {
  4394. return this.valueOf() > localInput.valueOf();
  4395. } else {
  4396. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  4397. }
  4398. }
  4399. function isBefore(input, units) {
  4400. var localInput = isMoment(input) ? input : createLocal(input);
  4401. if (!(this.isValid() && localInput.isValid())) {
  4402. return false;
  4403. }
  4404. units = normalizeUnits(units) || 'millisecond';
  4405. if (units === 'millisecond') {
  4406. return this.valueOf() < localInput.valueOf();
  4407. } else {
  4408. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  4409. }
  4410. }
  4411. function isBetween(from, to, units, inclusivity) {
  4412. var localFrom = isMoment(from) ? from : createLocal(from),
  4413. localTo = isMoment(to) ? to : createLocal(to);
  4414. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  4415. return false;
  4416. }
  4417. inclusivity = inclusivity || '()';
  4418. return (
  4419. (inclusivity[0] === '('
  4420. ? this.isAfter(localFrom, units)
  4421. : !this.isBefore(localFrom, units)) &&
  4422. (inclusivity[1] === ')'
  4423. ? this.isBefore(localTo, units)
  4424. : !this.isAfter(localTo, units))
  4425. );
  4426. }
  4427. function isSame(input, units) {
  4428. var localInput = isMoment(input) ? input : createLocal(input),
  4429. inputMs;
  4430. if (!(this.isValid() && localInput.isValid())) {
  4431. return false;
  4432. }
  4433. units = normalizeUnits(units) || 'millisecond';
  4434. if (units === 'millisecond') {
  4435. return this.valueOf() === localInput.valueOf();
  4436. } else {
  4437. inputMs = localInput.valueOf();
  4438. return (
  4439. this.clone().startOf(units).valueOf() <= inputMs &&
  4440. inputMs <= this.clone().endOf(units).valueOf()
  4441. );
  4442. }
  4443. }
  4444. function isSameOrAfter(input, units) {
  4445. return this.isSame(input, units) || this.isAfter(input, units);
  4446. }
  4447. function isSameOrBefore(input, units) {
  4448. return this.isSame(input, units) || this.isBefore(input, units);
  4449. }
  4450. function diff(input, units, asFloat) {
  4451. var that, zoneDelta, output;
  4452. if (!this.isValid()) {
  4453. return NaN;
  4454. }
  4455. that = cloneWithOffset(input, this);
  4456. if (!that.isValid()) {
  4457. return NaN;
  4458. }
  4459. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  4460. units = normalizeUnits(units);
  4461. switch (units) {
  4462. case 'year':
  4463. output = monthDiff(this, that) / 12;
  4464. break;
  4465. case 'month':
  4466. output = monthDiff(this, that);
  4467. break;
  4468. case 'quarter':
  4469. output = monthDiff(this, that) / 3;
  4470. break;
  4471. case 'second':
  4472. output = (this - that) / 1e3;
  4473. break; // 1000
  4474. case 'minute':
  4475. output = (this - that) / 6e4;
  4476. break; // 1000 * 60
  4477. case 'hour':
  4478. output = (this - that) / 36e5;
  4479. break; // 1000 * 60 * 60
  4480. case 'day':
  4481. output = (this - that - zoneDelta) / 864e5;
  4482. break; // 1000 * 60 * 60 * 24, negate dst
  4483. case 'week':
  4484. output = (this - that - zoneDelta) / 6048e5;
  4485. break; // 1000 * 60 * 60 * 24 * 7, negate dst
  4486. default:
  4487. output = this - that;
  4488. }
  4489. return asFloat ? output : absFloor(output);
  4490. }
  4491. function monthDiff(a, b) {
  4492. if (a.date() < b.date()) {
  4493. // end-of-month calculations work correct when the start month has more
  4494. // days than the end month.
  4495. return -monthDiff(b, a);
  4496. }
  4497. // difference in months
  4498. var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
  4499. // b is in (anchor - 1 month, anchor + 1 month)
  4500. anchor = a.clone().add(wholeMonthDiff, 'months'),
  4501. anchor2,
  4502. adjust;
  4503. if (b - anchor < 0) {
  4504. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  4505. // linear across the month
  4506. adjust = (b - anchor) / (anchor - anchor2);
  4507. } else {
  4508. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  4509. // linear across the month
  4510. adjust = (b - anchor) / (anchor2 - anchor);
  4511. }
  4512. //check for negative zero, return zero if negative zero
  4513. return -(wholeMonthDiff + adjust) || 0;
  4514. }
  4515. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  4516. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  4517. function toString() {
  4518. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  4519. }
  4520. function toISOString(keepOffset) {
  4521. if (!this.isValid()) {
  4522. return null;
  4523. }
  4524. var utc = keepOffset !== true,
  4525. m = utc ? this.clone().utc() : this;
  4526. if (m.year() < 0 || m.year() > 9999) {
  4527. return formatMoment(
  4528. m,
  4529. utc
  4530. ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
  4531. : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
  4532. );
  4533. }
  4534. if (isFunction(Date.prototype.toISOString)) {
  4535. // native implementation is ~50x faster, use it when we can
  4536. if (utc) {
  4537. return this.toDate().toISOString();
  4538. } else {
  4539. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
  4540. .toISOString()
  4541. .replace('Z', formatMoment(m, 'Z'));
  4542. }
  4543. }
  4544. return formatMoment(
  4545. m,
  4546. utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
  4547. );
  4548. }
  4549. /**
  4550. * Return a human readable representation of a moment that can
  4551. * also be evaluated to get a new moment which is the same
  4552. *
  4553. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  4554. */
  4555. function inspect() {
  4556. if (!this.isValid()) {
  4557. return 'moment.invalid(/* ' + this._i + ' */)';
  4558. }
  4559. var func = 'moment',
  4560. zone = '',
  4561. prefix,
  4562. year,
  4563. datetime,
  4564. suffix;
  4565. if (!this.isLocal()) {
  4566. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  4567. zone = 'Z';
  4568. }
  4569. prefix = '[' + func + '("]';
  4570. year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
  4571. datetime = '-MM-DD[T]HH:mm:ss.SSS';
  4572. suffix = zone + '[")]';
  4573. return this.format(prefix + year + datetime + suffix);
  4574. }
  4575. function format(inputString) {
  4576. if (!inputString) {
  4577. inputString = this.isUtc()
  4578. ? hooks.defaultFormatUtc
  4579. : hooks.defaultFormat;
  4580. }
  4581. var output = formatMoment(this, inputString);
  4582. return this.localeData().postformat(output);
  4583. }
  4584. function from(time, withoutSuffix) {
  4585. if (
  4586. this.isValid() &&
  4587. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  4588. ) {
  4589. return createDuration({ to: this, from: time })
  4590. .locale(this.locale())
  4591. .humanize(!withoutSuffix);
  4592. } else {
  4593. return this.localeData().invalidDate();
  4594. }
  4595. }
  4596. function fromNow(withoutSuffix) {
  4597. return this.from(createLocal(), withoutSuffix);
  4598. }
  4599. function to(time, withoutSuffix) {
  4600. if (
  4601. this.isValid() &&
  4602. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  4603. ) {
  4604. return createDuration({ from: this, to: time })
  4605. .locale(this.locale())
  4606. .humanize(!withoutSuffix);
  4607. } else {
  4608. return this.localeData().invalidDate();
  4609. }
  4610. }
  4611. function toNow(withoutSuffix) {
  4612. return this.to(createLocal(), withoutSuffix);
  4613. }
  4614. // If passed a locale key, it will set the locale for this
  4615. // instance. Otherwise, it will return the locale configuration
  4616. // variables for this instance.
  4617. function locale(key) {
  4618. var newLocaleData;
  4619. if (key === undefined) {
  4620. return this._locale._abbr;
  4621. } else {
  4622. newLocaleData = getLocale(key);
  4623. if (newLocaleData != null) {
  4624. this._locale = newLocaleData;
  4625. }
  4626. return this;
  4627. }
  4628. }
  4629. var lang = deprecate(
  4630. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  4631. function (key) {
  4632. if (key === undefined) {
  4633. return this.localeData();
  4634. } else {
  4635. return this.locale(key);
  4636. }
  4637. }
  4638. );
  4639. function localeData() {
  4640. return this._locale;
  4641. }
  4642. var MS_PER_SECOND = 1000,
  4643. MS_PER_MINUTE = 60 * MS_PER_SECOND,
  4644. MS_PER_HOUR = 60 * MS_PER_MINUTE,
  4645. MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  4646. // actual modulo - handles negative numbers (for dates before 1970):
  4647. function mod$1(dividend, divisor) {
  4648. return ((dividend % divisor) + divisor) % divisor;
  4649. }
  4650. function localStartOfDate(y, m, d) {
  4651. // the date constructor remaps years 0-99 to 1900-1999
  4652. if (y < 100 && y >= 0) {
  4653. // preserve leap years using a full 400 year cycle, then reset
  4654. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  4655. } else {
  4656. return new Date(y, m, d).valueOf();
  4657. }
  4658. }
  4659. function utcStartOfDate(y, m, d) {
  4660. // Date.UTC remaps years 0-99 to 1900-1999
  4661. if (y < 100 && y >= 0) {
  4662. // preserve leap years using a full 400 year cycle, then reset
  4663. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  4664. } else {
  4665. return Date.UTC(y, m, d);
  4666. }
  4667. }
  4668. function startOf(units) {
  4669. var time, startOfDate;
  4670. units = normalizeUnits(units);
  4671. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  4672. return this;
  4673. }
  4674. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  4675. switch (units) {
  4676. case 'year':
  4677. time = startOfDate(this.year(), 0, 1);
  4678. break;
  4679. case 'quarter':
  4680. time = startOfDate(
  4681. this.year(),
  4682. this.month() - (this.month() % 3),
  4683. 1
  4684. );
  4685. break;
  4686. case 'month':
  4687. time = startOfDate(this.year(), this.month(), 1);
  4688. break;
  4689. case 'week':
  4690. time = startOfDate(
  4691. this.year(),
  4692. this.month(),
  4693. this.date() - this.weekday()
  4694. );
  4695. break;
  4696. case 'isoWeek':
  4697. time = startOfDate(
  4698. this.year(),
  4699. this.month(),
  4700. this.date() - (this.isoWeekday() - 1)
  4701. );
  4702. break;
  4703. case 'day':
  4704. case 'date':
  4705. time = startOfDate(this.year(), this.month(), this.date());
  4706. break;
  4707. case 'hour':
  4708. time = this._d.valueOf();
  4709. time -= mod$1(
  4710. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  4711. MS_PER_HOUR
  4712. );
  4713. break;
  4714. case 'minute':
  4715. time = this._d.valueOf();
  4716. time -= mod$1(time, MS_PER_MINUTE);
  4717. break;
  4718. case 'second':
  4719. time = this._d.valueOf();
  4720. time -= mod$1(time, MS_PER_SECOND);
  4721. break;
  4722. }
  4723. this._d.setTime(time);
  4724. hooks.updateOffset(this, true);
  4725. return this;
  4726. }
  4727. function endOf(units) {
  4728. var time, startOfDate;
  4729. units = normalizeUnits(units);
  4730. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  4731. return this;
  4732. }
  4733. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  4734. switch (units) {
  4735. case 'year':
  4736. time = startOfDate(this.year() + 1, 0, 1) - 1;
  4737. break;
  4738. case 'quarter':
  4739. time =
  4740. startOfDate(
  4741. this.year(),
  4742. this.month() - (this.month() % 3) + 3,
  4743. 1
  4744. ) - 1;
  4745. break;
  4746. case 'month':
  4747. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  4748. break;
  4749. case 'week':
  4750. time =
  4751. startOfDate(
  4752. this.year(),
  4753. this.month(),
  4754. this.date() - this.weekday() + 7
  4755. ) - 1;
  4756. break;
  4757. case 'isoWeek':
  4758. time =
  4759. startOfDate(
  4760. this.year(),
  4761. this.month(),
  4762. this.date() - (this.isoWeekday() - 1) + 7
  4763. ) - 1;
  4764. break;
  4765. case 'day':
  4766. case 'date':
  4767. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  4768. break;
  4769. case 'hour':
  4770. time = this._d.valueOf();
  4771. time +=
  4772. MS_PER_HOUR -
  4773. mod$1(
  4774. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  4775. MS_PER_HOUR
  4776. ) -
  4777. 1;
  4778. break;
  4779. case 'minute':
  4780. time = this._d.valueOf();
  4781. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  4782. break;
  4783. case 'second':
  4784. time = this._d.valueOf();
  4785. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  4786. break;
  4787. }
  4788. this._d.setTime(time);
  4789. hooks.updateOffset(this, true);
  4790. return this;
  4791. }
  4792. function valueOf() {
  4793. return this._d.valueOf() - (this._offset || 0) * 60000;
  4794. }
  4795. function unix() {
  4796. return Math.floor(this.valueOf() / 1000);
  4797. }
  4798. function toDate() {
  4799. return new Date(this.valueOf());
  4800. }
  4801. function toArray() {
  4802. var m = this;
  4803. return [
  4804. m.year(),
  4805. m.month(),
  4806. m.date(),
  4807. m.hour(),
  4808. m.minute(),
  4809. m.second(),
  4810. m.millisecond(),
  4811. ];
  4812. }
  4813. function toObject() {
  4814. var m = this;
  4815. return {
  4816. years: m.year(),
  4817. months: m.month(),
  4818. date: m.date(),
  4819. hours: m.hours(),
  4820. minutes: m.minutes(),
  4821. seconds: m.seconds(),
  4822. milliseconds: m.milliseconds(),
  4823. };
  4824. }
  4825. function toJSON() {
  4826. // new Date(NaN).toJSON() === null
  4827. return this.isValid() ? this.toISOString() : null;
  4828. }
  4829. function isValid$2() {
  4830. return isValid(this);
  4831. }
  4832. function parsingFlags() {
  4833. return extend({}, getParsingFlags(this));
  4834. }
  4835. function invalidAt() {
  4836. return getParsingFlags(this).overflow;
  4837. }
  4838. function creationData() {
  4839. return {
  4840. input: this._i,
  4841. format: this._f,
  4842. locale: this._locale,
  4843. isUTC: this._isUTC,
  4844. strict: this._strict,
  4845. };
  4846. }
  4847. addFormatToken('N', 0, 0, 'eraAbbr');
  4848. addFormatToken('NN', 0, 0, 'eraAbbr');
  4849. addFormatToken('NNN', 0, 0, 'eraAbbr');
  4850. addFormatToken('NNNN', 0, 0, 'eraName');
  4851. addFormatToken('NNNNN', 0, 0, 'eraNarrow');
  4852. addFormatToken('y', ['y', 1], 'yo', 'eraYear');
  4853. addFormatToken('y', ['yy', 2], 0, 'eraYear');
  4854. addFormatToken('y', ['yyy', 3], 0, 'eraYear');
  4855. addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
  4856. addRegexToken('N', matchEraAbbr);
  4857. addRegexToken('NN', matchEraAbbr);
  4858. addRegexToken('NNN', matchEraAbbr);
  4859. addRegexToken('NNNN', matchEraName);
  4860. addRegexToken('NNNNN', matchEraNarrow);
  4861. addParseToken(
  4862. ['N', 'NN', 'NNN', 'NNNN', 'NNNNN'],
  4863. function (input, array, config, token) {
  4864. var era = config._locale.erasParse(input, token, config._strict);
  4865. if (era) {
  4866. getParsingFlags(config).era = era;
  4867. } else {
  4868. getParsingFlags(config).invalidEra = input;
  4869. }
  4870. }
  4871. );
  4872. addRegexToken('y', matchUnsigned);
  4873. addRegexToken('yy', matchUnsigned);
  4874. addRegexToken('yyy', matchUnsigned);
  4875. addRegexToken('yyyy', matchUnsigned);
  4876. addRegexToken('yo', matchEraYearOrdinal);
  4877. addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
  4878. addParseToken(['yo'], function (input, array, config, token) {
  4879. var match;
  4880. if (config._locale._eraYearOrdinalRegex) {
  4881. match = input.match(config._locale._eraYearOrdinalRegex);
  4882. }
  4883. if (config._locale.eraYearOrdinalParse) {
  4884. array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
  4885. } else {
  4886. array[YEAR] = parseInt(input, 10);
  4887. }
  4888. });
  4889. function localeEras(m, format) {
  4890. var i,
  4891. l,
  4892. date,
  4893. eras = this._eras || getLocale('en')._eras;
  4894. for (i = 0, l = eras.length; i < l; ++i) {
  4895. switch (typeof eras[i].since) {
  4896. case 'string':
  4897. // truncate time
  4898. date = hooks(eras[i].since).startOf('day');
  4899. eras[i].since = date.valueOf();
  4900. break;
  4901. }
  4902. switch (typeof eras[i].until) {
  4903. case 'undefined':
  4904. eras[i].until = +Infinity;
  4905. break;
  4906. case 'string':
  4907. // truncate time
  4908. date = hooks(eras[i].until).startOf('day').valueOf();
  4909. eras[i].until = date.valueOf();
  4910. break;
  4911. }
  4912. }
  4913. return eras;
  4914. }
  4915. function localeErasParse(eraName, format, strict) {
  4916. var i,
  4917. l,
  4918. eras = this.eras(),
  4919. name,
  4920. abbr,
  4921. narrow;
  4922. eraName = eraName.toUpperCase();
  4923. for (i = 0, l = eras.length; i < l; ++i) {
  4924. name = eras[i].name.toUpperCase();
  4925. abbr = eras[i].abbr.toUpperCase();
  4926. narrow = eras[i].narrow.toUpperCase();
  4927. if (strict) {
  4928. switch (format) {
  4929. case 'N':
  4930. case 'NN':
  4931. case 'NNN':
  4932. if (abbr === eraName) {
  4933. return eras[i];
  4934. }
  4935. break;
  4936. case 'NNNN':
  4937. if (name === eraName) {
  4938. return eras[i];
  4939. }
  4940. break;
  4941. case 'NNNNN':
  4942. if (narrow === eraName) {
  4943. return eras[i];
  4944. }
  4945. break;
  4946. }
  4947. } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
  4948. return eras[i];
  4949. }
  4950. }
  4951. }
  4952. function localeErasConvertYear(era, year) {
  4953. var dir = era.since <= era.until ? +1 : -1;
  4954. if (year === undefined) {
  4955. return hooks(era.since).year();
  4956. } else {
  4957. return hooks(era.since).year() + (year - era.offset) * dir;
  4958. }
  4959. }
  4960. function getEraName() {
  4961. var i,
  4962. l,
  4963. val,
  4964. eras = this.localeData().eras();
  4965. for (i = 0, l = eras.length; i < l; ++i) {
  4966. // truncate time
  4967. val = this.clone().startOf('day').valueOf();
  4968. if (eras[i].since <= val && val <= eras[i].until) {
  4969. return eras[i].name;
  4970. }
  4971. if (eras[i].until <= val && val <= eras[i].since) {
  4972. return eras[i].name;
  4973. }
  4974. }
  4975. return '';
  4976. }
  4977. function getEraNarrow() {
  4978. var i,
  4979. l,
  4980. val,
  4981. eras = this.localeData().eras();
  4982. for (i = 0, l = eras.length; i < l; ++i) {
  4983. // truncate time
  4984. val = this.clone().startOf('day').valueOf();
  4985. if (eras[i].since <= val && val <= eras[i].until) {
  4986. return eras[i].narrow;
  4987. }
  4988. if (eras[i].until <= val && val <= eras[i].since) {
  4989. return eras[i].narrow;
  4990. }
  4991. }
  4992. return '';
  4993. }
  4994. function getEraAbbr() {
  4995. var i,
  4996. l,
  4997. val,
  4998. eras = this.localeData().eras();
  4999. for (i = 0, l = eras.length; i < l; ++i) {
  5000. // truncate time
  5001. val = this.clone().startOf('day').valueOf();
  5002. if (eras[i].since <= val && val <= eras[i].until) {
  5003. return eras[i].abbr;
  5004. }
  5005. if (eras[i].until <= val && val <= eras[i].since) {
  5006. return eras[i].abbr;
  5007. }
  5008. }
  5009. return '';
  5010. }
  5011. function getEraYear() {
  5012. var i,
  5013. l,
  5014. dir,
  5015. val,
  5016. eras = this.localeData().eras();
  5017. for (i = 0, l = eras.length; i < l; ++i) {
  5018. dir = eras[i].since <= eras[i].until ? +1 : -1;
  5019. // truncate time
  5020. val = this.clone().startOf('day').valueOf();
  5021. if (
  5022. (eras[i].since <= val && val <= eras[i].until) ||
  5023. (eras[i].until <= val && val <= eras[i].since)
  5024. ) {
  5025. return (
  5026. (this.year() - hooks(eras[i].since).year()) * dir +
  5027. eras[i].offset
  5028. );
  5029. }
  5030. }
  5031. return this.year();
  5032. }
  5033. function erasNameRegex(isStrict) {
  5034. if (!hasOwnProp(this, '_erasNameRegex')) {
  5035. computeErasParse.call(this);
  5036. }
  5037. return isStrict ? this._erasNameRegex : this._erasRegex;
  5038. }
  5039. function erasAbbrRegex(isStrict) {
  5040. if (!hasOwnProp(this, '_erasAbbrRegex')) {
  5041. computeErasParse.call(this);
  5042. }
  5043. return isStrict ? this._erasAbbrRegex : this._erasRegex;
  5044. }
  5045. function erasNarrowRegex(isStrict) {
  5046. if (!hasOwnProp(this, '_erasNarrowRegex')) {
  5047. computeErasParse.call(this);
  5048. }
  5049. return isStrict ? this._erasNarrowRegex : this._erasRegex;
  5050. }
  5051. function matchEraAbbr(isStrict, locale) {
  5052. return locale.erasAbbrRegex(isStrict);
  5053. }
  5054. function matchEraName(isStrict, locale) {
  5055. return locale.erasNameRegex(isStrict);
  5056. }
  5057. function matchEraNarrow(isStrict, locale) {
  5058. return locale.erasNarrowRegex(isStrict);
  5059. }
  5060. function matchEraYearOrdinal(isStrict, locale) {
  5061. return locale._eraYearOrdinalRegex || matchUnsigned;
  5062. }
  5063. function computeErasParse() {
  5064. var abbrPieces = [],
  5065. namePieces = [],
  5066. narrowPieces = [],
  5067. mixedPieces = [],
  5068. i,
  5069. l,
  5070. eras = this.eras();
  5071. for (i = 0, l = eras.length; i < l; ++i) {
  5072. namePieces.push(regexEscape(eras[i].name));
  5073. abbrPieces.push(regexEscape(eras[i].abbr));
  5074. narrowPieces.push(regexEscape(eras[i].narrow));
  5075. mixedPieces.push(regexEscape(eras[i].name));
  5076. mixedPieces.push(regexEscape(eras[i].abbr));
  5077. mixedPieces.push(regexEscape(eras[i].narrow));
  5078. }
  5079. this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  5080. this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
  5081. this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
  5082. this._erasNarrowRegex = new RegExp(
  5083. '^(' + narrowPieces.join('|') + ')',
  5084. 'i'
  5085. );
  5086. }
  5087. // FORMATTING
  5088. addFormatToken(0, ['gg', 2], 0, function () {
  5089. return this.weekYear() % 100;
  5090. });
  5091. addFormatToken(0, ['GG', 2], 0, function () {
  5092. return this.isoWeekYear() % 100;
  5093. });
  5094. function addWeekYearFormatToken(token, getter) {
  5095. addFormatToken(0, [token, token.length], 0, getter);
  5096. }
  5097. addWeekYearFormatToken('gggg', 'weekYear');
  5098. addWeekYearFormatToken('ggggg', 'weekYear');
  5099. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  5100. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  5101. // ALIASES
  5102. addUnitAlias('weekYear', 'gg');
  5103. addUnitAlias('isoWeekYear', 'GG');
  5104. // PRIORITY
  5105. addUnitPriority('weekYear', 1);
  5106. addUnitPriority('isoWeekYear', 1);
  5107. // PARSING
  5108. addRegexToken('G', matchSigned);
  5109. addRegexToken('g', matchSigned);
  5110. addRegexToken('GG', match1to2, match2);
  5111. addRegexToken('gg', match1to2, match2);
  5112. addRegexToken('GGGG', match1to4, match4);
  5113. addRegexToken('gggg', match1to4, match4);
  5114. addRegexToken('GGGGG', match1to6, match6);
  5115. addRegexToken('ggggg', match1to6, match6);
  5116. addWeekParseToken(
  5117. ['gggg', 'ggggg', 'GGGG', 'GGGGG'],
  5118. function (input, week, config, token) {
  5119. week[token.substr(0, 2)] = toInt(input);
  5120. }
  5121. );
  5122. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  5123. week[token] = hooks.parseTwoDigitYear(input);
  5124. });
  5125. // MOMENTS
  5126. function getSetWeekYear(input) {
  5127. return getSetWeekYearHelper.call(
  5128. this,
  5129. input,
  5130. this.week(),
  5131. this.weekday(),
  5132. this.localeData()._week.dow,
  5133. this.localeData()._week.doy
  5134. );
  5135. }
  5136. function getSetISOWeekYear(input) {
  5137. return getSetWeekYearHelper.call(
  5138. this,
  5139. input,
  5140. this.isoWeek(),
  5141. this.isoWeekday(),
  5142. 1,
  5143. 4
  5144. );
  5145. }
  5146. function getISOWeeksInYear() {
  5147. return weeksInYear(this.year(), 1, 4);
  5148. }
  5149. function getISOWeeksInISOWeekYear() {
  5150. return weeksInYear(this.isoWeekYear(), 1, 4);
  5151. }
  5152. function getWeeksInYear() {
  5153. var weekInfo = this.localeData()._week;
  5154. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  5155. }
  5156. function getWeeksInWeekYear() {
  5157. var weekInfo = this.localeData()._week;
  5158. return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
  5159. }
  5160. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  5161. var weeksTarget;
  5162. if (input == null) {
  5163. return weekOfYear(this, dow, doy).year;
  5164. } else {
  5165. weeksTarget = weeksInYear(input, dow, doy);
  5166. if (week > weeksTarget) {
  5167. week = weeksTarget;
  5168. }
  5169. return setWeekAll.call(this, input, week, weekday, dow, doy);
  5170. }
  5171. }
  5172. function setWeekAll(weekYear, week, weekday, dow, doy) {
  5173. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  5174. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  5175. this.year(date.getUTCFullYear());
  5176. this.month(date.getUTCMonth());
  5177. this.date(date.getUTCDate());
  5178. return this;
  5179. }
  5180. // FORMATTING
  5181. addFormatToken('Q', 0, 'Qo', 'quarter');
  5182. // ALIASES
  5183. addUnitAlias('quarter', 'Q');
  5184. // PRIORITY
  5185. addUnitPriority('quarter', 7);
  5186. // PARSING
  5187. addRegexToken('Q', match1);
  5188. addParseToken('Q', function (input, array) {
  5189. array[MONTH] = (toInt(input) - 1) * 3;
  5190. });
  5191. // MOMENTS
  5192. function getSetQuarter(input) {
  5193. return input == null
  5194. ? Math.ceil((this.month() + 1) / 3)
  5195. : this.month((input - 1) * 3 + (this.month() % 3));
  5196. }
  5197. // FORMATTING
  5198. addFormatToken('D', ['DD', 2], 'Do', 'date');
  5199. // ALIASES
  5200. addUnitAlias('date', 'D');
  5201. // PRIORITY
  5202. addUnitPriority('date', 9);
  5203. // PARSING
  5204. addRegexToken('D', match1to2);
  5205. addRegexToken('DD', match1to2, match2);
  5206. addRegexToken('Do', function (isStrict, locale) {
  5207. // TODO: Remove "ordinalParse" fallback in next major release.
  5208. return isStrict
  5209. ? locale._dayOfMonthOrdinalParse || locale._ordinalParse
  5210. : locale._dayOfMonthOrdinalParseLenient;
  5211. });
  5212. addParseToken(['D', 'DD'], DATE);
  5213. addParseToken('Do', function (input, array) {
  5214. array[DATE] = toInt(input.match(match1to2)[0]);
  5215. });
  5216. // MOMENTS
  5217. var getSetDayOfMonth = makeGetSet('Date', true);
  5218. // FORMATTING
  5219. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  5220. // ALIASES
  5221. addUnitAlias('dayOfYear', 'DDD');
  5222. // PRIORITY
  5223. addUnitPriority('dayOfYear', 4);
  5224. // PARSING
  5225. addRegexToken('DDD', match1to3);
  5226. addRegexToken('DDDD', match3);
  5227. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  5228. config._dayOfYear = toInt(input);
  5229. });
  5230. // HELPERS
  5231. // MOMENTS
  5232. function getSetDayOfYear(input) {
  5233. var dayOfYear =
  5234. Math.round(
  5235. (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
  5236. ) + 1;
  5237. return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
  5238. }
  5239. // FORMATTING
  5240. addFormatToken('m', ['mm', 2], 0, 'minute');
  5241. // ALIASES
  5242. addUnitAlias('minute', 'm');
  5243. // PRIORITY
  5244. addUnitPriority('minute', 14);
  5245. // PARSING
  5246. addRegexToken('m', match1to2);
  5247. addRegexToken('mm', match1to2, match2);
  5248. addParseToken(['m', 'mm'], MINUTE);
  5249. // MOMENTS
  5250. var getSetMinute = makeGetSet('Minutes', false);
  5251. // FORMATTING
  5252. addFormatToken('s', ['ss', 2], 0, 'second');
  5253. // ALIASES
  5254. addUnitAlias('second', 's');
  5255. // PRIORITY
  5256. addUnitPriority('second', 15);
  5257. // PARSING
  5258. addRegexToken('s', match1to2);
  5259. addRegexToken('ss', match1to2, match2);
  5260. addParseToken(['s', 'ss'], SECOND);
  5261. // MOMENTS
  5262. var getSetSecond = makeGetSet('Seconds', false);
  5263. // FORMATTING
  5264. addFormatToken('S', 0, 0, function () {
  5265. return ~~(this.millisecond() / 100);
  5266. });
  5267. addFormatToken(0, ['SS', 2], 0, function () {
  5268. return ~~(this.millisecond() / 10);
  5269. });
  5270. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  5271. addFormatToken(0, ['SSSS', 4], 0, function () {
  5272. return this.millisecond() * 10;
  5273. });
  5274. addFormatToken(0, ['SSSSS', 5], 0, function () {
  5275. return this.millisecond() * 100;
  5276. });
  5277. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  5278. return this.millisecond() * 1000;
  5279. });
  5280. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  5281. return this.millisecond() * 10000;
  5282. });
  5283. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  5284. return this.millisecond() * 100000;
  5285. });
  5286. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  5287. return this.millisecond() * 1000000;
  5288. });
  5289. // ALIASES
  5290. addUnitAlias('millisecond', 'ms');
  5291. // PRIORITY
  5292. addUnitPriority('millisecond', 16);
  5293. // PARSING
  5294. addRegexToken('S', match1to3, match1);
  5295. addRegexToken('SS', match1to3, match2);
  5296. addRegexToken('SSS', match1to3, match3);
  5297. var token, getSetMillisecond;
  5298. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  5299. addRegexToken(token, matchUnsigned);
  5300. }
  5301. function parseMs(input, array) {
  5302. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  5303. }
  5304. for (token = 'S'; token.length <= 9; token += 'S') {
  5305. addParseToken(token, parseMs);
  5306. }
  5307. getSetMillisecond = makeGetSet('Milliseconds', false);
  5308. // FORMATTING
  5309. addFormatToken('z', 0, 0, 'zoneAbbr');
  5310. addFormatToken('zz', 0, 0, 'zoneName');
  5311. // MOMENTS
  5312. function getZoneAbbr() {
  5313. return this._isUTC ? 'UTC' : '';
  5314. }
  5315. function getZoneName() {
  5316. return this._isUTC ? 'Coordinated Universal Time' : '';
  5317. }
  5318. var proto = Moment.prototype;
  5319. proto.add = add;
  5320. proto.calendar = calendar$1;
  5321. proto.clone = clone;
  5322. proto.diff = diff;
  5323. proto.endOf = endOf;
  5324. proto.format = format;
  5325. proto.from = from;
  5326. proto.fromNow = fromNow;
  5327. proto.to = to;
  5328. proto.toNow = toNow;
  5329. proto.get = stringGet;
  5330. proto.invalidAt = invalidAt;
  5331. proto.isAfter = isAfter;
  5332. proto.isBefore = isBefore;
  5333. proto.isBetween = isBetween;
  5334. proto.isSame = isSame;
  5335. proto.isSameOrAfter = isSameOrAfter;
  5336. proto.isSameOrBefore = isSameOrBefore;
  5337. proto.isValid = isValid$2;
  5338. proto.lang = lang;
  5339. proto.locale = locale;
  5340. proto.localeData = localeData;
  5341. proto.max = prototypeMax;
  5342. proto.min = prototypeMin;
  5343. proto.parsingFlags = parsingFlags;
  5344. proto.set = stringSet;
  5345. proto.startOf = startOf;
  5346. proto.subtract = subtract;
  5347. proto.toArray = toArray;
  5348. proto.toObject = toObject;
  5349. proto.toDate = toDate;
  5350. proto.toISOString = toISOString;
  5351. proto.inspect = inspect;
  5352. if (typeof Symbol !== 'undefined' && Symbol.for != null) {
  5353. proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
  5354. return 'Moment<' + this.format() + '>';
  5355. };
  5356. }
  5357. proto.toJSON = toJSON;
  5358. proto.toString = toString;
  5359. proto.unix = unix;
  5360. proto.valueOf = valueOf;
  5361. proto.creationData = creationData;
  5362. proto.eraName = getEraName;
  5363. proto.eraNarrow = getEraNarrow;
  5364. proto.eraAbbr = getEraAbbr;
  5365. proto.eraYear = getEraYear;
  5366. proto.year = getSetYear;
  5367. proto.isLeapYear = getIsLeapYear;
  5368. proto.weekYear = getSetWeekYear;
  5369. proto.isoWeekYear = getSetISOWeekYear;
  5370. proto.quarter = proto.quarters = getSetQuarter;
  5371. proto.month = getSetMonth;
  5372. proto.daysInMonth = getDaysInMonth;
  5373. proto.week = proto.weeks = getSetWeek;
  5374. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  5375. proto.weeksInYear = getWeeksInYear;
  5376. proto.weeksInWeekYear = getWeeksInWeekYear;
  5377. proto.isoWeeksInYear = getISOWeeksInYear;
  5378. proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
  5379. proto.date = getSetDayOfMonth;
  5380. proto.day = proto.days = getSetDayOfWeek;
  5381. proto.weekday = getSetLocaleDayOfWeek;
  5382. proto.isoWeekday = getSetISODayOfWeek;
  5383. proto.dayOfYear = getSetDayOfYear;
  5384. proto.hour = proto.hours = getSetHour;
  5385. proto.minute = proto.minutes = getSetMinute;
  5386. proto.second = proto.seconds = getSetSecond;
  5387. proto.millisecond = proto.milliseconds = getSetMillisecond;
  5388. proto.utcOffset = getSetOffset;
  5389. proto.utc = setOffsetToUTC;
  5390. proto.local = setOffsetToLocal;
  5391. proto.parseZone = setOffsetToParsedOffset;
  5392. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  5393. proto.isDST = isDaylightSavingTime;
  5394. proto.isLocal = isLocal;
  5395. proto.isUtcOffset = isUtcOffset;
  5396. proto.isUtc = isUtc;
  5397. proto.isUTC = isUtc;
  5398. proto.zoneAbbr = getZoneAbbr;
  5399. proto.zoneName = getZoneName;
  5400. proto.dates = deprecate(
  5401. 'dates accessor is deprecated. Use date instead.',
  5402. getSetDayOfMonth
  5403. );
  5404. proto.months = deprecate(
  5405. 'months accessor is deprecated. Use month instead',
  5406. getSetMonth
  5407. );
  5408. proto.years = deprecate(
  5409. 'years accessor is deprecated. Use year instead',
  5410. getSetYear
  5411. );
  5412. proto.zone = deprecate(
  5413. 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
  5414. getSetZone
  5415. );
  5416. proto.isDSTShifted = deprecate(
  5417. 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
  5418. isDaylightSavingTimeShifted
  5419. );
  5420. function createUnix(input) {
  5421. return createLocal(input * 1000);
  5422. }
  5423. function createInZone() {
  5424. return createLocal.apply(null, arguments).parseZone();
  5425. }
  5426. function preParsePostFormat(string) {
  5427. return string;
  5428. }
  5429. var proto$1 = Locale.prototype;
  5430. proto$1.calendar = calendar;
  5431. proto$1.longDateFormat = longDateFormat;
  5432. proto$1.invalidDate = invalidDate;
  5433. proto$1.ordinal = ordinal;
  5434. proto$1.preparse = preParsePostFormat;
  5435. proto$1.postformat = preParsePostFormat;
  5436. proto$1.relativeTime = relativeTime;
  5437. proto$1.pastFuture = pastFuture;
  5438. proto$1.set = set;
  5439. proto$1.eras = localeEras;
  5440. proto$1.erasParse = localeErasParse;
  5441. proto$1.erasConvertYear = localeErasConvertYear;
  5442. proto$1.erasAbbrRegex = erasAbbrRegex;
  5443. proto$1.erasNameRegex = erasNameRegex;
  5444. proto$1.erasNarrowRegex = erasNarrowRegex;
  5445. proto$1.months = localeMonths;
  5446. proto$1.monthsShort = localeMonthsShort;
  5447. proto$1.monthsParse = localeMonthsParse;
  5448. proto$1.monthsRegex = monthsRegex;
  5449. proto$1.monthsShortRegex = monthsShortRegex;
  5450. proto$1.week = localeWeek;
  5451. proto$1.firstDayOfYear = localeFirstDayOfYear;
  5452. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  5453. proto$1.weekdays = localeWeekdays;
  5454. proto$1.weekdaysMin = localeWeekdaysMin;
  5455. proto$1.weekdaysShort = localeWeekdaysShort;
  5456. proto$1.weekdaysParse = localeWeekdaysParse;
  5457. proto$1.weekdaysRegex = weekdaysRegex;
  5458. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  5459. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  5460. proto$1.isPM = localeIsPM;
  5461. proto$1.meridiem = localeMeridiem;
  5462. function get$1(format, index, field, setter) {
  5463. var locale = getLocale(),
  5464. utc = createUTC().set(setter, index);
  5465. return locale[field](utc, format);
  5466. }
  5467. function listMonthsImpl(format, index, field) {
  5468. if (isNumber(format)) {
  5469. index = format;
  5470. format = undefined;
  5471. }
  5472. format = format || '';
  5473. if (index != null) {
  5474. return get$1(format, index, field, 'month');
  5475. }
  5476. var i,
  5477. out = [];
  5478. for (i = 0; i < 12; i++) {
  5479. out[i] = get$1(format, i, field, 'month');
  5480. }
  5481. return out;
  5482. }
  5483. // ()
  5484. // (5)
  5485. // (fmt, 5)
  5486. // (fmt)
  5487. // (true)
  5488. // (true, 5)
  5489. // (true, fmt, 5)
  5490. // (true, fmt)
  5491. function listWeekdaysImpl(localeSorted, format, index, field) {
  5492. if (typeof localeSorted === 'boolean') {
  5493. if (isNumber(format)) {
  5494. index = format;
  5495. format = undefined;
  5496. }
  5497. format = format || '';
  5498. } else {
  5499. format = localeSorted;
  5500. index = format;
  5501. localeSorted = false;
  5502. if (isNumber(format)) {
  5503. index = format;
  5504. format = undefined;
  5505. }
  5506. format = format || '';
  5507. }
  5508. var locale = getLocale(),
  5509. shift = localeSorted ? locale._week.dow : 0,
  5510. i,
  5511. out = [];
  5512. if (index != null) {
  5513. return get$1(format, (index + shift) % 7, field, 'day');
  5514. }
  5515. for (i = 0; i < 7; i++) {
  5516. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  5517. }
  5518. return out;
  5519. }
  5520. function listMonths(format, index) {
  5521. return listMonthsImpl(format, index, 'months');
  5522. }
  5523. function listMonthsShort(format, index) {
  5524. return listMonthsImpl(format, index, 'monthsShort');
  5525. }
  5526. function listWeekdays(localeSorted, format, index) {
  5527. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  5528. }
  5529. function listWeekdaysShort(localeSorted, format, index) {
  5530. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  5531. }
  5532. function listWeekdaysMin(localeSorted, format, index) {
  5533. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  5534. }
  5535. getSetGlobalLocale('en', {
  5536. eras: [
  5537. {
  5538. since: '0001-01-01',
  5539. until: +Infinity,
  5540. offset: 1,
  5541. name: 'Anno Domini',
  5542. narrow: 'AD',
  5543. abbr: 'AD',
  5544. },
  5545. {
  5546. since: '0000-12-31',
  5547. until: -Infinity,
  5548. offset: 1,
  5549. name: 'Before Christ',
  5550. narrow: 'BC',
  5551. abbr: 'BC',
  5552. },
  5553. ],
  5554. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  5555. ordinal: function (number) {
  5556. var b = number % 10,
  5557. output =
  5558. toInt((number % 100) / 10) === 1
  5559. ? 'th'
  5560. : b === 1
  5561. ? 'st'
  5562. : b === 2
  5563. ? 'nd'
  5564. : b === 3
  5565. ? 'rd'
  5566. : 'th';
  5567. return number + output;
  5568. },
  5569. });
  5570. // Side effect imports
  5571. hooks.lang = deprecate(
  5572. 'moment.lang is deprecated. Use moment.locale instead.',
  5573. getSetGlobalLocale
  5574. );
  5575. hooks.langData = deprecate(
  5576. 'moment.langData is deprecated. Use moment.localeData instead.',
  5577. getLocale
  5578. );
  5579. var mathAbs = Math.abs;
  5580. function abs() {
  5581. var data = this._data;
  5582. this._milliseconds = mathAbs(this._milliseconds);
  5583. this._days = mathAbs(this._days);
  5584. this._months = mathAbs(this._months);
  5585. data.milliseconds = mathAbs(data.milliseconds);
  5586. data.seconds = mathAbs(data.seconds);
  5587. data.minutes = mathAbs(data.minutes);
  5588. data.hours = mathAbs(data.hours);
  5589. data.months = mathAbs(data.months);
  5590. data.years = mathAbs(data.years);
  5591. return this;
  5592. }
  5593. function addSubtract$1(duration, input, value, direction) {
  5594. var other = createDuration(input, value);
  5595. duration._milliseconds += direction * other._milliseconds;
  5596. duration._days += direction * other._days;
  5597. duration._months += direction * other._months;
  5598. return duration._bubble();
  5599. }
  5600. // supports only 2.0-style add(1, 's') or add(duration)
  5601. function add$1(input, value) {
  5602. return addSubtract$1(this, input, value, 1);
  5603. }
  5604. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  5605. function subtract$1(input, value) {
  5606. return addSubtract$1(this, input, value, -1);
  5607. }
  5608. function absCeil(number) {
  5609. if (number < 0) {
  5610. return Math.floor(number);
  5611. } else {
  5612. return Math.ceil(number);
  5613. }
  5614. }
  5615. function bubble() {
  5616. var milliseconds = this._milliseconds,
  5617. days = this._days,
  5618. months = this._months,
  5619. data = this._data,
  5620. seconds,
  5621. minutes,
  5622. hours,
  5623. years,
  5624. monthsFromDays;
  5625. // if we have a mix of positive and negative values, bubble down first
  5626. // check: https://github.com/moment/moment/issues/2166
  5627. if (
  5628. !(
  5629. (milliseconds >= 0 && days >= 0 && months >= 0) ||
  5630. (milliseconds <= 0 && days <= 0 && months <= 0)
  5631. )
  5632. ) {
  5633. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  5634. days = 0;
  5635. months = 0;
  5636. }
  5637. // The following code bubbles up values, see the tests for
  5638. // examples of what that means.
  5639. data.milliseconds = milliseconds % 1000;
  5640. seconds = absFloor(milliseconds / 1000);
  5641. data.seconds = seconds % 60;
  5642. minutes = absFloor(seconds / 60);
  5643. data.minutes = minutes % 60;
  5644. hours = absFloor(minutes / 60);
  5645. data.hours = hours % 24;
  5646. days += absFloor(hours / 24);
  5647. // convert days to months
  5648. monthsFromDays = absFloor(daysToMonths(days));
  5649. months += monthsFromDays;
  5650. days -= absCeil(monthsToDays(monthsFromDays));
  5651. // 12 months -> 1 year
  5652. years = absFloor(months / 12);
  5653. months %= 12;
  5654. data.days = days;
  5655. data.months = months;
  5656. data.years = years;
  5657. return this;
  5658. }
  5659. function daysToMonths(days) {
  5660. // 400 years have 146097 days (taking into account leap year rules)
  5661. // 400 years have 12 months === 4800
  5662. return (days * 4800) / 146097;
  5663. }
  5664. function monthsToDays(months) {
  5665. // the reverse of daysToMonths
  5666. return (months * 146097) / 4800;
  5667. }
  5668. function as(units) {
  5669. if (!this.isValid()) {
  5670. return NaN;
  5671. }
  5672. var days,
  5673. months,
  5674. milliseconds = this._milliseconds;
  5675. units = normalizeUnits(units);
  5676. if (units === 'month' || units === 'quarter' || units === 'year') {
  5677. days = this._days + milliseconds / 864e5;
  5678. months = this._months + daysToMonths(days);
  5679. switch (units) {
  5680. case 'month':
  5681. return months;
  5682. case 'quarter':
  5683. return months / 3;
  5684. case 'year':
  5685. return months / 12;
  5686. }
  5687. } else {
  5688. // handle milliseconds separately because of floating point math errors (issue #1867)
  5689. days = this._days + Math.round(monthsToDays(this._months));
  5690. switch (units) {
  5691. case 'week':
  5692. return days / 7 + milliseconds / 6048e5;
  5693. case 'day':
  5694. return days + milliseconds / 864e5;
  5695. case 'hour':
  5696. return days * 24 + milliseconds / 36e5;
  5697. case 'minute':
  5698. return days * 1440 + milliseconds / 6e4;
  5699. case 'second':
  5700. return days * 86400 + milliseconds / 1000;
  5701. // Math.floor prevents floating point math errors here
  5702. case 'millisecond':
  5703. return Math.floor(days * 864e5) + milliseconds;
  5704. default:
  5705. throw new Error('Unknown unit ' + units);
  5706. }
  5707. }
  5708. }
  5709. // TODO: Use this.as('ms')?
  5710. function valueOf$1() {
  5711. if (!this.isValid()) {
  5712. return NaN;
  5713. }
  5714. return (
  5715. this._milliseconds +
  5716. this._days * 864e5 +
  5717. (this._months % 12) * 2592e6 +
  5718. toInt(this._months / 12) * 31536e6
  5719. );
  5720. }
  5721. function makeAs(alias) {
  5722. return function () {
  5723. return this.as(alias);
  5724. };
  5725. }
  5726. var asMilliseconds = makeAs('ms'),
  5727. asSeconds = makeAs('s'),
  5728. asMinutes = makeAs('m'),
  5729. asHours = makeAs('h'),
  5730. asDays = makeAs('d'),
  5731. asWeeks = makeAs('w'),
  5732. asMonths = makeAs('M'),
  5733. asQuarters = makeAs('Q'),
  5734. asYears = makeAs('y');
  5735. function clone$1() {
  5736. return createDuration(this);
  5737. }
  5738. function get$2(units) {
  5739. units = normalizeUnits(units);
  5740. return this.isValid() ? this[units + 's']() : NaN;
  5741. }
  5742. function makeGetter(name) {
  5743. return function () {
  5744. return this.isValid() ? this._data[name] : NaN;
  5745. };
  5746. }
  5747. var milliseconds = makeGetter('milliseconds'),
  5748. seconds = makeGetter('seconds'),
  5749. minutes = makeGetter('minutes'),
  5750. hours = makeGetter('hours'),
  5751. days = makeGetter('days'),
  5752. months = makeGetter('months'),
  5753. years = makeGetter('years');
  5754. function weeks() {
  5755. return absFloor(this.days() / 7);
  5756. }
  5757. var round = Math.round,
  5758. thresholds = {
  5759. ss: 44, // a few seconds to seconds
  5760. s: 45, // seconds to minute
  5761. m: 45, // minutes to hour
  5762. h: 22, // hours to day
  5763. d: 26, // days to month/week
  5764. w: null, // weeks to month
  5765. M: 11, // months to year
  5766. };
  5767. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  5768. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  5769. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  5770. }
  5771. function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
  5772. var duration = createDuration(posNegDuration).abs(),
  5773. seconds = round(duration.as('s')),
  5774. minutes = round(duration.as('m')),
  5775. hours = round(duration.as('h')),
  5776. days = round(duration.as('d')),
  5777. months = round(duration.as('M')),
  5778. weeks = round(duration.as('w')),
  5779. years = round(duration.as('y')),
  5780. a =
  5781. (seconds <= thresholds.ss && ['s', seconds]) ||
  5782. (seconds < thresholds.s && ['ss', seconds]) ||
  5783. (minutes <= 1 && ['m']) ||
  5784. (minutes < thresholds.m && ['mm', minutes]) ||
  5785. (hours <= 1 && ['h']) ||
  5786. (hours < thresholds.h && ['hh', hours]) ||
  5787. (days <= 1 && ['d']) ||
  5788. (days < thresholds.d && ['dd', days]);
  5789. if (thresholds.w != null) {
  5790. a =
  5791. a ||
  5792. (weeks <= 1 && ['w']) ||
  5793. (weeks < thresholds.w && ['ww', weeks]);
  5794. }
  5795. a = a ||
  5796. (months <= 1 && ['M']) ||
  5797. (months < thresholds.M && ['MM', months]) ||
  5798. (years <= 1 && ['y']) || ['yy', years];
  5799. a[2] = withoutSuffix;
  5800. a[3] = +posNegDuration > 0;
  5801. a[4] = locale;
  5802. return substituteTimeAgo.apply(null, a);
  5803. }
  5804. // This function allows you to set the rounding function for relative time strings
  5805. function getSetRelativeTimeRounding(roundingFunction) {
  5806. if (roundingFunction === undefined) {
  5807. return round;
  5808. }
  5809. if (typeof roundingFunction === 'function') {
  5810. round = roundingFunction;
  5811. return true;
  5812. }
  5813. return false;
  5814. }
  5815. // This function allows you to set a threshold for relative time strings
  5816. function getSetRelativeTimeThreshold(threshold, limit) {
  5817. if (thresholds[threshold] === undefined) {
  5818. return false;
  5819. }
  5820. if (limit === undefined) {
  5821. return thresholds[threshold];
  5822. }
  5823. thresholds[threshold] = limit;
  5824. if (threshold === 's') {
  5825. thresholds.ss = limit - 1;
  5826. }
  5827. return true;
  5828. }
  5829. function humanize(argWithSuffix, argThresholds) {
  5830. if (!this.isValid()) {
  5831. return this.localeData().invalidDate();
  5832. }
  5833. var withSuffix = false,
  5834. th = thresholds,
  5835. locale,
  5836. output;
  5837. if (typeof argWithSuffix === 'object') {
  5838. argThresholds = argWithSuffix;
  5839. argWithSuffix = false;
  5840. }
  5841. if (typeof argWithSuffix === 'boolean') {
  5842. withSuffix = argWithSuffix;
  5843. }
  5844. if (typeof argThresholds === 'object') {
  5845. th = Object.assign({}, thresholds, argThresholds);
  5846. if (argThresholds.s != null && argThresholds.ss == null) {
  5847. th.ss = argThresholds.s - 1;
  5848. }
  5849. }
  5850. locale = this.localeData();
  5851. output = relativeTime$1(this, !withSuffix, th, locale);
  5852. if (withSuffix) {
  5853. output = locale.pastFuture(+this, output);
  5854. }
  5855. return locale.postformat(output);
  5856. }
  5857. var abs$1 = Math.abs;
  5858. function sign(x) {
  5859. return (x > 0) - (x < 0) || +x;
  5860. }
  5861. function toISOString$1() {
  5862. // for ISO strings we do not use the normal bubbling rules:
  5863. // * milliseconds bubble up until they become hours
  5864. // * days do not bubble at all
  5865. // * months bubble up until they become years
  5866. // This is because there is no context-free conversion between hours and days
  5867. // (think of clock changes)
  5868. // and also not between days and months (28-31 days per month)
  5869. if (!this.isValid()) {
  5870. return this.localeData().invalidDate();
  5871. }
  5872. var seconds = abs$1(this._milliseconds) / 1000,
  5873. days = abs$1(this._days),
  5874. months = abs$1(this._months),
  5875. minutes,
  5876. hours,
  5877. years,
  5878. s,
  5879. total = this.asSeconds(),
  5880. totalSign,
  5881. ymSign,
  5882. daysSign,
  5883. hmsSign;
  5884. if (!total) {
  5885. // this is the same as C#'s (Noda) and python (isodate)...
  5886. // but not other JS (goog.date)
  5887. return 'P0D';
  5888. }
  5889. // 3600 seconds -> 60 minutes -> 1 hour
  5890. minutes = absFloor(seconds / 60);
  5891. hours = absFloor(minutes / 60);
  5892. seconds %= 60;
  5893. minutes %= 60;
  5894. // 12 months -> 1 year
  5895. years = absFloor(months / 12);
  5896. months %= 12;
  5897. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  5898. s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  5899. totalSign = total < 0 ? '-' : '';
  5900. ymSign = sign(this._months) !== sign(total) ? '-' : '';
  5901. daysSign = sign(this._days) !== sign(total) ? '-' : '';
  5902. hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  5903. return (
  5904. totalSign +
  5905. 'P' +
  5906. (years ? ymSign + years + 'Y' : '') +
  5907. (months ? ymSign + months + 'M' : '') +
  5908. (days ? daysSign + days + 'D' : '') +
  5909. (hours || minutes || seconds ? 'T' : '') +
  5910. (hours ? hmsSign + hours + 'H' : '') +
  5911. (minutes ? hmsSign + minutes + 'M' : '') +
  5912. (seconds ? hmsSign + s + 'S' : '')
  5913. );
  5914. }
  5915. var proto$2 = Duration.prototype;
  5916. proto$2.isValid = isValid$1;
  5917. proto$2.abs = abs;
  5918. proto$2.add = add$1;
  5919. proto$2.subtract = subtract$1;
  5920. proto$2.as = as;
  5921. proto$2.asMilliseconds = asMilliseconds;
  5922. proto$2.asSeconds = asSeconds;
  5923. proto$2.asMinutes = asMinutes;
  5924. proto$2.asHours = asHours;
  5925. proto$2.asDays = asDays;
  5926. proto$2.asWeeks = asWeeks;
  5927. proto$2.asMonths = asMonths;
  5928. proto$2.asQuarters = asQuarters;
  5929. proto$2.asYears = asYears;
  5930. proto$2.valueOf = valueOf$1;
  5931. proto$2._bubble = bubble;
  5932. proto$2.clone = clone$1;
  5933. proto$2.get = get$2;
  5934. proto$2.milliseconds = milliseconds;
  5935. proto$2.seconds = seconds;
  5936. proto$2.minutes = minutes;
  5937. proto$2.hours = hours;
  5938. proto$2.days = days;
  5939. proto$2.weeks = weeks;
  5940. proto$2.months = months;
  5941. proto$2.years = years;
  5942. proto$2.humanize = humanize;
  5943. proto$2.toISOString = toISOString$1;
  5944. proto$2.toString = toISOString$1;
  5945. proto$2.toJSON = toISOString$1;
  5946. proto$2.locale = locale;
  5947. proto$2.localeData = localeData;
  5948. proto$2.toIsoString = deprecate(
  5949. 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
  5950. toISOString$1
  5951. );
  5952. proto$2.lang = lang;
  5953. // FORMATTING
  5954. addFormatToken('X', 0, 0, 'unix');
  5955. addFormatToken('x', 0, 0, 'valueOf');
  5956. // PARSING
  5957. addRegexToken('x', matchSigned);
  5958. addRegexToken('X', matchTimestamp);
  5959. addParseToken('X', function (input, array, config) {
  5960. config._d = new Date(parseFloat(input) * 1000);
  5961. });
  5962. addParseToken('x', function (input, array, config) {
  5963. config._d = new Date(toInt(input));
  5964. });
  5965. //! moment.js
  5966. hooks.version = '2.29.4';
  5967. setHookCallback(createLocal);
  5968. hooks.fn = proto;
  5969. hooks.min = min;
  5970. hooks.max = max;
  5971. hooks.now = now;
  5972. hooks.utc = createUTC;
  5973. hooks.unix = createUnix;
  5974. hooks.months = listMonths;
  5975. hooks.isDate = isDate;
  5976. hooks.locale = getSetGlobalLocale;
  5977. hooks.invalid = createInvalid;
  5978. hooks.duration = createDuration;
  5979. hooks.isMoment = isMoment;
  5980. hooks.weekdays = listWeekdays;
  5981. hooks.parseZone = createInZone;
  5982. hooks.localeData = getLocale;
  5983. hooks.isDuration = isDuration;
  5984. hooks.monthsShort = listMonthsShort;
  5985. hooks.weekdaysMin = listWeekdaysMin;
  5986. hooks.defineLocale = defineLocale;
  5987. hooks.updateLocale = updateLocale;
  5988. hooks.locales = listLocales;
  5989. hooks.weekdaysShort = listWeekdaysShort;
  5990. hooks.normalizeUnits = normalizeUnits;
  5991. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  5992. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  5993. hooks.calendarFormat = getCalendarFormat;
  5994. hooks.prototype = proto;
  5995. // currently HTML5 input type only supports 24-hour formats
  5996. hooks.HTML5_FMT = {
  5997. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  5998. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  5999. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  6000. DATE: 'YYYY-MM-DD', // <input type="date" />
  6001. TIME: 'HH:mm', // <input type="time" />
  6002. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  6003. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  6004. WEEK: 'GGGG-[W]WW', // <input type="week" />
  6005. MONTH: 'YYYY-MM', // <input type="month" />
  6006. };
  6007. return hooks;
  6008. })));
  6009. } (moment));
  6010. return moment.exports;
  6011. }
  6012. /*!
  6013. * Chart.js v2.9.4
  6014. * https://www.chartjs.org
  6015. * (c) 2020 Chart.js Contributors
  6016. * Released under the MIT License
  6017. */
  6018. (function (module, exports) {
  6019. (function (global, factory) {
  6020. module.exports = factory(function() { try { return requireMoment(); } catch(e) { } }()) ;
  6021. }(commonjsGlobal, (function (moment) {
  6022. moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;
  6023. function createCommonjsModule(fn, module) {
  6024. return module = { exports: {} }, fn(module, module.exports), module.exports;
  6025. }
  6026. function getCjsExportFromNamespace (n) {
  6027. return n && n['default'] || n;
  6028. }
  6029. var colorName = {
  6030. "aliceblue": [240, 248, 255],
  6031. "antiquewhite": [250, 235, 215],
  6032. "aqua": [0, 255, 255],
  6033. "aquamarine": [127, 255, 212],
  6034. "azure": [240, 255, 255],
  6035. "beige": [245, 245, 220],
  6036. "bisque": [255, 228, 196],
  6037. "black": [0, 0, 0],
  6038. "blanchedalmond": [255, 235, 205],
  6039. "blue": [0, 0, 255],
  6040. "blueviolet": [138, 43, 226],
  6041. "brown": [165, 42, 42],
  6042. "burlywood": [222, 184, 135],
  6043. "cadetblue": [95, 158, 160],
  6044. "chartreuse": [127, 255, 0],
  6045. "chocolate": [210, 105, 30],
  6046. "coral": [255, 127, 80],
  6047. "cornflowerblue": [100, 149, 237],
  6048. "cornsilk": [255, 248, 220],
  6049. "crimson": [220, 20, 60],
  6050. "cyan": [0, 255, 255],
  6051. "darkblue": [0, 0, 139],
  6052. "darkcyan": [0, 139, 139],
  6053. "darkgoldenrod": [184, 134, 11],
  6054. "darkgray": [169, 169, 169],
  6055. "darkgreen": [0, 100, 0],
  6056. "darkgrey": [169, 169, 169],
  6057. "darkkhaki": [189, 183, 107],
  6058. "darkmagenta": [139, 0, 139],
  6059. "darkolivegreen": [85, 107, 47],
  6060. "darkorange": [255, 140, 0],
  6061. "darkorchid": [153, 50, 204],
  6062. "darkred": [139, 0, 0],
  6063. "darksalmon": [233, 150, 122],
  6064. "darkseagreen": [143, 188, 143],
  6065. "darkslateblue": [72, 61, 139],
  6066. "darkslategray": [47, 79, 79],
  6067. "darkslategrey": [47, 79, 79],
  6068. "darkturquoise": [0, 206, 209],
  6069. "darkviolet": [148, 0, 211],
  6070. "deeppink": [255, 20, 147],
  6071. "deepskyblue": [0, 191, 255],
  6072. "dimgray": [105, 105, 105],
  6073. "dimgrey": [105, 105, 105],
  6074. "dodgerblue": [30, 144, 255],
  6075. "firebrick": [178, 34, 34],
  6076. "floralwhite": [255, 250, 240],
  6077. "forestgreen": [34, 139, 34],
  6078. "fuchsia": [255, 0, 255],
  6079. "gainsboro": [220, 220, 220],
  6080. "ghostwhite": [248, 248, 255],
  6081. "gold": [255, 215, 0],
  6082. "goldenrod": [218, 165, 32],
  6083. "gray": [128, 128, 128],
  6084. "green": [0, 128, 0],
  6085. "greenyellow": [173, 255, 47],
  6086. "grey": [128, 128, 128],
  6087. "honeydew": [240, 255, 240],
  6088. "hotpink": [255, 105, 180],
  6089. "indianred": [205, 92, 92],
  6090. "indigo": [75, 0, 130],
  6091. "ivory": [255, 255, 240],
  6092. "khaki": [240, 230, 140],
  6093. "lavender": [230, 230, 250],
  6094. "lavenderblush": [255, 240, 245],
  6095. "lawngreen": [124, 252, 0],
  6096. "lemonchiffon": [255, 250, 205],
  6097. "lightblue": [173, 216, 230],
  6098. "lightcoral": [240, 128, 128],
  6099. "lightcyan": [224, 255, 255],
  6100. "lightgoldenrodyellow": [250, 250, 210],
  6101. "lightgray": [211, 211, 211],
  6102. "lightgreen": [144, 238, 144],
  6103. "lightgrey": [211, 211, 211],
  6104. "lightpink": [255, 182, 193],
  6105. "lightsalmon": [255, 160, 122],
  6106. "lightseagreen": [32, 178, 170],
  6107. "lightskyblue": [135, 206, 250],
  6108. "lightslategray": [119, 136, 153],
  6109. "lightslategrey": [119, 136, 153],
  6110. "lightsteelblue": [176, 196, 222],
  6111. "lightyellow": [255, 255, 224],
  6112. "lime": [0, 255, 0],
  6113. "limegreen": [50, 205, 50],
  6114. "linen": [250, 240, 230],
  6115. "magenta": [255, 0, 255],
  6116. "maroon": [128, 0, 0],
  6117. "mediumaquamarine": [102, 205, 170],
  6118. "mediumblue": [0, 0, 205],
  6119. "mediumorchid": [186, 85, 211],
  6120. "mediumpurple": [147, 112, 219],
  6121. "mediumseagreen": [60, 179, 113],
  6122. "mediumslateblue": [123, 104, 238],
  6123. "mediumspringgreen": [0, 250, 154],
  6124. "mediumturquoise": [72, 209, 204],
  6125. "mediumvioletred": [199, 21, 133],
  6126. "midnightblue": [25, 25, 112],
  6127. "mintcream": [245, 255, 250],
  6128. "mistyrose": [255, 228, 225],
  6129. "moccasin": [255, 228, 181],
  6130. "navajowhite": [255, 222, 173],
  6131. "navy": [0, 0, 128],
  6132. "oldlace": [253, 245, 230],
  6133. "olive": [128, 128, 0],
  6134. "olivedrab": [107, 142, 35],
  6135. "orange": [255, 165, 0],
  6136. "orangered": [255, 69, 0],
  6137. "orchid": [218, 112, 214],
  6138. "palegoldenrod": [238, 232, 170],
  6139. "palegreen": [152, 251, 152],
  6140. "paleturquoise": [175, 238, 238],
  6141. "palevioletred": [219, 112, 147],
  6142. "papayawhip": [255, 239, 213],
  6143. "peachpuff": [255, 218, 185],
  6144. "peru": [205, 133, 63],
  6145. "pink": [255, 192, 203],
  6146. "plum": [221, 160, 221],
  6147. "powderblue": [176, 224, 230],
  6148. "purple": [128, 0, 128],
  6149. "rebeccapurple": [102, 51, 153],
  6150. "red": [255, 0, 0],
  6151. "rosybrown": [188, 143, 143],
  6152. "royalblue": [65, 105, 225],
  6153. "saddlebrown": [139, 69, 19],
  6154. "salmon": [250, 128, 114],
  6155. "sandybrown": [244, 164, 96],
  6156. "seagreen": [46, 139, 87],
  6157. "seashell": [255, 245, 238],
  6158. "sienna": [160, 82, 45],
  6159. "silver": [192, 192, 192],
  6160. "skyblue": [135, 206, 235],
  6161. "slateblue": [106, 90, 205],
  6162. "slategray": [112, 128, 144],
  6163. "slategrey": [112, 128, 144],
  6164. "snow": [255, 250, 250],
  6165. "springgreen": [0, 255, 127],
  6166. "steelblue": [70, 130, 180],
  6167. "tan": [210, 180, 140],
  6168. "teal": [0, 128, 128],
  6169. "thistle": [216, 191, 216],
  6170. "tomato": [255, 99, 71],
  6171. "turquoise": [64, 224, 208],
  6172. "violet": [238, 130, 238],
  6173. "wheat": [245, 222, 179],
  6174. "white": [255, 255, 255],
  6175. "whitesmoke": [245, 245, 245],
  6176. "yellow": [255, 255, 0],
  6177. "yellowgreen": [154, 205, 50]
  6178. };
  6179. var conversions = createCommonjsModule(function (module) {
  6180. /* MIT license */
  6181. // NOTE: conversions should only return primitive values (i.e. arrays, or
  6182. // values that give correct `typeof` results).
  6183. // do not use box values types (i.e. Number(), String(), etc.)
  6184. var reverseKeywords = {};
  6185. for (var key in colorName) {
  6186. if (colorName.hasOwnProperty(key)) {
  6187. reverseKeywords[colorName[key]] = key;
  6188. }
  6189. }
  6190. var convert = module.exports = {
  6191. rgb: {channels: 3, labels: 'rgb'},
  6192. hsl: {channels: 3, labels: 'hsl'},
  6193. hsv: {channels: 3, labels: 'hsv'},
  6194. hwb: {channels: 3, labels: 'hwb'},
  6195. cmyk: {channels: 4, labels: 'cmyk'},
  6196. xyz: {channels: 3, labels: 'xyz'},
  6197. lab: {channels: 3, labels: 'lab'},
  6198. lch: {channels: 3, labels: 'lch'},
  6199. hex: {channels: 1, labels: ['hex']},
  6200. keyword: {channels: 1, labels: ['keyword']},
  6201. ansi16: {channels: 1, labels: ['ansi16']},
  6202. ansi256: {channels: 1, labels: ['ansi256']},
  6203. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  6204. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  6205. gray: {channels: 1, labels: ['gray']}
  6206. };
  6207. // hide .channels and .labels properties
  6208. for (var model in convert) {
  6209. if (convert.hasOwnProperty(model)) {
  6210. if (!('channels' in convert[model])) {
  6211. throw new Error('missing channels property: ' + model);
  6212. }
  6213. if (!('labels' in convert[model])) {
  6214. throw new Error('missing channel labels property: ' + model);
  6215. }
  6216. if (convert[model].labels.length !== convert[model].channels) {
  6217. throw new Error('channel and label counts mismatch: ' + model);
  6218. }
  6219. var channels = convert[model].channels;
  6220. var labels = convert[model].labels;
  6221. delete convert[model].channels;
  6222. delete convert[model].labels;
  6223. Object.defineProperty(convert[model], 'channels', {value: channels});
  6224. Object.defineProperty(convert[model], 'labels', {value: labels});
  6225. }
  6226. }
  6227. convert.rgb.hsl = function (rgb) {
  6228. var r = rgb[0] / 255;
  6229. var g = rgb[1] / 255;
  6230. var b = rgb[2] / 255;
  6231. var min = Math.min(r, g, b);
  6232. var max = Math.max(r, g, b);
  6233. var delta = max - min;
  6234. var h;
  6235. var s;
  6236. var l;
  6237. if (max === min) {
  6238. h = 0;
  6239. } else if (r === max) {
  6240. h = (g - b) / delta;
  6241. } else if (g === max) {
  6242. h = 2 + (b - r) / delta;
  6243. } else if (b === max) {
  6244. h = 4 + (r - g) / delta;
  6245. }
  6246. h = Math.min(h * 60, 360);
  6247. if (h < 0) {
  6248. h += 360;
  6249. }
  6250. l = (min + max) / 2;
  6251. if (max === min) {
  6252. s = 0;
  6253. } else if (l <= 0.5) {
  6254. s = delta / (max + min);
  6255. } else {
  6256. s = delta / (2 - max - min);
  6257. }
  6258. return [h, s * 100, l * 100];
  6259. };
  6260. convert.rgb.hsv = function (rgb) {
  6261. var rdif;
  6262. var gdif;
  6263. var bdif;
  6264. var h;
  6265. var s;
  6266. var r = rgb[0] / 255;
  6267. var g = rgb[1] / 255;
  6268. var b = rgb[2] / 255;
  6269. var v = Math.max(r, g, b);
  6270. var diff = v - Math.min(r, g, b);
  6271. var diffc = function (c) {
  6272. return (v - c) / 6 / diff + 1 / 2;
  6273. };
  6274. if (diff === 0) {
  6275. h = s = 0;
  6276. } else {
  6277. s = diff / v;
  6278. rdif = diffc(r);
  6279. gdif = diffc(g);
  6280. bdif = diffc(b);
  6281. if (r === v) {
  6282. h = bdif - gdif;
  6283. } else if (g === v) {
  6284. h = (1 / 3) + rdif - bdif;
  6285. } else if (b === v) {
  6286. h = (2 / 3) + gdif - rdif;
  6287. }
  6288. if (h < 0) {
  6289. h += 1;
  6290. } else if (h > 1) {
  6291. h -= 1;
  6292. }
  6293. }
  6294. return [
  6295. h * 360,
  6296. s * 100,
  6297. v * 100
  6298. ];
  6299. };
  6300. convert.rgb.hwb = function (rgb) {
  6301. var r = rgb[0];
  6302. var g = rgb[1];
  6303. var b = rgb[2];
  6304. var h = convert.rgb.hsl(rgb)[0];
  6305. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  6306. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  6307. return [h, w * 100, b * 100];
  6308. };
  6309. convert.rgb.cmyk = function (rgb) {
  6310. var r = rgb[0] / 255;
  6311. var g = rgb[1] / 255;
  6312. var b = rgb[2] / 255;
  6313. var c;
  6314. var m;
  6315. var y;
  6316. var k;
  6317. k = Math.min(1 - r, 1 - g, 1 - b);
  6318. c = (1 - r - k) / (1 - k) || 0;
  6319. m = (1 - g - k) / (1 - k) || 0;
  6320. y = (1 - b - k) / (1 - k) || 0;
  6321. return [c * 100, m * 100, y * 100, k * 100];
  6322. };
  6323. /**
  6324. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  6325. * */
  6326. function comparativeDistance(x, y) {
  6327. return (
  6328. Math.pow(x[0] - y[0], 2) +
  6329. Math.pow(x[1] - y[1], 2) +
  6330. Math.pow(x[2] - y[2], 2)
  6331. );
  6332. }
  6333. convert.rgb.keyword = function (rgb) {
  6334. var reversed = reverseKeywords[rgb];
  6335. if (reversed) {
  6336. return reversed;
  6337. }
  6338. var currentClosestDistance = Infinity;
  6339. var currentClosestKeyword;
  6340. for (var keyword in colorName) {
  6341. if (colorName.hasOwnProperty(keyword)) {
  6342. var value = colorName[keyword];
  6343. // Compute comparative distance
  6344. var distance = comparativeDistance(rgb, value);
  6345. // Check if its less, if so set as closest
  6346. if (distance < currentClosestDistance) {
  6347. currentClosestDistance = distance;
  6348. currentClosestKeyword = keyword;
  6349. }
  6350. }
  6351. }
  6352. return currentClosestKeyword;
  6353. };
  6354. convert.keyword.rgb = function (keyword) {
  6355. return colorName[keyword];
  6356. };
  6357. convert.rgb.xyz = function (rgb) {
  6358. var r = rgb[0] / 255;
  6359. var g = rgb[1] / 255;
  6360. var b = rgb[2] / 255;
  6361. // assume sRGB
  6362. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  6363. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  6364. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  6365. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  6366. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  6367. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  6368. return [x * 100, y * 100, z * 100];
  6369. };
  6370. convert.rgb.lab = function (rgb) {
  6371. var xyz = convert.rgb.xyz(rgb);
  6372. var x = xyz[0];
  6373. var y = xyz[1];
  6374. var z = xyz[2];
  6375. var l;
  6376. var a;
  6377. var b;
  6378. x /= 95.047;
  6379. y /= 100;
  6380. z /= 108.883;
  6381. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  6382. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  6383. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  6384. l = (116 * y) - 16;
  6385. a = 500 * (x - y);
  6386. b = 200 * (y - z);
  6387. return [l, a, b];
  6388. };
  6389. convert.hsl.rgb = function (hsl) {
  6390. var h = hsl[0] / 360;
  6391. var s = hsl[1] / 100;
  6392. var l = hsl[2] / 100;
  6393. var t1;
  6394. var t2;
  6395. var t3;
  6396. var rgb;
  6397. var val;
  6398. if (s === 0) {
  6399. val = l * 255;
  6400. return [val, val, val];
  6401. }
  6402. if (l < 0.5) {
  6403. t2 = l * (1 + s);
  6404. } else {
  6405. t2 = l + s - l * s;
  6406. }
  6407. t1 = 2 * l - t2;
  6408. rgb = [0, 0, 0];
  6409. for (var i = 0; i < 3; i++) {
  6410. t3 = h + 1 / 3 * -(i - 1);
  6411. if (t3 < 0) {
  6412. t3++;
  6413. }
  6414. if (t3 > 1) {
  6415. t3--;
  6416. }
  6417. if (6 * t3 < 1) {
  6418. val = t1 + (t2 - t1) * 6 * t3;
  6419. } else if (2 * t3 < 1) {
  6420. val = t2;
  6421. } else if (3 * t3 < 2) {
  6422. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  6423. } else {
  6424. val = t1;
  6425. }
  6426. rgb[i] = val * 255;
  6427. }
  6428. return rgb;
  6429. };
  6430. convert.hsl.hsv = function (hsl) {
  6431. var h = hsl[0];
  6432. var s = hsl[1] / 100;
  6433. var l = hsl[2] / 100;
  6434. var smin = s;
  6435. var lmin = Math.max(l, 0.01);
  6436. var sv;
  6437. var v;
  6438. l *= 2;
  6439. s *= (l <= 1) ? l : 2 - l;
  6440. smin *= lmin <= 1 ? lmin : 2 - lmin;
  6441. v = (l + s) / 2;
  6442. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  6443. return [h, sv * 100, v * 100];
  6444. };
  6445. convert.hsv.rgb = function (hsv) {
  6446. var h = hsv[0] / 60;
  6447. var s = hsv[1] / 100;
  6448. var v = hsv[2] / 100;
  6449. var hi = Math.floor(h) % 6;
  6450. var f = h - Math.floor(h);
  6451. var p = 255 * v * (1 - s);
  6452. var q = 255 * v * (1 - (s * f));
  6453. var t = 255 * v * (1 - (s * (1 - f)));
  6454. v *= 255;
  6455. switch (hi) {
  6456. case 0:
  6457. return [v, t, p];
  6458. case 1:
  6459. return [q, v, p];
  6460. case 2:
  6461. return [p, v, t];
  6462. case 3:
  6463. return [p, q, v];
  6464. case 4:
  6465. return [t, p, v];
  6466. case 5:
  6467. return [v, p, q];
  6468. }
  6469. };
  6470. convert.hsv.hsl = function (hsv) {
  6471. var h = hsv[0];
  6472. var s = hsv[1] / 100;
  6473. var v = hsv[2] / 100;
  6474. var vmin = Math.max(v, 0.01);
  6475. var lmin;
  6476. var sl;
  6477. var l;
  6478. l = (2 - s) * v;
  6479. lmin = (2 - s) * vmin;
  6480. sl = s * vmin;
  6481. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  6482. sl = sl || 0;
  6483. l /= 2;
  6484. return [h, sl * 100, l * 100];
  6485. };
  6486. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  6487. convert.hwb.rgb = function (hwb) {
  6488. var h = hwb[0] / 360;
  6489. var wh = hwb[1] / 100;
  6490. var bl = hwb[2] / 100;
  6491. var ratio = wh + bl;
  6492. var i;
  6493. var v;
  6494. var f;
  6495. var n;
  6496. // wh + bl cant be > 1
  6497. if (ratio > 1) {
  6498. wh /= ratio;
  6499. bl /= ratio;
  6500. }
  6501. i = Math.floor(6 * h);
  6502. v = 1 - bl;
  6503. f = 6 * h - i;
  6504. if ((i & 0x01) !== 0) {
  6505. f = 1 - f;
  6506. }
  6507. n = wh + f * (v - wh); // linear interpolation
  6508. var r;
  6509. var g;
  6510. var b;
  6511. switch (i) {
  6512. default:
  6513. case 6:
  6514. case 0: r = v; g = n; b = wh; break;
  6515. case 1: r = n; g = v; b = wh; break;
  6516. case 2: r = wh; g = v; b = n; break;
  6517. case 3: r = wh; g = n; b = v; break;
  6518. case 4: r = n; g = wh; b = v; break;
  6519. case 5: r = v; g = wh; b = n; break;
  6520. }
  6521. return [r * 255, g * 255, b * 255];
  6522. };
  6523. convert.cmyk.rgb = function (cmyk) {
  6524. var c = cmyk[0] / 100;
  6525. var m = cmyk[1] / 100;
  6526. var y = cmyk[2] / 100;
  6527. var k = cmyk[3] / 100;
  6528. var r;
  6529. var g;
  6530. var b;
  6531. r = 1 - Math.min(1, c * (1 - k) + k);
  6532. g = 1 - Math.min(1, m * (1 - k) + k);
  6533. b = 1 - Math.min(1, y * (1 - k) + k);
  6534. return [r * 255, g * 255, b * 255];
  6535. };
  6536. convert.xyz.rgb = function (xyz) {
  6537. var x = xyz[0] / 100;
  6538. var y = xyz[1] / 100;
  6539. var z = xyz[2] / 100;
  6540. var r;
  6541. var g;
  6542. var b;
  6543. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  6544. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  6545. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  6546. // assume sRGB
  6547. r = r > 0.0031308
  6548. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  6549. : r * 12.92;
  6550. g = g > 0.0031308
  6551. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  6552. : g * 12.92;
  6553. b = b > 0.0031308
  6554. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  6555. : b * 12.92;
  6556. r = Math.min(Math.max(0, r), 1);
  6557. g = Math.min(Math.max(0, g), 1);
  6558. b = Math.min(Math.max(0, b), 1);
  6559. return [r * 255, g * 255, b * 255];
  6560. };
  6561. convert.xyz.lab = function (xyz) {
  6562. var x = xyz[0];
  6563. var y = xyz[1];
  6564. var z = xyz[2];
  6565. var l;
  6566. var a;
  6567. var b;
  6568. x /= 95.047;
  6569. y /= 100;
  6570. z /= 108.883;
  6571. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  6572. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  6573. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  6574. l = (116 * y) - 16;
  6575. a = 500 * (x - y);
  6576. b = 200 * (y - z);
  6577. return [l, a, b];
  6578. };
  6579. convert.lab.xyz = function (lab) {
  6580. var l = lab[0];
  6581. var a = lab[1];
  6582. var b = lab[2];
  6583. var x;
  6584. var y;
  6585. var z;
  6586. y = (l + 16) / 116;
  6587. x = a / 500 + y;
  6588. z = y - b / 200;
  6589. var y2 = Math.pow(y, 3);
  6590. var x2 = Math.pow(x, 3);
  6591. var z2 = Math.pow(z, 3);
  6592. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  6593. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  6594. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  6595. x *= 95.047;
  6596. y *= 100;
  6597. z *= 108.883;
  6598. return [x, y, z];
  6599. };
  6600. convert.lab.lch = function (lab) {
  6601. var l = lab[0];
  6602. var a = lab[1];
  6603. var b = lab[2];
  6604. var hr;
  6605. var h;
  6606. var c;
  6607. hr = Math.atan2(b, a);
  6608. h = hr * 360 / 2 / Math.PI;
  6609. if (h < 0) {
  6610. h += 360;
  6611. }
  6612. c = Math.sqrt(a * a + b * b);
  6613. return [l, c, h];
  6614. };
  6615. convert.lch.lab = function (lch) {
  6616. var l = lch[0];
  6617. var c = lch[1];
  6618. var h = lch[2];
  6619. var a;
  6620. var b;
  6621. var hr;
  6622. hr = h / 360 * 2 * Math.PI;
  6623. a = c * Math.cos(hr);
  6624. b = c * Math.sin(hr);
  6625. return [l, a, b];
  6626. };
  6627. convert.rgb.ansi16 = function (args) {
  6628. var r = args[0];
  6629. var g = args[1];
  6630. var b = args[2];
  6631. var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  6632. value = Math.round(value / 50);
  6633. if (value === 0) {
  6634. return 30;
  6635. }
  6636. var ansi = 30
  6637. + ((Math.round(b / 255) << 2)
  6638. | (Math.round(g / 255) << 1)
  6639. | Math.round(r / 255));
  6640. if (value === 2) {
  6641. ansi += 60;
  6642. }
  6643. return ansi;
  6644. };
  6645. convert.hsv.ansi16 = function (args) {
  6646. // optimization here; we already know the value and don't need to get
  6647. // it converted for us.
  6648. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  6649. };
  6650. convert.rgb.ansi256 = function (args) {
  6651. var r = args[0];
  6652. var g = args[1];
  6653. var b = args[2];
  6654. // we use the extended greyscale palette here, with the exception of
  6655. // black and white. normal palette only has 4 greyscale shades.
  6656. if (r === g && g === b) {
  6657. if (r < 8) {
  6658. return 16;
  6659. }
  6660. if (r > 248) {
  6661. return 231;
  6662. }
  6663. return Math.round(((r - 8) / 247) * 24) + 232;
  6664. }
  6665. var ansi = 16
  6666. + (36 * Math.round(r / 255 * 5))
  6667. + (6 * Math.round(g / 255 * 5))
  6668. + Math.round(b / 255 * 5);
  6669. return ansi;
  6670. };
  6671. convert.ansi16.rgb = function (args) {
  6672. var color = args % 10;
  6673. // handle greyscale
  6674. if (color === 0 || color === 7) {
  6675. if (args > 50) {
  6676. color += 3.5;
  6677. }
  6678. color = color / 10.5 * 255;
  6679. return [color, color, color];
  6680. }
  6681. var mult = (~~(args > 50) + 1) * 0.5;
  6682. var r = ((color & 1) * mult) * 255;
  6683. var g = (((color >> 1) & 1) * mult) * 255;
  6684. var b = (((color >> 2) & 1) * mult) * 255;
  6685. return [r, g, b];
  6686. };
  6687. convert.ansi256.rgb = function (args) {
  6688. // handle greyscale
  6689. if (args >= 232) {
  6690. var c = (args - 232) * 10 + 8;
  6691. return [c, c, c];
  6692. }
  6693. args -= 16;
  6694. var rem;
  6695. var r = Math.floor(args / 36) / 5 * 255;
  6696. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  6697. var b = (rem % 6) / 5 * 255;
  6698. return [r, g, b];
  6699. };
  6700. convert.rgb.hex = function (args) {
  6701. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  6702. + ((Math.round(args[1]) & 0xFF) << 8)
  6703. + (Math.round(args[2]) & 0xFF);
  6704. var string = integer.toString(16).toUpperCase();
  6705. return '000000'.substring(string.length) + string;
  6706. };
  6707. convert.hex.rgb = function (args) {
  6708. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  6709. if (!match) {
  6710. return [0, 0, 0];
  6711. }
  6712. var colorString = match[0];
  6713. if (match[0].length === 3) {
  6714. colorString = colorString.split('').map(function (char) {
  6715. return char + char;
  6716. }).join('');
  6717. }
  6718. var integer = parseInt(colorString, 16);
  6719. var r = (integer >> 16) & 0xFF;
  6720. var g = (integer >> 8) & 0xFF;
  6721. var b = integer & 0xFF;
  6722. return [r, g, b];
  6723. };
  6724. convert.rgb.hcg = function (rgb) {
  6725. var r = rgb[0] / 255;
  6726. var g = rgb[1] / 255;
  6727. var b = rgb[2] / 255;
  6728. var max = Math.max(Math.max(r, g), b);
  6729. var min = Math.min(Math.min(r, g), b);
  6730. var chroma = (max - min);
  6731. var grayscale;
  6732. var hue;
  6733. if (chroma < 1) {
  6734. grayscale = min / (1 - chroma);
  6735. } else {
  6736. grayscale = 0;
  6737. }
  6738. if (chroma <= 0) {
  6739. hue = 0;
  6740. } else
  6741. if (max === r) {
  6742. hue = ((g - b) / chroma) % 6;
  6743. } else
  6744. if (max === g) {
  6745. hue = 2 + (b - r) / chroma;
  6746. } else {
  6747. hue = 4 + (r - g) / chroma + 4;
  6748. }
  6749. hue /= 6;
  6750. hue %= 1;
  6751. return [hue * 360, chroma * 100, grayscale * 100];
  6752. };
  6753. convert.hsl.hcg = function (hsl) {
  6754. var s = hsl[1] / 100;
  6755. var l = hsl[2] / 100;
  6756. var c = 1;
  6757. var f = 0;
  6758. if (l < 0.5) {
  6759. c = 2.0 * s * l;
  6760. } else {
  6761. c = 2.0 * s * (1.0 - l);
  6762. }
  6763. if (c < 1.0) {
  6764. f = (l - 0.5 * c) / (1.0 - c);
  6765. }
  6766. return [hsl[0], c * 100, f * 100];
  6767. };
  6768. convert.hsv.hcg = function (hsv) {
  6769. var s = hsv[1] / 100;
  6770. var v = hsv[2] / 100;
  6771. var c = s * v;
  6772. var f = 0;
  6773. if (c < 1.0) {
  6774. f = (v - c) / (1 - c);
  6775. }
  6776. return [hsv[0], c * 100, f * 100];
  6777. };
  6778. convert.hcg.rgb = function (hcg) {
  6779. var h = hcg[0] / 360;
  6780. var c = hcg[1] / 100;
  6781. var g = hcg[2] / 100;
  6782. if (c === 0.0) {
  6783. return [g * 255, g * 255, g * 255];
  6784. }
  6785. var pure = [0, 0, 0];
  6786. var hi = (h % 1) * 6;
  6787. var v = hi % 1;
  6788. var w = 1 - v;
  6789. var mg = 0;
  6790. switch (Math.floor(hi)) {
  6791. case 0:
  6792. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  6793. case 1:
  6794. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  6795. case 2:
  6796. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  6797. case 3:
  6798. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  6799. case 4:
  6800. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  6801. default:
  6802. pure[0] = 1; pure[1] = 0; pure[2] = w;
  6803. }
  6804. mg = (1.0 - c) * g;
  6805. return [
  6806. (c * pure[0] + mg) * 255,
  6807. (c * pure[1] + mg) * 255,
  6808. (c * pure[2] + mg) * 255
  6809. ];
  6810. };
  6811. convert.hcg.hsv = function (hcg) {
  6812. var c = hcg[1] / 100;
  6813. var g = hcg[2] / 100;
  6814. var v = c + g * (1.0 - c);
  6815. var f = 0;
  6816. if (v > 0.0) {
  6817. f = c / v;
  6818. }
  6819. return [hcg[0], f * 100, v * 100];
  6820. };
  6821. convert.hcg.hsl = function (hcg) {
  6822. var c = hcg[1] / 100;
  6823. var g = hcg[2] / 100;
  6824. var l = g * (1.0 - c) + 0.5 * c;
  6825. var s = 0;
  6826. if (l > 0.0 && l < 0.5) {
  6827. s = c / (2 * l);
  6828. } else
  6829. if (l >= 0.5 && l < 1.0) {
  6830. s = c / (2 * (1 - l));
  6831. }
  6832. return [hcg[0], s * 100, l * 100];
  6833. };
  6834. convert.hcg.hwb = function (hcg) {
  6835. var c = hcg[1] / 100;
  6836. var g = hcg[2] / 100;
  6837. var v = c + g * (1.0 - c);
  6838. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  6839. };
  6840. convert.hwb.hcg = function (hwb) {
  6841. var w = hwb[1] / 100;
  6842. var b = hwb[2] / 100;
  6843. var v = 1 - b;
  6844. var c = v - w;
  6845. var g = 0;
  6846. if (c < 1) {
  6847. g = (v - c) / (1 - c);
  6848. }
  6849. return [hwb[0], c * 100, g * 100];
  6850. };
  6851. convert.apple.rgb = function (apple) {
  6852. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  6853. };
  6854. convert.rgb.apple = function (rgb) {
  6855. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  6856. };
  6857. convert.gray.rgb = function (args) {
  6858. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  6859. };
  6860. convert.gray.hsl = convert.gray.hsv = function (args) {
  6861. return [0, 0, args[0]];
  6862. };
  6863. convert.gray.hwb = function (gray) {
  6864. return [0, 100, gray[0]];
  6865. };
  6866. convert.gray.cmyk = function (gray) {
  6867. return [0, 0, 0, gray[0]];
  6868. };
  6869. convert.gray.lab = function (gray) {
  6870. return [gray[0], 0, 0];
  6871. };
  6872. convert.gray.hex = function (gray) {
  6873. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  6874. var integer = (val << 16) + (val << 8) + val;
  6875. var string = integer.toString(16).toUpperCase();
  6876. return '000000'.substring(string.length) + string;
  6877. };
  6878. convert.rgb.gray = function (rgb) {
  6879. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  6880. return [val / 255 * 100];
  6881. };
  6882. });
  6883. conversions.rgb;
  6884. conversions.hsl;
  6885. conversions.hsv;
  6886. conversions.hwb;
  6887. conversions.cmyk;
  6888. conversions.xyz;
  6889. conversions.lab;
  6890. conversions.lch;
  6891. conversions.hex;
  6892. conversions.keyword;
  6893. conversions.ansi16;
  6894. conversions.ansi256;
  6895. conversions.hcg;
  6896. conversions.apple;
  6897. conversions.gray;
  6898. /*
  6899. this function routes a model to all other models.
  6900. all functions that are routed have a property `.conversion` attached
  6901. to the returned synthetic function. This property is an array
  6902. of strings, each with the steps in between the 'from' and 'to'
  6903. color models (inclusive).
  6904. conversions that are not possible simply are not included.
  6905. */
  6906. function buildGraph() {
  6907. var graph = {};
  6908. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  6909. var models = Object.keys(conversions);
  6910. for (var len = models.length, i = 0; i < len; i++) {
  6911. graph[models[i]] = {
  6912. // http://jsperf.com/1-vs-infinity
  6913. // micro-opt, but this is simple.
  6914. distance: -1,
  6915. parent: null
  6916. };
  6917. }
  6918. return graph;
  6919. }
  6920. // https://en.wikipedia.org/wiki/Breadth-first_search
  6921. function deriveBFS(fromModel) {
  6922. var graph = buildGraph();
  6923. var queue = [fromModel]; // unshift -> queue -> pop
  6924. graph[fromModel].distance = 0;
  6925. while (queue.length) {
  6926. var current = queue.pop();
  6927. var adjacents = Object.keys(conversions[current]);
  6928. for (var len = adjacents.length, i = 0; i < len; i++) {
  6929. var adjacent = adjacents[i];
  6930. var node = graph[adjacent];
  6931. if (node.distance === -1) {
  6932. node.distance = graph[current].distance + 1;
  6933. node.parent = current;
  6934. queue.unshift(adjacent);
  6935. }
  6936. }
  6937. }
  6938. return graph;
  6939. }
  6940. function link(from, to) {
  6941. return function (args) {
  6942. return to(from(args));
  6943. };
  6944. }
  6945. function wrapConversion(toModel, graph) {
  6946. var path = [graph[toModel].parent, toModel];
  6947. var fn = conversions[graph[toModel].parent][toModel];
  6948. var cur = graph[toModel].parent;
  6949. while (graph[cur].parent) {
  6950. path.unshift(graph[cur].parent);
  6951. fn = link(conversions[graph[cur].parent][cur], fn);
  6952. cur = graph[cur].parent;
  6953. }
  6954. fn.conversion = path;
  6955. return fn;
  6956. }
  6957. var route = function (fromModel) {
  6958. var graph = deriveBFS(fromModel);
  6959. var conversion = {};
  6960. var models = Object.keys(graph);
  6961. for (var len = models.length, i = 0; i < len; i++) {
  6962. var toModel = models[i];
  6963. var node = graph[toModel];
  6964. if (node.parent === null) {
  6965. // no possible conversion, or this node is the source model.
  6966. continue;
  6967. }
  6968. conversion[toModel] = wrapConversion(toModel, graph);
  6969. }
  6970. return conversion;
  6971. };
  6972. var convert = {};
  6973. var models = Object.keys(conversions);
  6974. function wrapRaw(fn) {
  6975. var wrappedFn = function (args) {
  6976. if (args === undefined || args === null) {
  6977. return args;
  6978. }
  6979. if (arguments.length > 1) {
  6980. args = Array.prototype.slice.call(arguments);
  6981. }
  6982. return fn(args);
  6983. };
  6984. // preserve .conversion property if there is one
  6985. if ('conversion' in fn) {
  6986. wrappedFn.conversion = fn.conversion;
  6987. }
  6988. return wrappedFn;
  6989. }
  6990. function wrapRounded(fn) {
  6991. var wrappedFn = function (args) {
  6992. if (args === undefined || args === null) {
  6993. return args;
  6994. }
  6995. if (arguments.length > 1) {
  6996. args = Array.prototype.slice.call(arguments);
  6997. }
  6998. var result = fn(args);
  6999. // we're assuming the result is an array here.
  7000. // see notice in conversions.js; don't use box types
  7001. // in conversion functions.
  7002. if (typeof result === 'object') {
  7003. for (var len = result.length, i = 0; i < len; i++) {
  7004. result[i] = Math.round(result[i]);
  7005. }
  7006. }
  7007. return result;
  7008. };
  7009. // preserve .conversion property if there is one
  7010. if ('conversion' in fn) {
  7011. wrappedFn.conversion = fn.conversion;
  7012. }
  7013. return wrappedFn;
  7014. }
  7015. models.forEach(function (fromModel) {
  7016. convert[fromModel] = {};
  7017. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  7018. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  7019. var routes = route(fromModel);
  7020. var routeModels = Object.keys(routes);
  7021. routeModels.forEach(function (toModel) {
  7022. var fn = routes[toModel];
  7023. convert[fromModel][toModel] = wrapRounded(fn);
  7024. convert[fromModel][toModel].raw = wrapRaw(fn);
  7025. });
  7026. });
  7027. var colorConvert = convert;
  7028. var colorName$1 = {
  7029. "aliceblue": [240, 248, 255],
  7030. "antiquewhite": [250, 235, 215],
  7031. "aqua": [0, 255, 255],
  7032. "aquamarine": [127, 255, 212],
  7033. "azure": [240, 255, 255],
  7034. "beige": [245, 245, 220],
  7035. "bisque": [255, 228, 196],
  7036. "black": [0, 0, 0],
  7037. "blanchedalmond": [255, 235, 205],
  7038. "blue": [0, 0, 255],
  7039. "blueviolet": [138, 43, 226],
  7040. "brown": [165, 42, 42],
  7041. "burlywood": [222, 184, 135],
  7042. "cadetblue": [95, 158, 160],
  7043. "chartreuse": [127, 255, 0],
  7044. "chocolate": [210, 105, 30],
  7045. "coral": [255, 127, 80],
  7046. "cornflowerblue": [100, 149, 237],
  7047. "cornsilk": [255, 248, 220],
  7048. "crimson": [220, 20, 60],
  7049. "cyan": [0, 255, 255],
  7050. "darkblue": [0, 0, 139],
  7051. "darkcyan": [0, 139, 139],
  7052. "darkgoldenrod": [184, 134, 11],
  7053. "darkgray": [169, 169, 169],
  7054. "darkgreen": [0, 100, 0],
  7055. "darkgrey": [169, 169, 169],
  7056. "darkkhaki": [189, 183, 107],
  7057. "darkmagenta": [139, 0, 139],
  7058. "darkolivegreen": [85, 107, 47],
  7059. "darkorange": [255, 140, 0],
  7060. "darkorchid": [153, 50, 204],
  7061. "darkred": [139, 0, 0],
  7062. "darksalmon": [233, 150, 122],
  7063. "darkseagreen": [143, 188, 143],
  7064. "darkslateblue": [72, 61, 139],
  7065. "darkslategray": [47, 79, 79],
  7066. "darkslategrey": [47, 79, 79],
  7067. "darkturquoise": [0, 206, 209],
  7068. "darkviolet": [148, 0, 211],
  7069. "deeppink": [255, 20, 147],
  7070. "deepskyblue": [0, 191, 255],
  7071. "dimgray": [105, 105, 105],
  7072. "dimgrey": [105, 105, 105],
  7073. "dodgerblue": [30, 144, 255],
  7074. "firebrick": [178, 34, 34],
  7075. "floralwhite": [255, 250, 240],
  7076. "forestgreen": [34, 139, 34],
  7077. "fuchsia": [255, 0, 255],
  7078. "gainsboro": [220, 220, 220],
  7079. "ghostwhite": [248, 248, 255],
  7080. "gold": [255, 215, 0],
  7081. "goldenrod": [218, 165, 32],
  7082. "gray": [128, 128, 128],
  7083. "green": [0, 128, 0],
  7084. "greenyellow": [173, 255, 47],
  7085. "grey": [128, 128, 128],
  7086. "honeydew": [240, 255, 240],
  7087. "hotpink": [255, 105, 180],
  7088. "indianred": [205, 92, 92],
  7089. "indigo": [75, 0, 130],
  7090. "ivory": [255, 255, 240],
  7091. "khaki": [240, 230, 140],
  7092. "lavender": [230, 230, 250],
  7093. "lavenderblush": [255, 240, 245],
  7094. "lawngreen": [124, 252, 0],
  7095. "lemonchiffon": [255, 250, 205],
  7096. "lightblue": [173, 216, 230],
  7097. "lightcoral": [240, 128, 128],
  7098. "lightcyan": [224, 255, 255],
  7099. "lightgoldenrodyellow": [250, 250, 210],
  7100. "lightgray": [211, 211, 211],
  7101. "lightgreen": [144, 238, 144],
  7102. "lightgrey": [211, 211, 211],
  7103. "lightpink": [255, 182, 193],
  7104. "lightsalmon": [255, 160, 122],
  7105. "lightseagreen": [32, 178, 170],
  7106. "lightskyblue": [135, 206, 250],
  7107. "lightslategray": [119, 136, 153],
  7108. "lightslategrey": [119, 136, 153],
  7109. "lightsteelblue": [176, 196, 222],
  7110. "lightyellow": [255, 255, 224],
  7111. "lime": [0, 255, 0],
  7112. "limegreen": [50, 205, 50],
  7113. "linen": [250, 240, 230],
  7114. "magenta": [255, 0, 255],
  7115. "maroon": [128, 0, 0],
  7116. "mediumaquamarine": [102, 205, 170],
  7117. "mediumblue": [0, 0, 205],
  7118. "mediumorchid": [186, 85, 211],
  7119. "mediumpurple": [147, 112, 219],
  7120. "mediumseagreen": [60, 179, 113],
  7121. "mediumslateblue": [123, 104, 238],
  7122. "mediumspringgreen": [0, 250, 154],
  7123. "mediumturquoise": [72, 209, 204],
  7124. "mediumvioletred": [199, 21, 133],
  7125. "midnightblue": [25, 25, 112],
  7126. "mintcream": [245, 255, 250],
  7127. "mistyrose": [255, 228, 225],
  7128. "moccasin": [255, 228, 181],
  7129. "navajowhite": [255, 222, 173],
  7130. "navy": [0, 0, 128],
  7131. "oldlace": [253, 245, 230],
  7132. "olive": [128, 128, 0],
  7133. "olivedrab": [107, 142, 35],
  7134. "orange": [255, 165, 0],
  7135. "orangered": [255, 69, 0],
  7136. "orchid": [218, 112, 214],
  7137. "palegoldenrod": [238, 232, 170],
  7138. "palegreen": [152, 251, 152],
  7139. "paleturquoise": [175, 238, 238],
  7140. "palevioletred": [219, 112, 147],
  7141. "papayawhip": [255, 239, 213],
  7142. "peachpuff": [255, 218, 185],
  7143. "peru": [205, 133, 63],
  7144. "pink": [255, 192, 203],
  7145. "plum": [221, 160, 221],
  7146. "powderblue": [176, 224, 230],
  7147. "purple": [128, 0, 128],
  7148. "rebeccapurple": [102, 51, 153],
  7149. "red": [255, 0, 0],
  7150. "rosybrown": [188, 143, 143],
  7151. "royalblue": [65, 105, 225],
  7152. "saddlebrown": [139, 69, 19],
  7153. "salmon": [250, 128, 114],
  7154. "sandybrown": [244, 164, 96],
  7155. "seagreen": [46, 139, 87],
  7156. "seashell": [255, 245, 238],
  7157. "sienna": [160, 82, 45],
  7158. "silver": [192, 192, 192],
  7159. "skyblue": [135, 206, 235],
  7160. "slateblue": [106, 90, 205],
  7161. "slategray": [112, 128, 144],
  7162. "slategrey": [112, 128, 144],
  7163. "snow": [255, 250, 250],
  7164. "springgreen": [0, 255, 127],
  7165. "steelblue": [70, 130, 180],
  7166. "tan": [210, 180, 140],
  7167. "teal": [0, 128, 128],
  7168. "thistle": [216, 191, 216],
  7169. "tomato": [255, 99, 71],
  7170. "turquoise": [64, 224, 208],
  7171. "violet": [238, 130, 238],
  7172. "wheat": [245, 222, 179],
  7173. "white": [255, 255, 255],
  7174. "whitesmoke": [245, 245, 245],
  7175. "yellow": [255, 255, 0],
  7176. "yellowgreen": [154, 205, 50]
  7177. };
  7178. /* MIT license */
  7179. var colorString = {
  7180. getRgba: getRgba,
  7181. getHsla: getHsla,
  7182. getRgb: getRgb,
  7183. getHsl: getHsl,
  7184. getHwb: getHwb,
  7185. getAlpha: getAlpha,
  7186. hexString: hexString,
  7187. rgbString: rgbString,
  7188. rgbaString: rgbaString,
  7189. percentString: percentString,
  7190. percentaString: percentaString,
  7191. hslString: hslString,
  7192. hslaString: hslaString,
  7193. hwbString: hwbString,
  7194. keyword: keyword
  7195. };
  7196. function getRgba(string) {
  7197. if (!string) {
  7198. return;
  7199. }
  7200. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  7201. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  7202. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  7203. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  7204. keyword = /(\w+)/;
  7205. var rgb = [0, 0, 0],
  7206. a = 1,
  7207. match = string.match(abbr),
  7208. hexAlpha = "";
  7209. if (match) {
  7210. match = match[1];
  7211. hexAlpha = match[3];
  7212. for (var i = 0; i < rgb.length; i++) {
  7213. rgb[i] = parseInt(match[i] + match[i], 16);
  7214. }
  7215. if (hexAlpha) {
  7216. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  7217. }
  7218. }
  7219. else if (match = string.match(hex)) {
  7220. hexAlpha = match[2];
  7221. match = match[1];
  7222. for (var i = 0; i < rgb.length; i++) {
  7223. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  7224. }
  7225. if (hexAlpha) {
  7226. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  7227. }
  7228. }
  7229. else if (match = string.match(rgba)) {
  7230. for (var i = 0; i < rgb.length; i++) {
  7231. rgb[i] = parseInt(match[i + 1]);
  7232. }
  7233. a = parseFloat(match[4]);
  7234. }
  7235. else if (match = string.match(per)) {
  7236. for (var i = 0; i < rgb.length; i++) {
  7237. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  7238. }
  7239. a = parseFloat(match[4]);
  7240. }
  7241. else if (match = string.match(keyword)) {
  7242. if (match[1] == "transparent") {
  7243. return [0, 0, 0, 0];
  7244. }
  7245. rgb = colorName$1[match[1]];
  7246. if (!rgb) {
  7247. return;
  7248. }
  7249. }
  7250. for (var i = 0; i < rgb.length; i++) {
  7251. rgb[i] = scale(rgb[i], 0, 255);
  7252. }
  7253. if (!a && a != 0) {
  7254. a = 1;
  7255. }
  7256. else {
  7257. a = scale(a, 0, 1);
  7258. }
  7259. rgb[3] = a;
  7260. return rgb;
  7261. }
  7262. function getHsla(string) {
  7263. if (!string) {
  7264. return;
  7265. }
  7266. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  7267. var match = string.match(hsl);
  7268. if (match) {
  7269. var alpha = parseFloat(match[4]);
  7270. var h = scale(parseInt(match[1]), 0, 360),
  7271. s = scale(parseFloat(match[2]), 0, 100),
  7272. l = scale(parseFloat(match[3]), 0, 100),
  7273. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  7274. return [h, s, l, a];
  7275. }
  7276. }
  7277. function getHwb(string) {
  7278. if (!string) {
  7279. return;
  7280. }
  7281. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  7282. var match = string.match(hwb);
  7283. if (match) {
  7284. var alpha = parseFloat(match[4]);
  7285. var h = scale(parseInt(match[1]), 0, 360),
  7286. w = scale(parseFloat(match[2]), 0, 100),
  7287. b = scale(parseFloat(match[3]), 0, 100),
  7288. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  7289. return [h, w, b, a];
  7290. }
  7291. }
  7292. function getRgb(string) {
  7293. var rgba = getRgba(string);
  7294. return rgba && rgba.slice(0, 3);
  7295. }
  7296. function getHsl(string) {
  7297. var hsla = getHsla(string);
  7298. return hsla && hsla.slice(0, 3);
  7299. }
  7300. function getAlpha(string) {
  7301. var vals = getRgba(string);
  7302. if (vals) {
  7303. return vals[3];
  7304. }
  7305. else if (vals = getHsla(string)) {
  7306. return vals[3];
  7307. }
  7308. else if (vals = getHwb(string)) {
  7309. return vals[3];
  7310. }
  7311. }
  7312. // generators
  7313. function hexString(rgba, a) {
  7314. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  7315. return "#" + hexDouble(rgba[0])
  7316. + hexDouble(rgba[1])
  7317. + hexDouble(rgba[2])
  7318. + (
  7319. (a >= 0 && a < 1)
  7320. ? hexDouble(Math.round(a * 255))
  7321. : ""
  7322. );
  7323. }
  7324. function rgbString(rgba, alpha) {
  7325. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  7326. return rgbaString(rgba, alpha);
  7327. }
  7328. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  7329. }
  7330. function rgbaString(rgba, alpha) {
  7331. if (alpha === undefined) {
  7332. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  7333. }
  7334. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  7335. + ", " + alpha + ")";
  7336. }
  7337. function percentString(rgba, alpha) {
  7338. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  7339. return percentaString(rgba, alpha);
  7340. }
  7341. var r = Math.round(rgba[0]/255 * 100),
  7342. g = Math.round(rgba[1]/255 * 100),
  7343. b = Math.round(rgba[2]/255 * 100);
  7344. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  7345. }
  7346. function percentaString(rgba, alpha) {
  7347. var r = Math.round(rgba[0]/255 * 100),
  7348. g = Math.round(rgba[1]/255 * 100),
  7349. b = Math.round(rgba[2]/255 * 100);
  7350. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  7351. }
  7352. function hslString(hsla, alpha) {
  7353. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  7354. return hslaString(hsla, alpha);
  7355. }
  7356. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  7357. }
  7358. function hslaString(hsla, alpha) {
  7359. if (alpha === undefined) {
  7360. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  7361. }
  7362. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  7363. + alpha + ")";
  7364. }
  7365. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  7366. // (hwb have alpha optional & 1 is default value)
  7367. function hwbString(hwb, alpha) {
  7368. if (alpha === undefined) {
  7369. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  7370. }
  7371. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  7372. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  7373. }
  7374. function keyword(rgb) {
  7375. return reverseNames[rgb.slice(0, 3)];
  7376. }
  7377. // helpers
  7378. function scale(num, min, max) {
  7379. return Math.min(Math.max(min, num), max);
  7380. }
  7381. function hexDouble(num) {
  7382. var str = num.toString(16).toUpperCase();
  7383. return (str.length < 2) ? "0" + str : str;
  7384. }
  7385. //create a list of reverse color names
  7386. var reverseNames = {};
  7387. for (var name in colorName$1) {
  7388. reverseNames[colorName$1[name]] = name;
  7389. }
  7390. /* MIT license */
  7391. var Color = function (obj) {
  7392. if (obj instanceof Color) {
  7393. return obj;
  7394. }
  7395. if (!(this instanceof Color)) {
  7396. return new Color(obj);
  7397. }
  7398. this.valid = false;
  7399. this.values = {
  7400. rgb: [0, 0, 0],
  7401. hsl: [0, 0, 0],
  7402. hsv: [0, 0, 0],
  7403. hwb: [0, 0, 0],
  7404. cmyk: [0, 0, 0, 0],
  7405. alpha: 1
  7406. };
  7407. // parse Color() argument
  7408. var vals;
  7409. if (typeof obj === 'string') {
  7410. vals = colorString.getRgba(obj);
  7411. if (vals) {
  7412. this.setValues('rgb', vals);
  7413. } else if (vals = colorString.getHsla(obj)) {
  7414. this.setValues('hsl', vals);
  7415. } else if (vals = colorString.getHwb(obj)) {
  7416. this.setValues('hwb', vals);
  7417. }
  7418. } else if (typeof obj === 'object') {
  7419. vals = obj;
  7420. if (vals.r !== undefined || vals.red !== undefined) {
  7421. this.setValues('rgb', vals);
  7422. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  7423. this.setValues('hsl', vals);
  7424. } else if (vals.v !== undefined || vals.value !== undefined) {
  7425. this.setValues('hsv', vals);
  7426. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  7427. this.setValues('hwb', vals);
  7428. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  7429. this.setValues('cmyk', vals);
  7430. }
  7431. }
  7432. };
  7433. Color.prototype = {
  7434. isValid: function () {
  7435. return this.valid;
  7436. },
  7437. rgb: function () {
  7438. return this.setSpace('rgb', arguments);
  7439. },
  7440. hsl: function () {
  7441. return this.setSpace('hsl', arguments);
  7442. },
  7443. hsv: function () {
  7444. return this.setSpace('hsv', arguments);
  7445. },
  7446. hwb: function () {
  7447. return this.setSpace('hwb', arguments);
  7448. },
  7449. cmyk: function () {
  7450. return this.setSpace('cmyk', arguments);
  7451. },
  7452. rgbArray: function () {
  7453. return this.values.rgb;
  7454. },
  7455. hslArray: function () {
  7456. return this.values.hsl;
  7457. },
  7458. hsvArray: function () {
  7459. return this.values.hsv;
  7460. },
  7461. hwbArray: function () {
  7462. var values = this.values;
  7463. if (values.alpha !== 1) {
  7464. return values.hwb.concat([values.alpha]);
  7465. }
  7466. return values.hwb;
  7467. },
  7468. cmykArray: function () {
  7469. return this.values.cmyk;
  7470. },
  7471. rgbaArray: function () {
  7472. var values = this.values;
  7473. return values.rgb.concat([values.alpha]);
  7474. },
  7475. hslaArray: function () {
  7476. var values = this.values;
  7477. return values.hsl.concat([values.alpha]);
  7478. },
  7479. alpha: function (val) {
  7480. if (val === undefined) {
  7481. return this.values.alpha;
  7482. }
  7483. this.setValues('alpha', val);
  7484. return this;
  7485. },
  7486. red: function (val) {
  7487. return this.setChannel('rgb', 0, val);
  7488. },
  7489. green: function (val) {
  7490. return this.setChannel('rgb', 1, val);
  7491. },
  7492. blue: function (val) {
  7493. return this.setChannel('rgb', 2, val);
  7494. },
  7495. hue: function (val) {
  7496. if (val) {
  7497. val %= 360;
  7498. val = val < 0 ? 360 + val : val;
  7499. }
  7500. return this.setChannel('hsl', 0, val);
  7501. },
  7502. saturation: function (val) {
  7503. return this.setChannel('hsl', 1, val);
  7504. },
  7505. lightness: function (val) {
  7506. return this.setChannel('hsl', 2, val);
  7507. },
  7508. saturationv: function (val) {
  7509. return this.setChannel('hsv', 1, val);
  7510. },
  7511. whiteness: function (val) {
  7512. return this.setChannel('hwb', 1, val);
  7513. },
  7514. blackness: function (val) {
  7515. return this.setChannel('hwb', 2, val);
  7516. },
  7517. value: function (val) {
  7518. return this.setChannel('hsv', 2, val);
  7519. },
  7520. cyan: function (val) {
  7521. return this.setChannel('cmyk', 0, val);
  7522. },
  7523. magenta: function (val) {
  7524. return this.setChannel('cmyk', 1, val);
  7525. },
  7526. yellow: function (val) {
  7527. return this.setChannel('cmyk', 2, val);
  7528. },
  7529. black: function (val) {
  7530. return this.setChannel('cmyk', 3, val);
  7531. },
  7532. hexString: function () {
  7533. return colorString.hexString(this.values.rgb);
  7534. },
  7535. rgbString: function () {
  7536. return colorString.rgbString(this.values.rgb, this.values.alpha);
  7537. },
  7538. rgbaString: function () {
  7539. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  7540. },
  7541. percentString: function () {
  7542. return colorString.percentString(this.values.rgb, this.values.alpha);
  7543. },
  7544. hslString: function () {
  7545. return colorString.hslString(this.values.hsl, this.values.alpha);
  7546. },
  7547. hslaString: function () {
  7548. return colorString.hslaString(this.values.hsl, this.values.alpha);
  7549. },
  7550. hwbString: function () {
  7551. return colorString.hwbString(this.values.hwb, this.values.alpha);
  7552. },
  7553. keyword: function () {
  7554. return colorString.keyword(this.values.rgb, this.values.alpha);
  7555. },
  7556. rgbNumber: function () {
  7557. var rgb = this.values.rgb;
  7558. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  7559. },
  7560. luminosity: function () {
  7561. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  7562. var rgb = this.values.rgb;
  7563. var lum = [];
  7564. for (var i = 0; i < rgb.length; i++) {
  7565. var chan = rgb[i] / 255;
  7566. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  7567. }
  7568. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  7569. },
  7570. contrast: function (color2) {
  7571. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  7572. var lum1 = this.luminosity();
  7573. var lum2 = color2.luminosity();
  7574. if (lum1 > lum2) {
  7575. return (lum1 + 0.05) / (lum2 + 0.05);
  7576. }
  7577. return (lum2 + 0.05) / (lum1 + 0.05);
  7578. },
  7579. level: function (color2) {
  7580. var contrastRatio = this.contrast(color2);
  7581. if (contrastRatio >= 7.1) {
  7582. return 'AAA';
  7583. }
  7584. return (contrastRatio >= 4.5) ? 'AA' : '';
  7585. },
  7586. dark: function () {
  7587. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  7588. var rgb = this.values.rgb;
  7589. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  7590. return yiq < 128;
  7591. },
  7592. light: function () {
  7593. return !this.dark();
  7594. },
  7595. negate: function () {
  7596. var rgb = [];
  7597. for (var i = 0; i < 3; i++) {
  7598. rgb[i] = 255 - this.values.rgb[i];
  7599. }
  7600. this.setValues('rgb', rgb);
  7601. return this;
  7602. },
  7603. lighten: function (ratio) {
  7604. var hsl = this.values.hsl;
  7605. hsl[2] += hsl[2] * ratio;
  7606. this.setValues('hsl', hsl);
  7607. return this;
  7608. },
  7609. darken: function (ratio) {
  7610. var hsl = this.values.hsl;
  7611. hsl[2] -= hsl[2] * ratio;
  7612. this.setValues('hsl', hsl);
  7613. return this;
  7614. },
  7615. saturate: function (ratio) {
  7616. var hsl = this.values.hsl;
  7617. hsl[1] += hsl[1] * ratio;
  7618. this.setValues('hsl', hsl);
  7619. return this;
  7620. },
  7621. desaturate: function (ratio) {
  7622. var hsl = this.values.hsl;
  7623. hsl[1] -= hsl[1] * ratio;
  7624. this.setValues('hsl', hsl);
  7625. return this;
  7626. },
  7627. whiten: function (ratio) {
  7628. var hwb = this.values.hwb;
  7629. hwb[1] += hwb[1] * ratio;
  7630. this.setValues('hwb', hwb);
  7631. return this;
  7632. },
  7633. blacken: function (ratio) {
  7634. var hwb = this.values.hwb;
  7635. hwb[2] += hwb[2] * ratio;
  7636. this.setValues('hwb', hwb);
  7637. return this;
  7638. },
  7639. greyscale: function () {
  7640. var rgb = this.values.rgb;
  7641. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  7642. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  7643. this.setValues('rgb', [val, val, val]);
  7644. return this;
  7645. },
  7646. clearer: function (ratio) {
  7647. var alpha = this.values.alpha;
  7648. this.setValues('alpha', alpha - (alpha * ratio));
  7649. return this;
  7650. },
  7651. opaquer: function (ratio) {
  7652. var alpha = this.values.alpha;
  7653. this.setValues('alpha', alpha + (alpha * ratio));
  7654. return this;
  7655. },
  7656. rotate: function (degrees) {
  7657. var hsl = this.values.hsl;
  7658. var hue = (hsl[0] + degrees) % 360;
  7659. hsl[0] = hue < 0 ? 360 + hue : hue;
  7660. this.setValues('hsl', hsl);
  7661. return this;
  7662. },
  7663. /**
  7664. * Ported from sass implementation in C
  7665. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  7666. */
  7667. mix: function (mixinColor, weight) {
  7668. var color1 = this;
  7669. var color2 = mixinColor;
  7670. var p = weight === undefined ? 0.5 : weight;
  7671. var w = 2 * p - 1;
  7672. var a = color1.alpha() - color2.alpha();
  7673. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  7674. var w2 = 1 - w1;
  7675. return this
  7676. .rgb(
  7677. w1 * color1.red() + w2 * color2.red(),
  7678. w1 * color1.green() + w2 * color2.green(),
  7679. w1 * color1.blue() + w2 * color2.blue()
  7680. )
  7681. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  7682. },
  7683. toJSON: function () {
  7684. return this.rgb();
  7685. },
  7686. clone: function () {
  7687. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  7688. // making the final build way to big to embed in Chart.js. So let's do it manually,
  7689. // assuming that values to clone are 1 dimension arrays containing only numbers,
  7690. // except 'alpha' which is a number.
  7691. var result = new Color();
  7692. var source = this.values;
  7693. var target = result.values;
  7694. var value, type;
  7695. for (var prop in source) {
  7696. if (source.hasOwnProperty(prop)) {
  7697. value = source[prop];
  7698. type = ({}).toString.call(value);
  7699. if (type === '[object Array]') {
  7700. target[prop] = value.slice(0);
  7701. } else if (type === '[object Number]') {
  7702. target[prop] = value;
  7703. } else {
  7704. console.error('unexpected color value:', value);
  7705. }
  7706. }
  7707. }
  7708. return result;
  7709. }
  7710. };
  7711. Color.prototype.spaces = {
  7712. rgb: ['red', 'green', 'blue'],
  7713. hsl: ['hue', 'saturation', 'lightness'],
  7714. hsv: ['hue', 'saturation', 'value'],
  7715. hwb: ['hue', 'whiteness', 'blackness'],
  7716. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  7717. };
  7718. Color.prototype.maxes = {
  7719. rgb: [255, 255, 255],
  7720. hsl: [360, 100, 100],
  7721. hsv: [360, 100, 100],
  7722. hwb: [360, 100, 100],
  7723. cmyk: [100, 100, 100, 100]
  7724. };
  7725. Color.prototype.getValues = function (space) {
  7726. var values = this.values;
  7727. var vals = {};
  7728. for (var i = 0; i < space.length; i++) {
  7729. vals[space.charAt(i)] = values[space][i];
  7730. }
  7731. if (values.alpha !== 1) {
  7732. vals.a = values.alpha;
  7733. }
  7734. // {r: 255, g: 255, b: 255, a: 0.4}
  7735. return vals;
  7736. };
  7737. Color.prototype.setValues = function (space, vals) {
  7738. var values = this.values;
  7739. var spaces = this.spaces;
  7740. var maxes = this.maxes;
  7741. var alpha = 1;
  7742. var i;
  7743. this.valid = true;
  7744. if (space === 'alpha') {
  7745. alpha = vals;
  7746. } else if (vals.length) {
  7747. // [10, 10, 10]
  7748. values[space] = vals.slice(0, space.length);
  7749. alpha = vals[space.length];
  7750. } else if (vals[space.charAt(0)] !== undefined) {
  7751. // {r: 10, g: 10, b: 10}
  7752. for (i = 0; i < space.length; i++) {
  7753. values[space][i] = vals[space.charAt(i)];
  7754. }
  7755. alpha = vals.a;
  7756. } else if (vals[spaces[space][0]] !== undefined) {
  7757. // {red: 10, green: 10, blue: 10}
  7758. var chans = spaces[space];
  7759. for (i = 0; i < space.length; i++) {
  7760. values[space][i] = vals[chans[i]];
  7761. }
  7762. alpha = vals.alpha;
  7763. }
  7764. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  7765. if (space === 'alpha') {
  7766. return false;
  7767. }
  7768. var capped;
  7769. // cap values of the space prior converting all values
  7770. for (i = 0; i < space.length; i++) {
  7771. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  7772. values[space][i] = Math.round(capped);
  7773. }
  7774. // convert to all the other color spaces
  7775. for (var sname in spaces) {
  7776. if (sname !== space) {
  7777. values[sname] = colorConvert[space][sname](values[space]);
  7778. }
  7779. }
  7780. return true;
  7781. };
  7782. Color.prototype.setSpace = function (space, args) {
  7783. var vals = args[0];
  7784. if (vals === undefined) {
  7785. // color.rgb()
  7786. return this.getValues(space);
  7787. }
  7788. // color.rgb(10, 10, 10)
  7789. if (typeof vals === 'number') {
  7790. vals = Array.prototype.slice.call(args);
  7791. }
  7792. this.setValues(space, vals);
  7793. return this;
  7794. };
  7795. Color.prototype.setChannel = function (space, index, val) {
  7796. var svalues = this.values[space];
  7797. if (val === undefined) {
  7798. // color.red()
  7799. return svalues[index];
  7800. } else if (val === svalues[index]) {
  7801. // color.red(color.red())
  7802. return this;
  7803. }
  7804. // color.red(100)
  7805. svalues[index] = val;
  7806. this.setValues(space, svalues);
  7807. return this;
  7808. };
  7809. if (typeof window !== 'undefined') {
  7810. window.Color = Color;
  7811. }
  7812. var chartjsColor = Color;
  7813. function isValidKey(key) {
  7814. return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;
  7815. }
  7816. /**
  7817. * @namespace Chart.helpers
  7818. */
  7819. var helpers = {
  7820. /**
  7821. * An empty function that can be used, for example, for optional callback.
  7822. */
  7823. noop: function() {},
  7824. /**
  7825. * Returns a unique id, sequentially generated from a global variable.
  7826. * @returns {number}
  7827. * @function
  7828. */
  7829. uid: (function() {
  7830. var id = 0;
  7831. return function() {
  7832. return id++;
  7833. };
  7834. }()),
  7835. /**
  7836. * Returns true if `value` is neither null nor undefined, else returns false.
  7837. * @param {*} value - The value to test.
  7838. * @returns {boolean}
  7839. * @since 2.7.0
  7840. */
  7841. isNullOrUndef: function(value) {
  7842. return value === null || typeof value === 'undefined';
  7843. },
  7844. /**
  7845. * Returns true if `value` is an array (including typed arrays), else returns false.
  7846. * @param {*} value - The value to test.
  7847. * @returns {boolean}
  7848. * @function
  7849. */
  7850. isArray: function(value) {
  7851. if (Array.isArray && Array.isArray(value)) {
  7852. return true;
  7853. }
  7854. var type = Object.prototype.toString.call(value);
  7855. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  7856. return true;
  7857. }
  7858. return false;
  7859. },
  7860. /**
  7861. * Returns true if `value` is an object (excluding null), else returns false.
  7862. * @param {*} value - The value to test.
  7863. * @returns {boolean}
  7864. * @since 2.7.0
  7865. */
  7866. isObject: function(value) {
  7867. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  7868. },
  7869. /**
  7870. * Returns true if `value` is a finite number, else returns false
  7871. * @param {*} value - The value to test.
  7872. * @returns {boolean}
  7873. */
  7874. isFinite: function(value) {
  7875. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  7876. },
  7877. /**
  7878. * Returns `value` if defined, else returns `defaultValue`.
  7879. * @param {*} value - The value to return if defined.
  7880. * @param {*} defaultValue - The value to return if `value` is undefined.
  7881. * @returns {*}
  7882. */
  7883. valueOrDefault: function(value, defaultValue) {
  7884. return typeof value === 'undefined' ? defaultValue : value;
  7885. },
  7886. /**
  7887. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  7888. * @param {Array} value - The array to lookup for value at `index`.
  7889. * @param {number} index - The index in `value` to lookup for value.
  7890. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  7891. * @returns {*}
  7892. */
  7893. valueAtIndexOrDefault: function(value, index, defaultValue) {
  7894. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  7895. },
  7896. /**
  7897. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  7898. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  7899. * @param {function} fn - The function to call.
  7900. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  7901. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  7902. * @returns {*}
  7903. */
  7904. callback: function(fn, args, thisArg) {
  7905. if (fn && typeof fn.call === 'function') {
  7906. return fn.apply(thisArg, args);
  7907. }
  7908. },
  7909. /**
  7910. * Note(SB) for performance sake, this method should only be used when loopable type
  7911. * is unknown or in none intensive code (not called often and small loopable). Else
  7912. * it's preferable to use a regular for() loop and save extra function calls.
  7913. * @param {object|Array} loopable - The object or array to be iterated.
  7914. * @param {function} fn - The function to call for each item.
  7915. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  7916. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  7917. */
  7918. each: function(loopable, fn, thisArg, reverse) {
  7919. var i, len, keys;
  7920. if (helpers.isArray(loopable)) {
  7921. len = loopable.length;
  7922. if (reverse) {
  7923. for (i = len - 1; i >= 0; i--) {
  7924. fn.call(thisArg, loopable[i], i);
  7925. }
  7926. } else {
  7927. for (i = 0; i < len; i++) {
  7928. fn.call(thisArg, loopable[i], i);
  7929. }
  7930. }
  7931. } else if (helpers.isObject(loopable)) {
  7932. keys = Object.keys(loopable);
  7933. len = keys.length;
  7934. for (i = 0; i < len; i++) {
  7935. fn.call(thisArg, loopable[keys[i]], keys[i]);
  7936. }
  7937. }
  7938. },
  7939. /**
  7940. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  7941. * @see https://stackoverflow.com/a/14853974
  7942. * @param {Array} a0 - The array to compare
  7943. * @param {Array} a1 - The array to compare
  7944. * @returns {boolean}
  7945. */
  7946. arrayEquals: function(a0, a1) {
  7947. var i, ilen, v0, v1;
  7948. if (!a0 || !a1 || a0.length !== a1.length) {
  7949. return false;
  7950. }
  7951. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  7952. v0 = a0[i];
  7953. v1 = a1[i];
  7954. if (v0 instanceof Array && v1 instanceof Array) {
  7955. if (!helpers.arrayEquals(v0, v1)) {
  7956. return false;
  7957. }
  7958. } else if (v0 !== v1) {
  7959. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  7960. return false;
  7961. }
  7962. }
  7963. return true;
  7964. },
  7965. /**
  7966. * Returns a deep copy of `source` without keeping references on objects and arrays.
  7967. * @param {*} source - The value to clone.
  7968. * @returns {*}
  7969. */
  7970. clone: function(source) {
  7971. if (helpers.isArray(source)) {
  7972. return source.map(helpers.clone);
  7973. }
  7974. if (helpers.isObject(source)) {
  7975. var target = Object.create(source);
  7976. var keys = Object.keys(source);
  7977. var klen = keys.length;
  7978. var k = 0;
  7979. for (; k < klen; ++k) {
  7980. target[keys[k]] = helpers.clone(source[keys[k]]);
  7981. }
  7982. return target;
  7983. }
  7984. return source;
  7985. },
  7986. /**
  7987. * The default merger when Chart.helpers.merge is called without merger option.
  7988. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  7989. * @private
  7990. */
  7991. _merger: function(key, target, source, options) {
  7992. if (!isValidKey(key)) {
  7993. // We want to ensure we do not copy prototypes over
  7994. // as this can pollute global namespaces
  7995. return;
  7996. }
  7997. var tval = target[key];
  7998. var sval = source[key];
  7999. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  8000. helpers.merge(tval, sval, options);
  8001. } else {
  8002. target[key] = helpers.clone(sval);
  8003. }
  8004. },
  8005. /**
  8006. * Merges source[key] in target[key] only if target[key] is undefined.
  8007. * @private
  8008. */
  8009. _mergerIf: function(key, target, source) {
  8010. if (!isValidKey(key)) {
  8011. // We want to ensure we do not copy prototypes over
  8012. // as this can pollute global namespaces
  8013. return;
  8014. }
  8015. var tval = target[key];
  8016. var sval = source[key];
  8017. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  8018. helpers.mergeIf(tval, sval);
  8019. } else if (!target.hasOwnProperty(key)) {
  8020. target[key] = helpers.clone(sval);
  8021. }
  8022. },
  8023. /**
  8024. * Recursively deep copies `source` properties into `target` with the given `options`.
  8025. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  8026. * @param {object} target - The target object in which all sources are merged into.
  8027. * @param {object|object[]} source - Object(s) to merge into `target`.
  8028. * @param {object} [options] - Merging options:
  8029. * @param {function} [options.merger] - The merge method (key, target, source, options)
  8030. * @returns {object} The `target` object.
  8031. */
  8032. merge: function(target, source, options) {
  8033. var sources = helpers.isArray(source) ? source : [source];
  8034. var ilen = sources.length;
  8035. var merge, i, keys, klen, k;
  8036. if (!helpers.isObject(target)) {
  8037. return target;
  8038. }
  8039. options = options || {};
  8040. merge = options.merger || helpers._merger;
  8041. for (i = 0; i < ilen; ++i) {
  8042. source = sources[i];
  8043. if (!helpers.isObject(source)) {
  8044. continue;
  8045. }
  8046. keys = Object.keys(source);
  8047. for (k = 0, klen = keys.length; k < klen; ++k) {
  8048. merge(keys[k], target, source, options);
  8049. }
  8050. }
  8051. return target;
  8052. },
  8053. /**
  8054. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  8055. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  8056. * @param {object} target - The target object in which all sources are merged into.
  8057. * @param {object|object[]} source - Object(s) to merge into `target`.
  8058. * @returns {object} The `target` object.
  8059. */
  8060. mergeIf: function(target, source) {
  8061. return helpers.merge(target, source, {merger: helpers._mergerIf});
  8062. },
  8063. /**
  8064. * Applies the contents of two or more objects together into the first object.
  8065. * @param {object} target - The target object in which all objects are merged into.
  8066. * @param {object} arg1 - Object containing additional properties to merge in target.
  8067. * @param {object} argN - Additional objects containing properties to merge in target.
  8068. * @returns {object} The `target` object.
  8069. */
  8070. extend: Object.assign || function(target) {
  8071. return helpers.merge(target, [].slice.call(arguments, 1), {
  8072. merger: function(key, dst, src) {
  8073. dst[key] = src[key];
  8074. }
  8075. });
  8076. },
  8077. /**
  8078. * Basic javascript inheritance based on the model created in Backbone.js
  8079. */
  8080. inherits: function(extensions) {
  8081. var me = this;
  8082. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  8083. return me.apply(this, arguments);
  8084. };
  8085. var Surrogate = function() {
  8086. this.constructor = ChartElement;
  8087. };
  8088. Surrogate.prototype = me.prototype;
  8089. ChartElement.prototype = new Surrogate();
  8090. ChartElement.extend = helpers.inherits;
  8091. if (extensions) {
  8092. helpers.extend(ChartElement.prototype, extensions);
  8093. }
  8094. ChartElement.__super__ = me.prototype;
  8095. return ChartElement;
  8096. },
  8097. _deprecated: function(scope, value, previous, current) {
  8098. if (value !== undefined) {
  8099. console.warn(scope + ': "' + previous +
  8100. '" is deprecated. Please use "' + current + '" instead');
  8101. }
  8102. }
  8103. };
  8104. var helpers_core = helpers;
  8105. // DEPRECATIONS
  8106. /**
  8107. * Provided for backward compatibility, use Chart.helpers.callback instead.
  8108. * @function Chart.helpers.callCallback
  8109. * @deprecated since version 2.6.0
  8110. * @todo remove at version 3
  8111. * @private
  8112. */
  8113. helpers.callCallback = helpers.callback;
  8114. /**
  8115. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  8116. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  8117. * @function Chart.helpers.indexOf
  8118. * @deprecated since version 2.7.0
  8119. * @todo remove at version 3
  8120. * @private
  8121. */
  8122. helpers.indexOf = function(array, item, fromIndex) {
  8123. return Array.prototype.indexOf.call(array, item, fromIndex);
  8124. };
  8125. /**
  8126. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  8127. * @function Chart.helpers.getValueOrDefault
  8128. * @deprecated since version 2.7.0
  8129. * @todo remove at version 3
  8130. * @private
  8131. */
  8132. helpers.getValueOrDefault = helpers.valueOrDefault;
  8133. /**
  8134. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  8135. * @function Chart.helpers.getValueAtIndexOrDefault
  8136. * @deprecated since version 2.7.0
  8137. * @todo remove at version 3
  8138. * @private
  8139. */
  8140. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  8141. /**
  8142. * Easing functions adapted from Robert Penner's easing equations.
  8143. * @namespace Chart.helpers.easingEffects
  8144. * @see http://www.robertpenner.com/easing/
  8145. */
  8146. var effects = {
  8147. linear: function(t) {
  8148. return t;
  8149. },
  8150. easeInQuad: function(t) {
  8151. return t * t;
  8152. },
  8153. easeOutQuad: function(t) {
  8154. return -t * (t - 2);
  8155. },
  8156. easeInOutQuad: function(t) {
  8157. if ((t /= 0.5) < 1) {
  8158. return 0.5 * t * t;
  8159. }
  8160. return -0.5 * ((--t) * (t - 2) - 1);
  8161. },
  8162. easeInCubic: function(t) {
  8163. return t * t * t;
  8164. },
  8165. easeOutCubic: function(t) {
  8166. return (t = t - 1) * t * t + 1;
  8167. },
  8168. easeInOutCubic: function(t) {
  8169. if ((t /= 0.5) < 1) {
  8170. return 0.5 * t * t * t;
  8171. }
  8172. return 0.5 * ((t -= 2) * t * t + 2);
  8173. },
  8174. easeInQuart: function(t) {
  8175. return t * t * t * t;
  8176. },
  8177. easeOutQuart: function(t) {
  8178. return -((t = t - 1) * t * t * t - 1);
  8179. },
  8180. easeInOutQuart: function(t) {
  8181. if ((t /= 0.5) < 1) {
  8182. return 0.5 * t * t * t * t;
  8183. }
  8184. return -0.5 * ((t -= 2) * t * t * t - 2);
  8185. },
  8186. easeInQuint: function(t) {
  8187. return t * t * t * t * t;
  8188. },
  8189. easeOutQuint: function(t) {
  8190. return (t = t - 1) * t * t * t * t + 1;
  8191. },
  8192. easeInOutQuint: function(t) {
  8193. if ((t /= 0.5) < 1) {
  8194. return 0.5 * t * t * t * t * t;
  8195. }
  8196. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  8197. },
  8198. easeInSine: function(t) {
  8199. return -Math.cos(t * (Math.PI / 2)) + 1;
  8200. },
  8201. easeOutSine: function(t) {
  8202. return Math.sin(t * (Math.PI / 2));
  8203. },
  8204. easeInOutSine: function(t) {
  8205. return -0.5 * (Math.cos(Math.PI * t) - 1);
  8206. },
  8207. easeInExpo: function(t) {
  8208. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  8209. },
  8210. easeOutExpo: function(t) {
  8211. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  8212. },
  8213. easeInOutExpo: function(t) {
  8214. if (t === 0) {
  8215. return 0;
  8216. }
  8217. if (t === 1) {
  8218. return 1;
  8219. }
  8220. if ((t /= 0.5) < 1) {
  8221. return 0.5 * Math.pow(2, 10 * (t - 1));
  8222. }
  8223. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  8224. },
  8225. easeInCirc: function(t) {
  8226. if (t >= 1) {
  8227. return t;
  8228. }
  8229. return -(Math.sqrt(1 - t * t) - 1);
  8230. },
  8231. easeOutCirc: function(t) {
  8232. return Math.sqrt(1 - (t = t - 1) * t);
  8233. },
  8234. easeInOutCirc: function(t) {
  8235. if ((t /= 0.5) < 1) {
  8236. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  8237. }
  8238. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  8239. },
  8240. easeInElastic: function(t) {
  8241. var s = 1.70158;
  8242. var p = 0;
  8243. var a = 1;
  8244. if (t === 0) {
  8245. return 0;
  8246. }
  8247. if (t === 1) {
  8248. return 1;
  8249. }
  8250. if (!p) {
  8251. p = 0.3;
  8252. }
  8253. {
  8254. s = p / (2 * Math.PI) * Math.asin(1 / a);
  8255. }
  8256. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  8257. },
  8258. easeOutElastic: function(t) {
  8259. var s = 1.70158;
  8260. var p = 0;
  8261. var a = 1;
  8262. if (t === 0) {
  8263. return 0;
  8264. }
  8265. if (t === 1) {
  8266. return 1;
  8267. }
  8268. if (!p) {
  8269. p = 0.3;
  8270. }
  8271. {
  8272. s = p / (2 * Math.PI) * Math.asin(1 / a);
  8273. }
  8274. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  8275. },
  8276. easeInOutElastic: function(t) {
  8277. var s = 1.70158;
  8278. var p = 0;
  8279. var a = 1;
  8280. if (t === 0) {
  8281. return 0;
  8282. }
  8283. if ((t /= 0.5) === 2) {
  8284. return 1;
  8285. }
  8286. if (!p) {
  8287. p = 0.45;
  8288. }
  8289. {
  8290. s = p / (2 * Math.PI) * Math.asin(1 / a);
  8291. }
  8292. if (t < 1) {
  8293. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  8294. }
  8295. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  8296. },
  8297. easeInBack: function(t) {
  8298. var s = 1.70158;
  8299. return t * t * ((s + 1) * t - s);
  8300. },
  8301. easeOutBack: function(t) {
  8302. var s = 1.70158;
  8303. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  8304. },
  8305. easeInOutBack: function(t) {
  8306. var s = 1.70158;
  8307. if ((t /= 0.5) < 1) {
  8308. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  8309. }
  8310. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  8311. },
  8312. easeInBounce: function(t) {
  8313. return 1 - effects.easeOutBounce(1 - t);
  8314. },
  8315. easeOutBounce: function(t) {
  8316. if (t < (1 / 2.75)) {
  8317. return 7.5625 * t * t;
  8318. }
  8319. if (t < (2 / 2.75)) {
  8320. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  8321. }
  8322. if (t < (2.5 / 2.75)) {
  8323. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  8324. }
  8325. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  8326. },
  8327. easeInOutBounce: function(t) {
  8328. if (t < 0.5) {
  8329. return effects.easeInBounce(t * 2) * 0.5;
  8330. }
  8331. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  8332. }
  8333. };
  8334. var helpers_easing = {
  8335. effects: effects
  8336. };
  8337. // DEPRECATIONS
  8338. /**
  8339. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  8340. * @function Chart.helpers.easingEffects
  8341. * @deprecated since version 2.7.0
  8342. * @todo remove at version 3
  8343. * @private
  8344. */
  8345. helpers_core.easingEffects = effects;
  8346. var PI = Math.PI;
  8347. var RAD_PER_DEG = PI / 180;
  8348. var DOUBLE_PI = PI * 2;
  8349. var HALF_PI = PI / 2;
  8350. var QUARTER_PI = PI / 4;
  8351. var TWO_THIRDS_PI = PI * 2 / 3;
  8352. /**
  8353. * @namespace Chart.helpers.canvas
  8354. */
  8355. var exports$1 = {
  8356. /**
  8357. * Clears the entire canvas associated to the given `chart`.
  8358. * @param {Chart} chart - The chart for which to clear the canvas.
  8359. */
  8360. clear: function(chart) {
  8361. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  8362. },
  8363. /**
  8364. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  8365. * given size (width, height) and the same `radius` for all corners.
  8366. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  8367. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  8368. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  8369. * @param {number} width - The rectangle's width.
  8370. * @param {number} height - The rectangle's height.
  8371. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  8372. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  8373. */
  8374. roundedRect: function(ctx, x, y, width, height, radius) {
  8375. if (radius) {
  8376. var r = Math.min(radius, height / 2, width / 2);
  8377. var left = x + r;
  8378. var top = y + r;
  8379. var right = x + width - r;
  8380. var bottom = y + height - r;
  8381. ctx.moveTo(x, top);
  8382. if (left < right && top < bottom) {
  8383. ctx.arc(left, top, r, -PI, -HALF_PI);
  8384. ctx.arc(right, top, r, -HALF_PI, 0);
  8385. ctx.arc(right, bottom, r, 0, HALF_PI);
  8386. ctx.arc(left, bottom, r, HALF_PI, PI);
  8387. } else if (left < right) {
  8388. ctx.moveTo(left, y);
  8389. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  8390. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  8391. } else if (top < bottom) {
  8392. ctx.arc(left, top, r, -PI, 0);
  8393. ctx.arc(left, bottom, r, 0, PI);
  8394. } else {
  8395. ctx.arc(left, top, r, -PI, PI);
  8396. }
  8397. ctx.closePath();
  8398. ctx.moveTo(x, y);
  8399. } else {
  8400. ctx.rect(x, y, width, height);
  8401. }
  8402. },
  8403. drawPoint: function(ctx, style, radius, x, y, rotation) {
  8404. var type, xOffset, yOffset, size, cornerRadius;
  8405. var rad = (rotation || 0) * RAD_PER_DEG;
  8406. if (style && typeof style === 'object') {
  8407. type = style.toString();
  8408. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  8409. ctx.save();
  8410. ctx.translate(x, y);
  8411. ctx.rotate(rad);
  8412. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  8413. ctx.restore();
  8414. return;
  8415. }
  8416. }
  8417. if (isNaN(radius) || radius <= 0) {
  8418. return;
  8419. }
  8420. ctx.beginPath();
  8421. switch (style) {
  8422. // Default includes circle
  8423. default:
  8424. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  8425. ctx.closePath();
  8426. break;
  8427. case 'triangle':
  8428. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  8429. rad += TWO_THIRDS_PI;
  8430. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  8431. rad += TWO_THIRDS_PI;
  8432. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  8433. ctx.closePath();
  8434. break;
  8435. case 'rectRounded':
  8436. // NOTE: the rounded rect implementation changed to use `arc` instead of
  8437. // `quadraticCurveTo` since it generates better results when rect is
  8438. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  8439. // closer proportion to the previous impl and it is inscribed in the
  8440. // circle with `radius`. For more details, see the following PRs:
  8441. // https://github.com/chartjs/Chart.js/issues/5597
  8442. // https://github.com/chartjs/Chart.js/issues/5858
  8443. cornerRadius = radius * 0.516;
  8444. size = radius - cornerRadius;
  8445. xOffset = Math.cos(rad + QUARTER_PI) * size;
  8446. yOffset = Math.sin(rad + QUARTER_PI) * size;
  8447. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  8448. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  8449. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  8450. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  8451. ctx.closePath();
  8452. break;
  8453. case 'rect':
  8454. if (!rotation) {
  8455. size = Math.SQRT1_2 * radius;
  8456. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  8457. break;
  8458. }
  8459. rad += QUARTER_PI;
  8460. /* falls through */
  8461. case 'rectRot':
  8462. xOffset = Math.cos(rad) * radius;
  8463. yOffset = Math.sin(rad) * radius;
  8464. ctx.moveTo(x - xOffset, y - yOffset);
  8465. ctx.lineTo(x + yOffset, y - xOffset);
  8466. ctx.lineTo(x + xOffset, y + yOffset);
  8467. ctx.lineTo(x - yOffset, y + xOffset);
  8468. ctx.closePath();
  8469. break;
  8470. case 'crossRot':
  8471. rad += QUARTER_PI;
  8472. /* falls through */
  8473. case 'cross':
  8474. xOffset = Math.cos(rad) * radius;
  8475. yOffset = Math.sin(rad) * radius;
  8476. ctx.moveTo(x - xOffset, y - yOffset);
  8477. ctx.lineTo(x + xOffset, y + yOffset);
  8478. ctx.moveTo(x + yOffset, y - xOffset);
  8479. ctx.lineTo(x - yOffset, y + xOffset);
  8480. break;
  8481. case 'star':
  8482. xOffset = Math.cos(rad) * radius;
  8483. yOffset = Math.sin(rad) * radius;
  8484. ctx.moveTo(x - xOffset, y - yOffset);
  8485. ctx.lineTo(x + xOffset, y + yOffset);
  8486. ctx.moveTo(x + yOffset, y - xOffset);
  8487. ctx.lineTo(x - yOffset, y + xOffset);
  8488. rad += QUARTER_PI;
  8489. xOffset = Math.cos(rad) * radius;
  8490. yOffset = Math.sin(rad) * radius;
  8491. ctx.moveTo(x - xOffset, y - yOffset);
  8492. ctx.lineTo(x + xOffset, y + yOffset);
  8493. ctx.moveTo(x + yOffset, y - xOffset);
  8494. ctx.lineTo(x - yOffset, y + xOffset);
  8495. break;
  8496. case 'line':
  8497. xOffset = Math.cos(rad) * radius;
  8498. yOffset = Math.sin(rad) * radius;
  8499. ctx.moveTo(x - xOffset, y - yOffset);
  8500. ctx.lineTo(x + xOffset, y + yOffset);
  8501. break;
  8502. case 'dash':
  8503. ctx.moveTo(x, y);
  8504. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  8505. break;
  8506. }
  8507. ctx.fill();
  8508. ctx.stroke();
  8509. },
  8510. /**
  8511. * Returns true if the point is inside the rectangle
  8512. * @param {object} point - The point to test
  8513. * @param {object} area - The rectangle
  8514. * @returns {boolean}
  8515. * @private
  8516. */
  8517. _isPointInArea: function(point, area) {
  8518. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  8519. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  8520. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  8521. },
  8522. clipArea: function(ctx, area) {
  8523. ctx.save();
  8524. ctx.beginPath();
  8525. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  8526. ctx.clip();
  8527. },
  8528. unclipArea: function(ctx) {
  8529. ctx.restore();
  8530. },
  8531. lineTo: function(ctx, previous, target, flip) {
  8532. var stepped = target.steppedLine;
  8533. if (stepped) {
  8534. if (stepped === 'middle') {
  8535. var midpoint = (previous.x + target.x) / 2.0;
  8536. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  8537. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  8538. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  8539. ctx.lineTo(previous.x, target.y);
  8540. } else {
  8541. ctx.lineTo(target.x, previous.y);
  8542. }
  8543. ctx.lineTo(target.x, target.y);
  8544. return;
  8545. }
  8546. if (!target.tension) {
  8547. ctx.lineTo(target.x, target.y);
  8548. return;
  8549. }
  8550. ctx.bezierCurveTo(
  8551. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  8552. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  8553. flip ? target.controlPointNextX : target.controlPointPreviousX,
  8554. flip ? target.controlPointNextY : target.controlPointPreviousY,
  8555. target.x,
  8556. target.y);
  8557. }
  8558. };
  8559. var helpers_canvas = exports$1;
  8560. // DEPRECATIONS
  8561. /**
  8562. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  8563. * @namespace Chart.helpers.clear
  8564. * @deprecated since version 2.7.0
  8565. * @todo remove at version 3
  8566. * @private
  8567. */
  8568. helpers_core.clear = exports$1.clear;
  8569. /**
  8570. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  8571. * @namespace Chart.helpers.drawRoundedRectangle
  8572. * @deprecated since version 2.7.0
  8573. * @todo remove at version 3
  8574. * @private
  8575. */
  8576. helpers_core.drawRoundedRectangle = function(ctx) {
  8577. ctx.beginPath();
  8578. exports$1.roundedRect.apply(exports$1, arguments);
  8579. };
  8580. var defaults = {
  8581. /**
  8582. * @private
  8583. */
  8584. _set: function(scope, values) {
  8585. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  8586. }
  8587. };
  8588. // TODO(v3): remove 'global' from namespace. all default are global and
  8589. // there's inconsistency around which options are under 'global'
  8590. defaults._set('global', {
  8591. defaultColor: 'rgba(0,0,0,0.1)',
  8592. defaultFontColor: '#666',
  8593. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  8594. defaultFontSize: 12,
  8595. defaultFontStyle: 'normal',
  8596. defaultLineHeight: 1.2,
  8597. showLines: true
  8598. });
  8599. var core_defaults = defaults;
  8600. var valueOrDefault = helpers_core.valueOrDefault;
  8601. /**
  8602. * Converts the given font object into a CSS font string.
  8603. * @param {object} font - A font object.
  8604. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  8605. * @private
  8606. */
  8607. function toFontString(font) {
  8608. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  8609. return null;
  8610. }
  8611. return (font.style ? font.style + ' ' : '')
  8612. + (font.weight ? font.weight + ' ' : '')
  8613. + font.size + 'px '
  8614. + font.family;
  8615. }
  8616. /**
  8617. * @alias Chart.helpers.options
  8618. * @namespace
  8619. */
  8620. var helpers_options = {
  8621. /**
  8622. * Converts the given line height `value` in pixels for a specific font `size`.
  8623. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  8624. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  8625. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  8626. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  8627. * @since 2.7.0
  8628. */
  8629. toLineHeight: function(value, size) {
  8630. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  8631. if (!matches || matches[1] === 'normal') {
  8632. return size * 1.2;
  8633. }
  8634. value = +matches[2];
  8635. switch (matches[3]) {
  8636. case 'px':
  8637. return value;
  8638. case '%':
  8639. value /= 100;
  8640. break;
  8641. }
  8642. return size * value;
  8643. },
  8644. /**
  8645. * Converts the given value into a padding object with pre-computed width/height.
  8646. * @param {number|object} value - If a number, set the value to all TRBL component,
  8647. * else, if and object, use defined properties and sets undefined ones to 0.
  8648. * @returns {object} The padding values (top, right, bottom, left, width, height)
  8649. * @since 2.7.0
  8650. */
  8651. toPadding: function(value) {
  8652. var t, r, b, l;
  8653. if (helpers_core.isObject(value)) {
  8654. t = +value.top || 0;
  8655. r = +value.right || 0;
  8656. b = +value.bottom || 0;
  8657. l = +value.left || 0;
  8658. } else {
  8659. t = r = b = l = +value || 0;
  8660. }
  8661. return {
  8662. top: t,
  8663. right: r,
  8664. bottom: b,
  8665. left: l,
  8666. height: t + b,
  8667. width: l + r
  8668. };
  8669. },
  8670. /**
  8671. * Parses font options and returns the font object.
  8672. * @param {object} options - A object that contains font options to be parsed.
  8673. * @return {object} The font object.
  8674. * @todo Support font.* options and renamed to toFont().
  8675. * @private
  8676. */
  8677. _parseFont: function(options) {
  8678. var globalDefaults = core_defaults.global;
  8679. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  8680. var font = {
  8681. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  8682. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  8683. size: size,
  8684. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  8685. weight: null,
  8686. string: ''
  8687. };
  8688. font.string = toFontString(font);
  8689. return font;
  8690. },
  8691. /**
  8692. * Evaluates the given `inputs` sequentially and returns the first defined value.
  8693. * @param {Array} inputs - An array of values, falling back to the last value.
  8694. * @param {object} [context] - If defined and the current value is a function, the value
  8695. * is called with `context` as first argument and the result becomes the new input.
  8696. * @param {number} [index] - If defined and the current value is an array, the value
  8697. * at `index` become the new input.
  8698. * @param {object} [info] - object to return information about resolution in
  8699. * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.
  8700. * @since 2.7.0
  8701. */
  8702. resolve: function(inputs, context, index, info) {
  8703. var cacheable = true;
  8704. var i, ilen, value;
  8705. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  8706. value = inputs[i];
  8707. if (value === undefined) {
  8708. continue;
  8709. }
  8710. if (context !== undefined && typeof value === 'function') {
  8711. value = value(context);
  8712. cacheable = false;
  8713. }
  8714. if (index !== undefined && helpers_core.isArray(value)) {
  8715. value = value[index];
  8716. cacheable = false;
  8717. }
  8718. if (value !== undefined) {
  8719. if (info && !cacheable) {
  8720. info.cacheable = false;
  8721. }
  8722. return value;
  8723. }
  8724. }
  8725. }
  8726. };
  8727. /**
  8728. * @alias Chart.helpers.math
  8729. * @namespace
  8730. */
  8731. var exports$2 = {
  8732. /**
  8733. * Returns an array of factors sorted from 1 to sqrt(value)
  8734. * @private
  8735. */
  8736. _factorize: function(value) {
  8737. var result = [];
  8738. var sqrt = Math.sqrt(value);
  8739. var i;
  8740. for (i = 1; i < sqrt; i++) {
  8741. if (value % i === 0) {
  8742. result.push(i);
  8743. result.push(value / i);
  8744. }
  8745. }
  8746. if (sqrt === (sqrt | 0)) { // if value is a square number
  8747. result.push(sqrt);
  8748. }
  8749. result.sort(function(a, b) {
  8750. return a - b;
  8751. }).pop();
  8752. return result;
  8753. },
  8754. log10: Math.log10 || function(x) {
  8755. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  8756. // Check for whole powers of 10,
  8757. // which due to floating point rounding error should be corrected.
  8758. var powerOf10 = Math.round(exponent);
  8759. var isPowerOf10 = x === Math.pow(10, powerOf10);
  8760. return isPowerOf10 ? powerOf10 : exponent;
  8761. }
  8762. };
  8763. var helpers_math = exports$2;
  8764. // DEPRECATIONS
  8765. /**
  8766. * Provided for backward compatibility, use Chart.helpers.math.log10 instead.
  8767. * @namespace Chart.helpers.log10
  8768. * @deprecated since version 2.9.0
  8769. * @todo remove at version 3
  8770. * @private
  8771. */
  8772. helpers_core.log10 = exports$2.log10;
  8773. var getRtlAdapter = function(rectX, width) {
  8774. return {
  8775. x: function(x) {
  8776. return rectX + rectX + width - x;
  8777. },
  8778. setWidth: function(w) {
  8779. width = w;
  8780. },
  8781. textAlign: function(align) {
  8782. if (align === 'center') {
  8783. return align;
  8784. }
  8785. return align === 'right' ? 'left' : 'right';
  8786. },
  8787. xPlus: function(x, value) {
  8788. return x - value;
  8789. },
  8790. leftForLtr: function(x, itemWidth) {
  8791. return x - itemWidth;
  8792. },
  8793. };
  8794. };
  8795. var getLtrAdapter = function() {
  8796. return {
  8797. x: function(x) {
  8798. return x;
  8799. },
  8800. setWidth: function(w) { // eslint-disable-line no-unused-vars
  8801. },
  8802. textAlign: function(align) {
  8803. return align;
  8804. },
  8805. xPlus: function(x, value) {
  8806. return x + value;
  8807. },
  8808. leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars
  8809. return x;
  8810. },
  8811. };
  8812. };
  8813. var getAdapter = function(rtl, rectX, width) {
  8814. return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();
  8815. };
  8816. var overrideTextDirection = function(ctx, direction) {
  8817. var style, original;
  8818. if (direction === 'ltr' || direction === 'rtl') {
  8819. style = ctx.canvas.style;
  8820. original = [
  8821. style.getPropertyValue('direction'),
  8822. style.getPropertyPriority('direction'),
  8823. ];
  8824. style.setProperty('direction', direction, 'important');
  8825. ctx.prevTextDirection = original;
  8826. }
  8827. };
  8828. var restoreTextDirection = function(ctx) {
  8829. var original = ctx.prevTextDirection;
  8830. if (original !== undefined) {
  8831. delete ctx.prevTextDirection;
  8832. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  8833. }
  8834. };
  8835. var helpers_rtl = {
  8836. getRtlAdapter: getAdapter,
  8837. overrideTextDirection: overrideTextDirection,
  8838. restoreTextDirection: restoreTextDirection,
  8839. };
  8840. var helpers$1 = helpers_core;
  8841. var easing = helpers_easing;
  8842. var canvas = helpers_canvas;
  8843. var options = helpers_options;
  8844. var math = helpers_math;
  8845. var rtl = helpers_rtl;
  8846. helpers$1.easing = easing;
  8847. helpers$1.canvas = canvas;
  8848. helpers$1.options = options;
  8849. helpers$1.math = math;
  8850. helpers$1.rtl = rtl;
  8851. function interpolate(start, view, model, ease) {
  8852. var keys = Object.keys(model);
  8853. var i, ilen, key, actual, origin, target, type, c0, c1;
  8854. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  8855. key = keys[i];
  8856. target = model[key];
  8857. // if a value is added to the model after pivot() has been called, the view
  8858. // doesn't contain it, so let's initialize the view to the target value.
  8859. if (!view.hasOwnProperty(key)) {
  8860. view[key] = target;
  8861. }
  8862. actual = view[key];
  8863. if (actual === target || key[0] === '_') {
  8864. continue;
  8865. }
  8866. if (!start.hasOwnProperty(key)) {
  8867. start[key] = actual;
  8868. }
  8869. origin = start[key];
  8870. type = typeof target;
  8871. if (type === typeof origin) {
  8872. if (type === 'string') {
  8873. c0 = chartjsColor(origin);
  8874. if (c0.valid) {
  8875. c1 = chartjsColor(target);
  8876. if (c1.valid) {
  8877. view[key] = c1.mix(c0, ease).rgbString();
  8878. continue;
  8879. }
  8880. }
  8881. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  8882. view[key] = origin + (target - origin) * ease;
  8883. continue;
  8884. }
  8885. }
  8886. view[key] = target;
  8887. }
  8888. }
  8889. var Element = function(configuration) {
  8890. helpers$1.extend(this, configuration);
  8891. this.initialize.apply(this, arguments);
  8892. };
  8893. helpers$1.extend(Element.prototype, {
  8894. _type: undefined,
  8895. initialize: function() {
  8896. this.hidden = false;
  8897. },
  8898. pivot: function() {
  8899. var me = this;
  8900. if (!me._view) {
  8901. me._view = helpers$1.extend({}, me._model);
  8902. }
  8903. me._start = {};
  8904. return me;
  8905. },
  8906. transition: function(ease) {
  8907. var me = this;
  8908. var model = me._model;
  8909. var start = me._start;
  8910. var view = me._view;
  8911. // No animation -> No Transition
  8912. if (!model || ease === 1) {
  8913. me._view = helpers$1.extend({}, model);
  8914. me._start = null;
  8915. return me;
  8916. }
  8917. if (!view) {
  8918. view = me._view = {};
  8919. }
  8920. if (!start) {
  8921. start = me._start = {};
  8922. }
  8923. interpolate(start, view, model, ease);
  8924. return me;
  8925. },
  8926. tooltipPosition: function() {
  8927. return {
  8928. x: this._model.x,
  8929. y: this._model.y
  8930. };
  8931. },
  8932. hasValue: function() {
  8933. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  8934. }
  8935. });
  8936. Element.extend = helpers$1.inherits;
  8937. var core_element = Element;
  8938. var exports$3 = core_element.extend({
  8939. chart: null, // the animation associated chart instance
  8940. currentStep: 0, // the current animation step
  8941. numSteps: 60, // default number of steps
  8942. easing: '', // the easing to use for this animation
  8943. render: null, // render function used by the animation service
  8944. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  8945. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  8946. });
  8947. var core_animation = exports$3;
  8948. // DEPRECATIONS
  8949. /**
  8950. * Provided for backward compatibility, use Chart.Animation instead
  8951. * @prop Chart.Animation#animationObject
  8952. * @deprecated since version 2.6.0
  8953. * @todo remove at version 3
  8954. */
  8955. Object.defineProperty(exports$3.prototype, 'animationObject', {
  8956. get: function() {
  8957. return this;
  8958. }
  8959. });
  8960. /**
  8961. * Provided for backward compatibility, use Chart.Animation#chart instead
  8962. * @prop Chart.Animation#chartInstance
  8963. * @deprecated since version 2.6.0
  8964. * @todo remove at version 3
  8965. */
  8966. Object.defineProperty(exports$3.prototype, 'chartInstance', {
  8967. get: function() {
  8968. return this.chart;
  8969. },
  8970. set: function(value) {
  8971. this.chart = value;
  8972. }
  8973. });
  8974. core_defaults._set('global', {
  8975. animation: {
  8976. duration: 1000,
  8977. easing: 'easeOutQuart',
  8978. onProgress: helpers$1.noop,
  8979. onComplete: helpers$1.noop
  8980. }
  8981. });
  8982. var core_animations = {
  8983. animations: [],
  8984. request: null,
  8985. /**
  8986. * @param {Chart} chart - The chart to animate.
  8987. * @param {Chart.Animation} animation - The animation that we will animate.
  8988. * @param {number} duration - The animation duration in ms.
  8989. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  8990. */
  8991. addAnimation: function(chart, animation, duration, lazy) {
  8992. var animations = this.animations;
  8993. var i, ilen;
  8994. animation.chart = chart;
  8995. animation.startTime = Date.now();
  8996. animation.duration = duration;
  8997. if (!lazy) {
  8998. chart.animating = true;
  8999. }
  9000. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  9001. if (animations[i].chart === chart) {
  9002. animations[i] = animation;
  9003. return;
  9004. }
  9005. }
  9006. animations.push(animation);
  9007. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  9008. if (animations.length === 1) {
  9009. this.requestAnimationFrame();
  9010. }
  9011. },
  9012. cancelAnimation: function(chart) {
  9013. var index = helpers$1.findIndex(this.animations, function(animation) {
  9014. return animation.chart === chart;
  9015. });
  9016. if (index !== -1) {
  9017. this.animations.splice(index, 1);
  9018. chart.animating = false;
  9019. }
  9020. },
  9021. requestAnimationFrame: function() {
  9022. var me = this;
  9023. if (me.request === null) {
  9024. // Skip animation frame requests until the active one is executed.
  9025. // This can happen when processing mouse events, e.g. 'mousemove'
  9026. // and 'mouseout' events will trigger multiple renders.
  9027. me.request = helpers$1.requestAnimFrame.call(window, function() {
  9028. me.request = null;
  9029. me.startDigest();
  9030. });
  9031. }
  9032. },
  9033. /**
  9034. * @private
  9035. */
  9036. startDigest: function() {
  9037. var me = this;
  9038. me.advance();
  9039. // Do we have more stuff to animate?
  9040. if (me.animations.length > 0) {
  9041. me.requestAnimationFrame();
  9042. }
  9043. },
  9044. /**
  9045. * @private
  9046. */
  9047. advance: function() {
  9048. var animations = this.animations;
  9049. var animation, chart, numSteps, nextStep;
  9050. var i = 0;
  9051. // 1 animation per chart, so we are looping charts here
  9052. while (i < animations.length) {
  9053. animation = animations[i];
  9054. chart = animation.chart;
  9055. numSteps = animation.numSteps;
  9056. // Make sure that currentStep starts at 1
  9057. // https://github.com/chartjs/Chart.js/issues/6104
  9058. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  9059. animation.currentStep = Math.min(nextStep, numSteps);
  9060. helpers$1.callback(animation.render, [chart, animation], chart);
  9061. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  9062. if (animation.currentStep >= numSteps) {
  9063. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  9064. chart.animating = false;
  9065. animations.splice(i, 1);
  9066. } else {
  9067. ++i;
  9068. }
  9069. }
  9070. }
  9071. };
  9072. var resolve = helpers$1.options.resolve;
  9073. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  9074. /**
  9075. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  9076. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  9077. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  9078. */
  9079. function listenArrayEvents(array, listener) {
  9080. if (array._chartjs) {
  9081. array._chartjs.listeners.push(listener);
  9082. return;
  9083. }
  9084. Object.defineProperty(array, '_chartjs', {
  9085. configurable: true,
  9086. enumerable: false,
  9087. value: {
  9088. listeners: [listener]
  9089. }
  9090. });
  9091. arrayEvents.forEach(function(key) {
  9092. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  9093. var base = array[key];
  9094. Object.defineProperty(array, key, {
  9095. configurable: true,
  9096. enumerable: false,
  9097. value: function() {
  9098. var args = Array.prototype.slice.call(arguments);
  9099. var res = base.apply(this, args);
  9100. helpers$1.each(array._chartjs.listeners, function(object) {
  9101. if (typeof object[method] === 'function') {
  9102. object[method].apply(object, args);
  9103. }
  9104. });
  9105. return res;
  9106. }
  9107. });
  9108. });
  9109. }
  9110. /**
  9111. * Removes the given array event listener and cleanup extra attached properties (such as
  9112. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  9113. */
  9114. function unlistenArrayEvents(array, listener) {
  9115. var stub = array._chartjs;
  9116. if (!stub) {
  9117. return;
  9118. }
  9119. var listeners = stub.listeners;
  9120. var index = listeners.indexOf(listener);
  9121. if (index !== -1) {
  9122. listeners.splice(index, 1);
  9123. }
  9124. if (listeners.length > 0) {
  9125. return;
  9126. }
  9127. arrayEvents.forEach(function(key) {
  9128. delete array[key];
  9129. });
  9130. delete array._chartjs;
  9131. }
  9132. // Base class for all dataset controllers (line, bar, etc)
  9133. var DatasetController = function(chart, datasetIndex) {
  9134. this.initialize(chart, datasetIndex);
  9135. };
  9136. helpers$1.extend(DatasetController.prototype, {
  9137. /**
  9138. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  9139. * @type {Chart.core.element}
  9140. */
  9141. datasetElementType: null,
  9142. /**
  9143. * Element type used to generate a meta data (e.g. Chart.element.Point).
  9144. * @type {Chart.core.element}
  9145. */
  9146. dataElementType: null,
  9147. /**
  9148. * Dataset element option keys to be resolved in _resolveDatasetElementOptions.
  9149. * A derived controller may override this to resolve controller-specific options.
  9150. * The keys defined here are for backward compatibility for legend styles.
  9151. * @private
  9152. */
  9153. _datasetElementOptions: [
  9154. 'backgroundColor',
  9155. 'borderCapStyle',
  9156. 'borderColor',
  9157. 'borderDash',
  9158. 'borderDashOffset',
  9159. 'borderJoinStyle',
  9160. 'borderWidth'
  9161. ],
  9162. /**
  9163. * Data element option keys to be resolved in _resolveDataElementOptions.
  9164. * A derived controller may override this to resolve controller-specific options.
  9165. * The keys defined here are for backward compatibility for legend styles.
  9166. * @private
  9167. */
  9168. _dataElementOptions: [
  9169. 'backgroundColor',
  9170. 'borderColor',
  9171. 'borderWidth',
  9172. 'pointStyle'
  9173. ],
  9174. initialize: function(chart, datasetIndex) {
  9175. var me = this;
  9176. me.chart = chart;
  9177. me.index = datasetIndex;
  9178. me.linkScales();
  9179. me.addElements();
  9180. me._type = me.getMeta().type;
  9181. },
  9182. updateIndex: function(datasetIndex) {
  9183. this.index = datasetIndex;
  9184. },
  9185. linkScales: function() {
  9186. var me = this;
  9187. var meta = me.getMeta();
  9188. var chart = me.chart;
  9189. var scales = chart.scales;
  9190. var dataset = me.getDataset();
  9191. var scalesOpts = chart.options.scales;
  9192. if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
  9193. meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
  9194. }
  9195. if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
  9196. meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
  9197. }
  9198. },
  9199. getDataset: function() {
  9200. return this.chart.data.datasets[this.index];
  9201. },
  9202. getMeta: function() {
  9203. return this.chart.getDatasetMeta(this.index);
  9204. },
  9205. getScaleForId: function(scaleID) {
  9206. return this.chart.scales[scaleID];
  9207. },
  9208. /**
  9209. * @private
  9210. */
  9211. _getValueScaleId: function() {
  9212. return this.getMeta().yAxisID;
  9213. },
  9214. /**
  9215. * @private
  9216. */
  9217. _getIndexScaleId: function() {
  9218. return this.getMeta().xAxisID;
  9219. },
  9220. /**
  9221. * @private
  9222. */
  9223. _getValueScale: function() {
  9224. return this.getScaleForId(this._getValueScaleId());
  9225. },
  9226. /**
  9227. * @private
  9228. */
  9229. _getIndexScale: function() {
  9230. return this.getScaleForId(this._getIndexScaleId());
  9231. },
  9232. reset: function() {
  9233. this._update(true);
  9234. },
  9235. /**
  9236. * @private
  9237. */
  9238. destroy: function() {
  9239. if (this._data) {
  9240. unlistenArrayEvents(this._data, this);
  9241. }
  9242. },
  9243. createMetaDataset: function() {
  9244. var me = this;
  9245. var type = me.datasetElementType;
  9246. return type && new type({
  9247. _chart: me.chart,
  9248. _datasetIndex: me.index
  9249. });
  9250. },
  9251. createMetaData: function(index) {
  9252. var me = this;
  9253. var type = me.dataElementType;
  9254. return type && new type({
  9255. _chart: me.chart,
  9256. _datasetIndex: me.index,
  9257. _index: index
  9258. });
  9259. },
  9260. addElements: function() {
  9261. var me = this;
  9262. var meta = me.getMeta();
  9263. var data = me.getDataset().data || [];
  9264. var metaData = meta.data;
  9265. var i, ilen;
  9266. for (i = 0, ilen = data.length; i < ilen; ++i) {
  9267. metaData[i] = metaData[i] || me.createMetaData(i);
  9268. }
  9269. meta.dataset = meta.dataset || me.createMetaDataset();
  9270. },
  9271. addElementAndReset: function(index) {
  9272. var element = this.createMetaData(index);
  9273. this.getMeta().data.splice(index, 0, element);
  9274. this.updateElement(element, index, true);
  9275. },
  9276. buildOrUpdateElements: function() {
  9277. var me = this;
  9278. var dataset = me.getDataset();
  9279. var data = dataset.data || (dataset.data = []);
  9280. // In order to correctly handle data addition/deletion animation (an thus simulate
  9281. // real-time charts), we need to monitor these data modifications and synchronize
  9282. // the internal meta data accordingly.
  9283. if (me._data !== data) {
  9284. if (me._data) {
  9285. // This case happens when the user replaced the data array instance.
  9286. unlistenArrayEvents(me._data, me);
  9287. }
  9288. if (data && Object.isExtensible(data)) {
  9289. listenArrayEvents(data, me);
  9290. }
  9291. me._data = data;
  9292. }
  9293. // Re-sync meta data in case the user replaced the data array or if we missed
  9294. // any updates and so make sure that we handle number of datapoints changing.
  9295. me.resyncElements();
  9296. },
  9297. /**
  9298. * Returns the merged user-supplied and default dataset-level options
  9299. * @private
  9300. */
  9301. _configure: function() {
  9302. var me = this;
  9303. me._config = helpers$1.merge(Object.create(null), [
  9304. me.chart.options.datasets[me._type],
  9305. me.getDataset(),
  9306. ], {
  9307. merger: function(key, target, source) {
  9308. if (key !== '_meta' && key !== 'data') {
  9309. helpers$1._merger(key, target, source);
  9310. }
  9311. }
  9312. });
  9313. },
  9314. _update: function(reset) {
  9315. var me = this;
  9316. me._configure();
  9317. me._cachedDataOpts = null;
  9318. me.update(reset);
  9319. },
  9320. update: helpers$1.noop,
  9321. transition: function(easingValue) {
  9322. var meta = this.getMeta();
  9323. var elements = meta.data || [];
  9324. var ilen = elements.length;
  9325. var i = 0;
  9326. for (; i < ilen; ++i) {
  9327. elements[i].transition(easingValue);
  9328. }
  9329. if (meta.dataset) {
  9330. meta.dataset.transition(easingValue);
  9331. }
  9332. },
  9333. draw: function() {
  9334. var meta = this.getMeta();
  9335. var elements = meta.data || [];
  9336. var ilen = elements.length;
  9337. var i = 0;
  9338. if (meta.dataset) {
  9339. meta.dataset.draw();
  9340. }
  9341. for (; i < ilen; ++i) {
  9342. elements[i].draw();
  9343. }
  9344. },
  9345. /**
  9346. * Returns a set of predefined style properties that should be used to represent the dataset
  9347. * or the data if the index is specified
  9348. * @param {number} index - data index
  9349. * @return {IStyleInterface} style object
  9350. */
  9351. getStyle: function(index) {
  9352. var me = this;
  9353. var meta = me.getMeta();
  9354. var dataset = meta.dataset;
  9355. var style;
  9356. me._configure();
  9357. if (dataset && index === undefined) {
  9358. style = me._resolveDatasetElementOptions(dataset || {});
  9359. } else {
  9360. index = index || 0;
  9361. style = me._resolveDataElementOptions(meta.data[index] || {}, index);
  9362. }
  9363. if (style.fill === false || style.fill === null) {
  9364. style.backgroundColor = style.borderColor;
  9365. }
  9366. return style;
  9367. },
  9368. /**
  9369. * @private
  9370. */
  9371. _resolveDatasetElementOptions: function(element, hover) {
  9372. var me = this;
  9373. var chart = me.chart;
  9374. var datasetOpts = me._config;
  9375. var custom = element.custom || {};
  9376. var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
  9377. var elementOptions = me._datasetElementOptions;
  9378. var values = {};
  9379. var i, ilen, key, readKey;
  9380. // Scriptable options
  9381. var context = {
  9382. chart: chart,
  9383. dataset: me.getDataset(),
  9384. datasetIndex: me.index,
  9385. hover: hover
  9386. };
  9387. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  9388. key = elementOptions[i];
  9389. readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
  9390. values[key] = resolve([
  9391. custom[readKey],
  9392. datasetOpts[readKey],
  9393. options[readKey]
  9394. ], context);
  9395. }
  9396. return values;
  9397. },
  9398. /**
  9399. * @private
  9400. */
  9401. _resolveDataElementOptions: function(element, index) {
  9402. var me = this;
  9403. var custom = element && element.custom;
  9404. var cached = me._cachedDataOpts;
  9405. if (cached && !custom) {
  9406. return cached;
  9407. }
  9408. var chart = me.chart;
  9409. var datasetOpts = me._config;
  9410. var options = chart.options.elements[me.dataElementType.prototype._type] || {};
  9411. var elementOptions = me._dataElementOptions;
  9412. var values = {};
  9413. // Scriptable options
  9414. var context = {
  9415. chart: chart,
  9416. dataIndex: index,
  9417. dataset: me.getDataset(),
  9418. datasetIndex: me.index
  9419. };
  9420. // `resolve` sets cacheable to `false` if any option is indexed or scripted
  9421. var info = {cacheable: !custom};
  9422. var keys, i, ilen, key;
  9423. custom = custom || {};
  9424. if (helpers$1.isArray(elementOptions)) {
  9425. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  9426. key = elementOptions[i];
  9427. values[key] = resolve([
  9428. custom[key],
  9429. datasetOpts[key],
  9430. options[key]
  9431. ], context, index, info);
  9432. }
  9433. } else {
  9434. keys = Object.keys(elementOptions);
  9435. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  9436. key = keys[i];
  9437. values[key] = resolve([
  9438. custom[key],
  9439. datasetOpts[elementOptions[key]],
  9440. datasetOpts[key],
  9441. options[key]
  9442. ], context, index, info);
  9443. }
  9444. }
  9445. if (info.cacheable) {
  9446. me._cachedDataOpts = Object.freeze(values);
  9447. }
  9448. return values;
  9449. },
  9450. removeHoverStyle: function(element) {
  9451. helpers$1.merge(element._model, element.$previousStyle || {});
  9452. delete element.$previousStyle;
  9453. },
  9454. setHoverStyle: function(element) {
  9455. var dataset = this.chart.data.datasets[element._datasetIndex];
  9456. var index = element._index;
  9457. var custom = element.custom || {};
  9458. var model = element._model;
  9459. var getHoverColor = helpers$1.getHoverColor;
  9460. element.$previousStyle = {
  9461. backgroundColor: model.backgroundColor,
  9462. borderColor: model.borderColor,
  9463. borderWidth: model.borderWidth
  9464. };
  9465. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  9466. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  9467. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  9468. },
  9469. /**
  9470. * @private
  9471. */
  9472. _removeDatasetHoverStyle: function() {
  9473. var element = this.getMeta().dataset;
  9474. if (element) {
  9475. this.removeHoverStyle(element);
  9476. }
  9477. },
  9478. /**
  9479. * @private
  9480. */
  9481. _setDatasetHoverStyle: function() {
  9482. var element = this.getMeta().dataset;
  9483. var prev = {};
  9484. var i, ilen, key, keys, hoverOptions, model;
  9485. if (!element) {
  9486. return;
  9487. }
  9488. model = element._model;
  9489. hoverOptions = this._resolveDatasetElementOptions(element, true);
  9490. keys = Object.keys(hoverOptions);
  9491. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  9492. key = keys[i];
  9493. prev[key] = model[key];
  9494. model[key] = hoverOptions[key];
  9495. }
  9496. element.$previousStyle = prev;
  9497. },
  9498. /**
  9499. * @private
  9500. */
  9501. resyncElements: function() {
  9502. var me = this;
  9503. var meta = me.getMeta();
  9504. var data = me.getDataset().data;
  9505. var numMeta = meta.data.length;
  9506. var numData = data.length;
  9507. if (numData < numMeta) {
  9508. meta.data.splice(numData, numMeta - numData);
  9509. } else if (numData > numMeta) {
  9510. me.insertElements(numMeta, numData - numMeta);
  9511. }
  9512. },
  9513. /**
  9514. * @private
  9515. */
  9516. insertElements: function(start, count) {
  9517. for (var i = 0; i < count; ++i) {
  9518. this.addElementAndReset(start + i);
  9519. }
  9520. },
  9521. /**
  9522. * @private
  9523. */
  9524. onDataPush: function() {
  9525. var count = arguments.length;
  9526. this.insertElements(this.getDataset().data.length - count, count);
  9527. },
  9528. /**
  9529. * @private
  9530. */
  9531. onDataPop: function() {
  9532. this.getMeta().data.pop();
  9533. },
  9534. /**
  9535. * @private
  9536. */
  9537. onDataShift: function() {
  9538. this.getMeta().data.shift();
  9539. },
  9540. /**
  9541. * @private
  9542. */
  9543. onDataSplice: function(start, count) {
  9544. this.getMeta().data.splice(start, count);
  9545. this.insertElements(start, arguments.length - 2);
  9546. },
  9547. /**
  9548. * @private
  9549. */
  9550. onDataUnshift: function() {
  9551. this.insertElements(0, arguments.length);
  9552. }
  9553. });
  9554. DatasetController.extend = helpers$1.inherits;
  9555. var core_datasetController = DatasetController;
  9556. var TAU = Math.PI * 2;
  9557. core_defaults._set('global', {
  9558. elements: {
  9559. arc: {
  9560. backgroundColor: core_defaults.global.defaultColor,
  9561. borderColor: '#fff',
  9562. borderWidth: 2,
  9563. borderAlign: 'center'
  9564. }
  9565. }
  9566. });
  9567. function clipArc(ctx, arc) {
  9568. var startAngle = arc.startAngle;
  9569. var endAngle = arc.endAngle;
  9570. var pixelMargin = arc.pixelMargin;
  9571. var angleMargin = pixelMargin / arc.outerRadius;
  9572. var x = arc.x;
  9573. var y = arc.y;
  9574. // Draw an inner border by cliping the arc and drawing a double-width border
  9575. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  9576. ctx.beginPath();
  9577. ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  9578. if (arc.innerRadius > pixelMargin) {
  9579. angleMargin = pixelMargin / arc.innerRadius;
  9580. ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);
  9581. } else {
  9582. ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);
  9583. }
  9584. ctx.closePath();
  9585. ctx.clip();
  9586. }
  9587. function drawFullCircleBorders(ctx, vm, arc, inner) {
  9588. var endAngle = arc.endAngle;
  9589. var i;
  9590. if (inner) {
  9591. arc.endAngle = arc.startAngle + TAU;
  9592. clipArc(ctx, arc);
  9593. arc.endAngle = endAngle;
  9594. if (arc.endAngle === arc.startAngle && arc.fullCircles) {
  9595. arc.endAngle += TAU;
  9596. arc.fullCircles--;
  9597. }
  9598. }
  9599. ctx.beginPath();
  9600. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);
  9601. for (i = 0; i < arc.fullCircles; ++i) {
  9602. ctx.stroke();
  9603. }
  9604. ctx.beginPath();
  9605. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);
  9606. for (i = 0; i < arc.fullCircles; ++i) {
  9607. ctx.stroke();
  9608. }
  9609. }
  9610. function drawBorder(ctx, vm, arc) {
  9611. var inner = vm.borderAlign === 'inner';
  9612. if (inner) {
  9613. ctx.lineWidth = vm.borderWidth * 2;
  9614. ctx.lineJoin = 'round';
  9615. } else {
  9616. ctx.lineWidth = vm.borderWidth;
  9617. ctx.lineJoin = 'bevel';
  9618. }
  9619. if (arc.fullCircles) {
  9620. drawFullCircleBorders(ctx, vm, arc, inner);
  9621. }
  9622. if (inner) {
  9623. clipArc(ctx, arc);
  9624. }
  9625. ctx.beginPath();
  9626. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);
  9627. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  9628. ctx.closePath();
  9629. ctx.stroke();
  9630. }
  9631. var element_arc = core_element.extend({
  9632. _type: 'arc',
  9633. inLabelRange: function(mouseX) {
  9634. var vm = this._view;
  9635. if (vm) {
  9636. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  9637. }
  9638. return false;
  9639. },
  9640. inRange: function(chartX, chartY) {
  9641. var vm = this._view;
  9642. if (vm) {
  9643. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  9644. var angle = pointRelativePosition.angle;
  9645. var distance = pointRelativePosition.distance;
  9646. // Sanitise angle range
  9647. var startAngle = vm.startAngle;
  9648. var endAngle = vm.endAngle;
  9649. while (endAngle < startAngle) {
  9650. endAngle += TAU;
  9651. }
  9652. while (angle > endAngle) {
  9653. angle -= TAU;
  9654. }
  9655. while (angle < startAngle) {
  9656. angle += TAU;
  9657. }
  9658. // Check if within the range of the open/close angle
  9659. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  9660. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  9661. return (betweenAngles && withinRadius);
  9662. }
  9663. return false;
  9664. },
  9665. getCenterPoint: function() {
  9666. var vm = this._view;
  9667. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  9668. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  9669. return {
  9670. x: vm.x + Math.cos(halfAngle) * halfRadius,
  9671. y: vm.y + Math.sin(halfAngle) * halfRadius
  9672. };
  9673. },
  9674. getArea: function() {
  9675. var vm = this._view;
  9676. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  9677. },
  9678. tooltipPosition: function() {
  9679. var vm = this._view;
  9680. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  9681. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  9682. return {
  9683. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  9684. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  9685. };
  9686. },
  9687. draw: function() {
  9688. var ctx = this._chart.ctx;
  9689. var vm = this._view;
  9690. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  9691. var arc = {
  9692. x: vm.x,
  9693. y: vm.y,
  9694. innerRadius: vm.innerRadius,
  9695. outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),
  9696. pixelMargin: pixelMargin,
  9697. startAngle: vm.startAngle,
  9698. endAngle: vm.endAngle,
  9699. fullCircles: Math.floor(vm.circumference / TAU)
  9700. };
  9701. var i;
  9702. ctx.save();
  9703. ctx.fillStyle = vm.backgroundColor;
  9704. ctx.strokeStyle = vm.borderColor;
  9705. if (arc.fullCircles) {
  9706. arc.endAngle = arc.startAngle + TAU;
  9707. ctx.beginPath();
  9708. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  9709. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  9710. ctx.closePath();
  9711. for (i = 0; i < arc.fullCircles; ++i) {
  9712. ctx.fill();
  9713. }
  9714. arc.endAngle = arc.startAngle + vm.circumference % TAU;
  9715. }
  9716. ctx.beginPath();
  9717. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  9718. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  9719. ctx.closePath();
  9720. ctx.fill();
  9721. if (vm.borderWidth) {
  9722. drawBorder(ctx, vm, arc);
  9723. }
  9724. ctx.restore();
  9725. }
  9726. });
  9727. var valueOrDefault$1 = helpers$1.valueOrDefault;
  9728. var defaultColor = core_defaults.global.defaultColor;
  9729. core_defaults._set('global', {
  9730. elements: {
  9731. line: {
  9732. tension: 0.4,
  9733. backgroundColor: defaultColor,
  9734. borderWidth: 3,
  9735. borderColor: defaultColor,
  9736. borderCapStyle: 'butt',
  9737. borderDash: [],
  9738. borderDashOffset: 0.0,
  9739. borderJoinStyle: 'miter',
  9740. capBezierPoints: true,
  9741. fill: true, // do we fill in the area between the line and its base axis
  9742. }
  9743. }
  9744. });
  9745. var element_line = core_element.extend({
  9746. _type: 'line',
  9747. draw: function() {
  9748. var me = this;
  9749. var vm = me._view;
  9750. var ctx = me._chart.ctx;
  9751. var spanGaps = vm.spanGaps;
  9752. var points = me._children.slice(); // clone array
  9753. var globalDefaults = core_defaults.global;
  9754. var globalOptionLineElements = globalDefaults.elements.line;
  9755. var lastDrawnIndex = -1;
  9756. var closePath = me._loop;
  9757. var index, previous, currentVM;
  9758. if (!points.length) {
  9759. return;
  9760. }
  9761. if (me._loop) {
  9762. for (index = 0; index < points.length; ++index) {
  9763. previous = helpers$1.previousItem(points, index);
  9764. // If the line has an open path, shift the point array
  9765. if (!points[index]._view.skip && previous._view.skip) {
  9766. points = points.slice(index).concat(points.slice(0, index));
  9767. closePath = spanGaps;
  9768. break;
  9769. }
  9770. }
  9771. // If the line has a close path, add the first point again
  9772. if (closePath) {
  9773. points.push(points[0]);
  9774. }
  9775. }
  9776. ctx.save();
  9777. // Stroke Line Options
  9778. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  9779. // IE 9 and 10 do not support line dash
  9780. if (ctx.setLineDash) {
  9781. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  9782. }
  9783. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  9784. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  9785. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  9786. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  9787. // Stroke Line
  9788. ctx.beginPath();
  9789. // First point moves to it's starting position no matter what
  9790. currentVM = points[0]._view;
  9791. if (!currentVM.skip) {
  9792. ctx.moveTo(currentVM.x, currentVM.y);
  9793. lastDrawnIndex = 0;
  9794. }
  9795. for (index = 1; index < points.length; ++index) {
  9796. currentVM = points[index]._view;
  9797. previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];
  9798. if (!currentVM.skip) {
  9799. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  9800. // There was a gap and this is the first point after the gap
  9801. ctx.moveTo(currentVM.x, currentVM.y);
  9802. } else {
  9803. // Line to next point
  9804. helpers$1.canvas.lineTo(ctx, previous._view, currentVM);
  9805. }
  9806. lastDrawnIndex = index;
  9807. }
  9808. }
  9809. if (closePath) {
  9810. ctx.closePath();
  9811. }
  9812. ctx.stroke();
  9813. ctx.restore();
  9814. }
  9815. });
  9816. var valueOrDefault$2 = helpers$1.valueOrDefault;
  9817. var defaultColor$1 = core_defaults.global.defaultColor;
  9818. core_defaults._set('global', {
  9819. elements: {
  9820. point: {
  9821. radius: 3,
  9822. pointStyle: 'circle',
  9823. backgroundColor: defaultColor$1,
  9824. borderColor: defaultColor$1,
  9825. borderWidth: 1,
  9826. // Hover
  9827. hitRadius: 1,
  9828. hoverRadius: 4,
  9829. hoverBorderWidth: 1
  9830. }
  9831. }
  9832. });
  9833. function xRange(mouseX) {
  9834. var vm = this._view;
  9835. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  9836. }
  9837. function yRange(mouseY) {
  9838. var vm = this._view;
  9839. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  9840. }
  9841. var element_point = core_element.extend({
  9842. _type: 'point',
  9843. inRange: function(mouseX, mouseY) {
  9844. var vm = this._view;
  9845. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  9846. },
  9847. inLabelRange: xRange,
  9848. inXRange: xRange,
  9849. inYRange: yRange,
  9850. getCenterPoint: function() {
  9851. var vm = this._view;
  9852. return {
  9853. x: vm.x,
  9854. y: vm.y
  9855. };
  9856. },
  9857. getArea: function() {
  9858. return Math.PI * Math.pow(this._view.radius, 2);
  9859. },
  9860. tooltipPosition: function() {
  9861. var vm = this._view;
  9862. return {
  9863. x: vm.x,
  9864. y: vm.y,
  9865. padding: vm.radius + vm.borderWidth
  9866. };
  9867. },
  9868. draw: function(chartArea) {
  9869. var vm = this._view;
  9870. var ctx = this._chart.ctx;
  9871. var pointStyle = vm.pointStyle;
  9872. var rotation = vm.rotation;
  9873. var radius = vm.radius;
  9874. var x = vm.x;
  9875. var y = vm.y;
  9876. var globalDefaults = core_defaults.global;
  9877. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  9878. if (vm.skip) {
  9879. return;
  9880. }
  9881. // Clipping for Points.
  9882. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  9883. ctx.strokeStyle = vm.borderColor || defaultColor;
  9884. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  9885. ctx.fillStyle = vm.backgroundColor || defaultColor;
  9886. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  9887. }
  9888. }
  9889. });
  9890. var defaultColor$2 = core_defaults.global.defaultColor;
  9891. core_defaults._set('global', {
  9892. elements: {
  9893. rectangle: {
  9894. backgroundColor: defaultColor$2,
  9895. borderColor: defaultColor$2,
  9896. borderSkipped: 'bottom',
  9897. borderWidth: 0
  9898. }
  9899. }
  9900. });
  9901. function isVertical(vm) {
  9902. return vm && vm.width !== undefined;
  9903. }
  9904. /**
  9905. * Helper function to get the bounds of the bar regardless of the orientation
  9906. * @param bar {Chart.Element.Rectangle} the bar
  9907. * @return {Bounds} bounds of the bar
  9908. * @private
  9909. */
  9910. function getBarBounds(vm) {
  9911. var x1, x2, y1, y2, half;
  9912. if (isVertical(vm)) {
  9913. half = vm.width / 2;
  9914. x1 = vm.x - half;
  9915. x2 = vm.x + half;
  9916. y1 = Math.min(vm.y, vm.base);
  9917. y2 = Math.max(vm.y, vm.base);
  9918. } else {
  9919. half = vm.height / 2;
  9920. x1 = Math.min(vm.x, vm.base);
  9921. x2 = Math.max(vm.x, vm.base);
  9922. y1 = vm.y - half;
  9923. y2 = vm.y + half;
  9924. }
  9925. return {
  9926. left: x1,
  9927. top: y1,
  9928. right: x2,
  9929. bottom: y2
  9930. };
  9931. }
  9932. function swap(orig, v1, v2) {
  9933. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  9934. }
  9935. function parseBorderSkipped(vm) {
  9936. var edge = vm.borderSkipped;
  9937. var res = {};
  9938. if (!edge) {
  9939. return res;
  9940. }
  9941. if (vm.horizontal) {
  9942. if (vm.base > vm.x) {
  9943. edge = swap(edge, 'left', 'right');
  9944. }
  9945. } else if (vm.base < vm.y) {
  9946. edge = swap(edge, 'bottom', 'top');
  9947. }
  9948. res[edge] = true;
  9949. return res;
  9950. }
  9951. function parseBorderWidth(vm, maxW, maxH) {
  9952. var value = vm.borderWidth;
  9953. var skip = parseBorderSkipped(vm);
  9954. var t, r, b, l;
  9955. if (helpers$1.isObject(value)) {
  9956. t = +value.top || 0;
  9957. r = +value.right || 0;
  9958. b = +value.bottom || 0;
  9959. l = +value.left || 0;
  9960. } else {
  9961. t = r = b = l = +value || 0;
  9962. }
  9963. return {
  9964. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  9965. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  9966. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  9967. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  9968. };
  9969. }
  9970. function boundingRects(vm) {
  9971. var bounds = getBarBounds(vm);
  9972. var width = bounds.right - bounds.left;
  9973. var height = bounds.bottom - bounds.top;
  9974. var border = parseBorderWidth(vm, width / 2, height / 2);
  9975. return {
  9976. outer: {
  9977. x: bounds.left,
  9978. y: bounds.top,
  9979. w: width,
  9980. h: height
  9981. },
  9982. inner: {
  9983. x: bounds.left + border.l,
  9984. y: bounds.top + border.t,
  9985. w: width - border.l - border.r,
  9986. h: height - border.t - border.b
  9987. }
  9988. };
  9989. }
  9990. function inRange(vm, x, y) {
  9991. var skipX = x === null;
  9992. var skipY = y === null;
  9993. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  9994. return bounds
  9995. && (skipX || x >= bounds.left && x <= bounds.right)
  9996. && (skipY || y >= bounds.top && y <= bounds.bottom);
  9997. }
  9998. var element_rectangle = core_element.extend({
  9999. _type: 'rectangle',
  10000. draw: function() {
  10001. var ctx = this._chart.ctx;
  10002. var vm = this._view;
  10003. var rects = boundingRects(vm);
  10004. var outer = rects.outer;
  10005. var inner = rects.inner;
  10006. ctx.fillStyle = vm.backgroundColor;
  10007. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  10008. if (outer.w === inner.w && outer.h === inner.h) {
  10009. return;
  10010. }
  10011. ctx.save();
  10012. ctx.beginPath();
  10013. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  10014. ctx.clip();
  10015. ctx.fillStyle = vm.borderColor;
  10016. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  10017. ctx.fill('evenodd');
  10018. ctx.restore();
  10019. },
  10020. height: function() {
  10021. var vm = this._view;
  10022. return vm.base - vm.y;
  10023. },
  10024. inRange: function(mouseX, mouseY) {
  10025. return inRange(this._view, mouseX, mouseY);
  10026. },
  10027. inLabelRange: function(mouseX, mouseY) {
  10028. var vm = this._view;
  10029. return isVertical(vm)
  10030. ? inRange(vm, mouseX, null)
  10031. : inRange(vm, null, mouseY);
  10032. },
  10033. inXRange: function(mouseX) {
  10034. return inRange(this._view, mouseX, null);
  10035. },
  10036. inYRange: function(mouseY) {
  10037. return inRange(this._view, null, mouseY);
  10038. },
  10039. getCenterPoint: function() {
  10040. var vm = this._view;
  10041. var x, y;
  10042. if (isVertical(vm)) {
  10043. x = vm.x;
  10044. y = (vm.y + vm.base) / 2;
  10045. } else {
  10046. x = (vm.x + vm.base) / 2;
  10047. y = vm.y;
  10048. }
  10049. return {x: x, y: y};
  10050. },
  10051. getArea: function() {
  10052. var vm = this._view;
  10053. return isVertical(vm)
  10054. ? vm.width * Math.abs(vm.y - vm.base)
  10055. : vm.height * Math.abs(vm.x - vm.base);
  10056. },
  10057. tooltipPosition: function() {
  10058. var vm = this._view;
  10059. return {
  10060. x: vm.x,
  10061. y: vm.y
  10062. };
  10063. }
  10064. });
  10065. var elements = {};
  10066. var Arc = element_arc;
  10067. var Line = element_line;
  10068. var Point = element_point;
  10069. var Rectangle = element_rectangle;
  10070. elements.Arc = Arc;
  10071. elements.Line = Line;
  10072. elements.Point = Point;
  10073. elements.Rectangle = Rectangle;
  10074. var deprecated = helpers$1._deprecated;
  10075. var valueOrDefault$3 = helpers$1.valueOrDefault;
  10076. core_defaults._set('bar', {
  10077. hover: {
  10078. mode: 'label'
  10079. },
  10080. scales: {
  10081. xAxes: [{
  10082. type: 'category',
  10083. offset: true,
  10084. gridLines: {
  10085. offsetGridLines: true
  10086. }
  10087. }],
  10088. yAxes: [{
  10089. type: 'linear'
  10090. }]
  10091. }
  10092. });
  10093. core_defaults._set('global', {
  10094. datasets: {
  10095. bar: {
  10096. categoryPercentage: 0.8,
  10097. barPercentage: 0.9
  10098. }
  10099. }
  10100. });
  10101. /**
  10102. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  10103. * @private
  10104. */
  10105. function computeMinSampleSize(scale, pixels) {
  10106. var min = scale._length;
  10107. var prev, curr, i, ilen;
  10108. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  10109. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  10110. }
  10111. for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
  10112. curr = scale.getPixelForTick(i);
  10113. min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
  10114. prev = curr;
  10115. }
  10116. return min;
  10117. }
  10118. /**
  10119. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  10120. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  10121. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  10122. * @private
  10123. */
  10124. function computeFitCategoryTraits(index, ruler, options) {
  10125. var thickness = options.barThickness;
  10126. var count = ruler.stackCount;
  10127. var curr = ruler.pixels[index];
  10128. var min = helpers$1.isNullOrUndef(thickness)
  10129. ? computeMinSampleSize(ruler.scale, ruler.pixels)
  10130. : -1;
  10131. var size, ratio;
  10132. if (helpers$1.isNullOrUndef(thickness)) {
  10133. size = min * options.categoryPercentage;
  10134. ratio = options.barPercentage;
  10135. } else {
  10136. // When bar thickness is enforced, category and bar percentages are ignored.
  10137. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  10138. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  10139. size = thickness * count;
  10140. ratio = 1;
  10141. }
  10142. return {
  10143. chunk: size / count,
  10144. ratio: ratio,
  10145. start: curr - (size / 2)
  10146. };
  10147. }
  10148. /**
  10149. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  10150. * percentage options are 1), based on the previous and following categories. This mode
  10151. * generates bars with different widths when data are not evenly spaced.
  10152. * @private
  10153. */
  10154. function computeFlexCategoryTraits(index, ruler, options) {
  10155. var pixels = ruler.pixels;
  10156. var curr = pixels[index];
  10157. var prev = index > 0 ? pixels[index - 1] : null;
  10158. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  10159. var percent = options.categoryPercentage;
  10160. var start, size;
  10161. if (prev === null) {
  10162. // first data: its size is double based on the next point or,
  10163. // if it's also the last data, we use the scale size.
  10164. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  10165. }
  10166. if (next === null) {
  10167. // last data: its size is also double based on the previous point.
  10168. next = curr + curr - prev;
  10169. }
  10170. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  10171. size = Math.abs(next - prev) / 2 * percent;
  10172. return {
  10173. chunk: size / ruler.stackCount,
  10174. ratio: options.barPercentage,
  10175. start: start
  10176. };
  10177. }
  10178. var controller_bar = core_datasetController.extend({
  10179. dataElementType: elements.Rectangle,
  10180. /**
  10181. * @private
  10182. */
  10183. _dataElementOptions: [
  10184. 'backgroundColor',
  10185. 'borderColor',
  10186. 'borderSkipped',
  10187. 'borderWidth',
  10188. 'barPercentage',
  10189. 'barThickness',
  10190. 'categoryPercentage',
  10191. 'maxBarThickness',
  10192. 'minBarLength'
  10193. ],
  10194. initialize: function() {
  10195. var me = this;
  10196. var meta, scaleOpts;
  10197. core_datasetController.prototype.initialize.apply(me, arguments);
  10198. meta = me.getMeta();
  10199. meta.stack = me.getDataset().stack;
  10200. meta.bar = true;
  10201. scaleOpts = me._getIndexScale().options;
  10202. deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
  10203. deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
  10204. deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
  10205. deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
  10206. deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
  10207. },
  10208. update: function(reset) {
  10209. var me = this;
  10210. var rects = me.getMeta().data;
  10211. var i, ilen;
  10212. me._ruler = me.getRuler();
  10213. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  10214. me.updateElement(rects[i], i, reset);
  10215. }
  10216. },
  10217. updateElement: function(rectangle, index, reset) {
  10218. var me = this;
  10219. var meta = me.getMeta();
  10220. var dataset = me.getDataset();
  10221. var options = me._resolveDataElementOptions(rectangle, index);
  10222. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  10223. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  10224. rectangle._datasetIndex = me.index;
  10225. rectangle._index = index;
  10226. rectangle._model = {
  10227. backgroundColor: options.backgroundColor,
  10228. borderColor: options.borderColor,
  10229. borderSkipped: options.borderSkipped,
  10230. borderWidth: options.borderWidth,
  10231. datasetLabel: dataset.label,
  10232. label: me.chart.data.labels[index]
  10233. };
  10234. if (helpers$1.isArray(dataset.data[index])) {
  10235. rectangle._model.borderSkipped = null;
  10236. }
  10237. me._updateElementGeometry(rectangle, index, reset, options);
  10238. rectangle.pivot();
  10239. },
  10240. /**
  10241. * @private
  10242. */
  10243. _updateElementGeometry: function(rectangle, index, reset, options) {
  10244. var me = this;
  10245. var model = rectangle._model;
  10246. var vscale = me._getValueScale();
  10247. var base = vscale.getBasePixel();
  10248. var horizontal = vscale.isHorizontal();
  10249. var ruler = me._ruler || me.getRuler();
  10250. var vpixels = me.calculateBarValuePixels(me.index, index, options);
  10251. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
  10252. model.horizontal = horizontal;
  10253. model.base = reset ? base : vpixels.base;
  10254. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  10255. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  10256. model.height = horizontal ? ipixels.size : undefined;
  10257. model.width = horizontal ? undefined : ipixels.size;
  10258. },
  10259. /**
  10260. * Returns the stacks based on groups and bar visibility.
  10261. * @param {number} [last] - The dataset index
  10262. * @returns {string[]} The list of stack IDs
  10263. * @private
  10264. */
  10265. _getStacks: function(last) {
  10266. var me = this;
  10267. var scale = me._getIndexScale();
  10268. var metasets = scale._getMatchingVisibleMetas(me._type);
  10269. var stacked = scale.options.stacked;
  10270. var ilen = metasets.length;
  10271. var stacks = [];
  10272. var i, meta;
  10273. for (i = 0; i < ilen; ++i) {
  10274. meta = metasets[i];
  10275. // stacked | meta.stack
  10276. // | found | not found | undefined
  10277. // false | x | x | x
  10278. // true | | x |
  10279. // undefined | | x | x
  10280. if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
  10281. (stacked === undefined && meta.stack === undefined)) {
  10282. stacks.push(meta.stack);
  10283. }
  10284. if (meta.index === last) {
  10285. break;
  10286. }
  10287. }
  10288. return stacks;
  10289. },
  10290. /**
  10291. * Returns the effective number of stacks based on groups and bar visibility.
  10292. * @private
  10293. */
  10294. getStackCount: function() {
  10295. return this._getStacks().length;
  10296. },
  10297. /**
  10298. * Returns the stack index for the given dataset based on groups and bar visibility.
  10299. * @param {number} [datasetIndex] - The dataset index
  10300. * @param {string} [name] - The stack name to find
  10301. * @returns {number} The stack index
  10302. * @private
  10303. */
  10304. getStackIndex: function(datasetIndex, name) {
  10305. var stacks = this._getStacks(datasetIndex);
  10306. var index = (name !== undefined)
  10307. ? stacks.indexOf(name)
  10308. : -1; // indexOf returns -1 if element is not present
  10309. return (index === -1)
  10310. ? stacks.length - 1
  10311. : index;
  10312. },
  10313. /**
  10314. * @private
  10315. */
  10316. getRuler: function() {
  10317. var me = this;
  10318. var scale = me._getIndexScale();
  10319. var pixels = [];
  10320. var i, ilen;
  10321. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  10322. pixels.push(scale.getPixelForValue(null, i, me.index));
  10323. }
  10324. return {
  10325. pixels: pixels,
  10326. start: scale._startPixel,
  10327. end: scale._endPixel,
  10328. stackCount: me.getStackCount(),
  10329. scale: scale
  10330. };
  10331. },
  10332. /**
  10333. * Note: pixel values are not clamped to the scale area.
  10334. * @private
  10335. */
  10336. calculateBarValuePixels: function(datasetIndex, index, options) {
  10337. var me = this;
  10338. var chart = me.chart;
  10339. var scale = me._getValueScale();
  10340. var isHorizontal = scale.isHorizontal();
  10341. var datasets = chart.data.datasets;
  10342. var metasets = scale._getMatchingVisibleMetas(me._type);
  10343. var value = scale._parseValue(datasets[datasetIndex].data[index]);
  10344. var minBarLength = options.minBarLength;
  10345. var stacked = scale.options.stacked;
  10346. var stack = me.getMeta().stack;
  10347. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  10348. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  10349. var ilen = metasets.length;
  10350. var i, imeta, ivalue, base, head, size, stackLength;
  10351. if (stacked || (stacked === undefined && stack !== undefined)) {
  10352. for (i = 0; i < ilen; ++i) {
  10353. imeta = metasets[i];
  10354. if (imeta.index === datasetIndex) {
  10355. break;
  10356. }
  10357. if (imeta.stack === stack) {
  10358. stackLength = scale._parseValue(datasets[imeta.index].data[index]);
  10359. ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
  10360. if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
  10361. start += ivalue;
  10362. }
  10363. }
  10364. }
  10365. }
  10366. base = scale.getPixelForValue(start);
  10367. head = scale.getPixelForValue(start + length);
  10368. size = head - base;
  10369. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  10370. size = minBarLength;
  10371. if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
  10372. head = base - minBarLength;
  10373. } else {
  10374. head = base + minBarLength;
  10375. }
  10376. }
  10377. return {
  10378. size: size,
  10379. base: base,
  10380. head: head,
  10381. center: head + size / 2
  10382. };
  10383. },
  10384. /**
  10385. * @private
  10386. */
  10387. calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {
  10388. var me = this;
  10389. var range = options.barThickness === 'flex'
  10390. ? computeFlexCategoryTraits(index, ruler, options)
  10391. : computeFitCategoryTraits(index, ruler, options);
  10392. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  10393. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  10394. var size = Math.min(
  10395. valueOrDefault$3(options.maxBarThickness, Infinity),
  10396. range.chunk * range.ratio);
  10397. return {
  10398. base: center - size / 2,
  10399. head: center + size / 2,
  10400. center: center,
  10401. size: size
  10402. };
  10403. },
  10404. draw: function() {
  10405. var me = this;
  10406. var chart = me.chart;
  10407. var scale = me._getValueScale();
  10408. var rects = me.getMeta().data;
  10409. var dataset = me.getDataset();
  10410. var ilen = rects.length;
  10411. var i = 0;
  10412. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  10413. for (; i < ilen; ++i) {
  10414. var val = scale._parseValue(dataset.data[i]);
  10415. if (!isNaN(val.min) && !isNaN(val.max)) {
  10416. rects[i].draw();
  10417. }
  10418. }
  10419. helpers$1.canvas.unclipArea(chart.ctx);
  10420. },
  10421. /**
  10422. * @private
  10423. */
  10424. _resolveDataElementOptions: function() {
  10425. var me = this;
  10426. var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));
  10427. var indexOpts = me._getIndexScale().options;
  10428. var valueOpts = me._getValueScale().options;
  10429. values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);
  10430. values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);
  10431. values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);
  10432. values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);
  10433. values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);
  10434. return values;
  10435. }
  10436. });
  10437. var valueOrDefault$4 = helpers$1.valueOrDefault;
  10438. var resolve$1 = helpers$1.options.resolve;
  10439. core_defaults._set('bubble', {
  10440. hover: {
  10441. mode: 'single'
  10442. },
  10443. scales: {
  10444. xAxes: [{
  10445. type: 'linear', // bubble should probably use a linear scale by default
  10446. position: 'bottom',
  10447. id: 'x-axis-0' // need an ID so datasets can reference the scale
  10448. }],
  10449. yAxes: [{
  10450. type: 'linear',
  10451. position: 'left',
  10452. id: 'y-axis-0'
  10453. }]
  10454. },
  10455. tooltips: {
  10456. callbacks: {
  10457. title: function() {
  10458. // Title doesn't make sense for scatter since we format the data as a point
  10459. return '';
  10460. },
  10461. label: function(item, data) {
  10462. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  10463. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  10464. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  10465. }
  10466. }
  10467. }
  10468. });
  10469. var controller_bubble = core_datasetController.extend({
  10470. /**
  10471. * @protected
  10472. */
  10473. dataElementType: elements.Point,
  10474. /**
  10475. * @private
  10476. */
  10477. _dataElementOptions: [
  10478. 'backgroundColor',
  10479. 'borderColor',
  10480. 'borderWidth',
  10481. 'hoverBackgroundColor',
  10482. 'hoverBorderColor',
  10483. 'hoverBorderWidth',
  10484. 'hoverRadius',
  10485. 'hitRadius',
  10486. 'pointStyle',
  10487. 'rotation'
  10488. ],
  10489. /**
  10490. * @protected
  10491. */
  10492. update: function(reset) {
  10493. var me = this;
  10494. var meta = me.getMeta();
  10495. var points = meta.data;
  10496. // Update Points
  10497. helpers$1.each(points, function(point, index) {
  10498. me.updateElement(point, index, reset);
  10499. });
  10500. },
  10501. /**
  10502. * @protected
  10503. */
  10504. updateElement: function(point, index, reset) {
  10505. var me = this;
  10506. var meta = me.getMeta();
  10507. var custom = point.custom || {};
  10508. var xScale = me.getScaleForId(meta.xAxisID);
  10509. var yScale = me.getScaleForId(meta.yAxisID);
  10510. var options = me._resolveDataElementOptions(point, index);
  10511. var data = me.getDataset().data[index];
  10512. var dsIndex = me.index;
  10513. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  10514. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  10515. point._xScale = xScale;
  10516. point._yScale = yScale;
  10517. point._options = options;
  10518. point._datasetIndex = dsIndex;
  10519. point._index = index;
  10520. point._model = {
  10521. backgroundColor: options.backgroundColor,
  10522. borderColor: options.borderColor,
  10523. borderWidth: options.borderWidth,
  10524. hitRadius: options.hitRadius,
  10525. pointStyle: options.pointStyle,
  10526. rotation: options.rotation,
  10527. radius: reset ? 0 : options.radius,
  10528. skip: custom.skip || isNaN(x) || isNaN(y),
  10529. x: x,
  10530. y: y,
  10531. };
  10532. point.pivot();
  10533. },
  10534. /**
  10535. * @protected
  10536. */
  10537. setHoverStyle: function(point) {
  10538. var model = point._model;
  10539. var options = point._options;
  10540. var getHoverColor = helpers$1.getHoverColor;
  10541. point.$previousStyle = {
  10542. backgroundColor: model.backgroundColor,
  10543. borderColor: model.borderColor,
  10544. borderWidth: model.borderWidth,
  10545. radius: model.radius
  10546. };
  10547. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  10548. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  10549. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  10550. model.radius = options.radius + options.hoverRadius;
  10551. },
  10552. /**
  10553. * @private
  10554. */
  10555. _resolveDataElementOptions: function(point, index) {
  10556. var me = this;
  10557. var chart = me.chart;
  10558. var dataset = me.getDataset();
  10559. var custom = point.custom || {};
  10560. var data = dataset.data[index] || {};
  10561. var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);
  10562. // Scriptable options
  10563. var context = {
  10564. chart: chart,
  10565. dataIndex: index,
  10566. dataset: dataset,
  10567. datasetIndex: me.index
  10568. };
  10569. // In case values were cached (and thus frozen), we need to clone the values
  10570. if (me._cachedDataOpts === values) {
  10571. values = helpers$1.extend({}, values);
  10572. }
  10573. // Custom radius resolution
  10574. values.radius = resolve$1([
  10575. custom.radius,
  10576. data.r,
  10577. me._config.radius,
  10578. chart.options.elements.point.radius
  10579. ], context, index);
  10580. return values;
  10581. }
  10582. });
  10583. var valueOrDefault$5 = helpers$1.valueOrDefault;
  10584. var PI$1 = Math.PI;
  10585. var DOUBLE_PI$1 = PI$1 * 2;
  10586. var HALF_PI$1 = PI$1 / 2;
  10587. core_defaults._set('doughnut', {
  10588. animation: {
  10589. // Boolean - Whether we animate the rotation of the Doughnut
  10590. animateRotate: true,
  10591. // Boolean - Whether we animate scaling the Doughnut from the centre
  10592. animateScale: false
  10593. },
  10594. hover: {
  10595. mode: 'single'
  10596. },
  10597. legendCallback: function(chart) {
  10598. var list = document.createElement('ul');
  10599. var data = chart.data;
  10600. var datasets = data.datasets;
  10601. var labels = data.labels;
  10602. var i, ilen, listItem, listItemSpan;
  10603. list.setAttribute('class', chart.id + '-legend');
  10604. if (datasets.length) {
  10605. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  10606. listItem = list.appendChild(document.createElement('li'));
  10607. listItemSpan = listItem.appendChild(document.createElement('span'));
  10608. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  10609. if (labels[i]) {
  10610. listItem.appendChild(document.createTextNode(labels[i]));
  10611. }
  10612. }
  10613. }
  10614. return list.outerHTML;
  10615. },
  10616. legend: {
  10617. labels: {
  10618. generateLabels: function(chart) {
  10619. var data = chart.data;
  10620. if (data.labels.length && data.datasets.length) {
  10621. return data.labels.map(function(label, i) {
  10622. var meta = chart.getDatasetMeta(0);
  10623. var style = meta.controller.getStyle(i);
  10624. return {
  10625. text: label,
  10626. fillStyle: style.backgroundColor,
  10627. strokeStyle: style.borderColor,
  10628. lineWidth: style.borderWidth,
  10629. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  10630. // Extra data used for toggling the correct item
  10631. index: i
  10632. };
  10633. });
  10634. }
  10635. return [];
  10636. }
  10637. },
  10638. onClick: function(e, legendItem) {
  10639. var index = legendItem.index;
  10640. var chart = this.chart;
  10641. var i, ilen, meta;
  10642. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  10643. meta = chart.getDatasetMeta(i);
  10644. // toggle visibility of index if exists
  10645. if (meta.data[index]) {
  10646. meta.data[index].hidden = !meta.data[index].hidden;
  10647. }
  10648. }
  10649. chart.update();
  10650. }
  10651. },
  10652. // The percentage of the chart that we cut out of the middle.
  10653. cutoutPercentage: 50,
  10654. // The rotation of the chart, where the first data arc begins.
  10655. rotation: -HALF_PI$1,
  10656. // The total circumference of the chart.
  10657. circumference: DOUBLE_PI$1,
  10658. // Need to override these to give a nice default
  10659. tooltips: {
  10660. callbacks: {
  10661. title: function() {
  10662. return '';
  10663. },
  10664. label: function(tooltipItem, data) {
  10665. var dataLabel = data.labels[tooltipItem.index];
  10666. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  10667. if (helpers$1.isArray(dataLabel)) {
  10668. // show value on first line of multiline label
  10669. // need to clone because we are changing the value
  10670. dataLabel = dataLabel.slice();
  10671. dataLabel[0] += value;
  10672. } else {
  10673. dataLabel += value;
  10674. }
  10675. return dataLabel;
  10676. }
  10677. }
  10678. }
  10679. });
  10680. var controller_doughnut = core_datasetController.extend({
  10681. dataElementType: elements.Arc,
  10682. linkScales: helpers$1.noop,
  10683. /**
  10684. * @private
  10685. */
  10686. _dataElementOptions: [
  10687. 'backgroundColor',
  10688. 'borderColor',
  10689. 'borderWidth',
  10690. 'borderAlign',
  10691. 'hoverBackgroundColor',
  10692. 'hoverBorderColor',
  10693. 'hoverBorderWidth',
  10694. ],
  10695. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  10696. getRingIndex: function(datasetIndex) {
  10697. var ringIndex = 0;
  10698. for (var j = 0; j < datasetIndex; ++j) {
  10699. if (this.chart.isDatasetVisible(j)) {
  10700. ++ringIndex;
  10701. }
  10702. }
  10703. return ringIndex;
  10704. },
  10705. update: function(reset) {
  10706. var me = this;
  10707. var chart = me.chart;
  10708. var chartArea = chart.chartArea;
  10709. var opts = chart.options;
  10710. var ratioX = 1;
  10711. var ratioY = 1;
  10712. var offsetX = 0;
  10713. var offsetY = 0;
  10714. var meta = me.getMeta();
  10715. var arcs = meta.data;
  10716. var cutout = opts.cutoutPercentage / 100 || 0;
  10717. var circumference = opts.circumference;
  10718. var chartWeight = me._getRingWeight(me.index);
  10719. var maxWidth, maxHeight, i, ilen;
  10720. // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
  10721. if (circumference < DOUBLE_PI$1) {
  10722. var startAngle = opts.rotation % DOUBLE_PI$1;
  10723. startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;
  10724. var endAngle = startAngle + circumference;
  10725. var startX = Math.cos(startAngle);
  10726. var startY = Math.sin(startAngle);
  10727. var endX = Math.cos(endAngle);
  10728. var endY = Math.sin(endAngle);
  10729. var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;
  10730. var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;
  10731. var contains180 = startAngle === -PI$1 || endAngle >= PI$1;
  10732. var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;
  10733. var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
  10734. var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
  10735. var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
  10736. var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
  10737. ratioX = (maxX - minX) / 2;
  10738. ratioY = (maxY - minY) / 2;
  10739. offsetX = -(maxX + minX) / 2;
  10740. offsetY = -(maxY + minY) / 2;
  10741. }
  10742. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  10743. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  10744. }
  10745. chart.borderWidth = me.getMaxBorderWidth();
  10746. maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
  10747. maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
  10748. chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  10749. chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
  10750. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  10751. chart.offsetX = offsetX * chart.outerRadius;
  10752. chart.offsetY = offsetY * chart.outerRadius;
  10753. meta.total = me.calculateTotal();
  10754. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  10755. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  10756. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  10757. me.updateElement(arcs[i], i, reset);
  10758. }
  10759. },
  10760. updateElement: function(arc, index, reset) {
  10761. var me = this;
  10762. var chart = me.chart;
  10763. var chartArea = chart.chartArea;
  10764. var opts = chart.options;
  10765. var animationOpts = opts.animation;
  10766. var centerX = (chartArea.left + chartArea.right) / 2;
  10767. var centerY = (chartArea.top + chartArea.bottom) / 2;
  10768. var startAngle = opts.rotation; // non reset case handled later
  10769. var endAngle = opts.rotation; // non reset case handled later
  10770. var dataset = me.getDataset();
  10771. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1);
  10772. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  10773. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  10774. var options = arc._options || {};
  10775. helpers$1.extend(arc, {
  10776. // Utility
  10777. _datasetIndex: me.index,
  10778. _index: index,
  10779. // Desired view properties
  10780. _model: {
  10781. backgroundColor: options.backgroundColor,
  10782. borderColor: options.borderColor,
  10783. borderWidth: options.borderWidth,
  10784. borderAlign: options.borderAlign,
  10785. x: centerX + chart.offsetX,
  10786. y: centerY + chart.offsetY,
  10787. startAngle: startAngle,
  10788. endAngle: endAngle,
  10789. circumference: circumference,
  10790. outerRadius: outerRadius,
  10791. innerRadius: innerRadius,
  10792. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  10793. }
  10794. });
  10795. var model = arc._model;
  10796. // Set correct angles if not resetting
  10797. if (!reset || !animationOpts.animateRotate) {
  10798. if (index === 0) {
  10799. model.startAngle = opts.rotation;
  10800. } else {
  10801. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  10802. }
  10803. model.endAngle = model.startAngle + model.circumference;
  10804. }
  10805. arc.pivot();
  10806. },
  10807. calculateTotal: function() {
  10808. var dataset = this.getDataset();
  10809. var meta = this.getMeta();
  10810. var total = 0;
  10811. var value;
  10812. helpers$1.each(meta.data, function(element, index) {
  10813. value = dataset.data[index];
  10814. if (!isNaN(value) && !element.hidden) {
  10815. total += Math.abs(value);
  10816. }
  10817. });
  10818. /* if (total === 0) {
  10819. total = NaN;
  10820. }*/
  10821. return total;
  10822. },
  10823. calculateCircumference: function(value) {
  10824. var total = this.getMeta().total;
  10825. if (total > 0 && !isNaN(value)) {
  10826. return DOUBLE_PI$1 * (Math.abs(value) / total);
  10827. }
  10828. return 0;
  10829. },
  10830. // gets the max border or hover width to properly scale pie charts
  10831. getMaxBorderWidth: function(arcs) {
  10832. var me = this;
  10833. var max = 0;
  10834. var chart = me.chart;
  10835. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  10836. if (!arcs) {
  10837. // Find the outmost visible dataset
  10838. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  10839. if (chart.isDatasetVisible(i)) {
  10840. meta = chart.getDatasetMeta(i);
  10841. arcs = meta.data;
  10842. if (i !== me.index) {
  10843. controller = meta.controller;
  10844. }
  10845. break;
  10846. }
  10847. }
  10848. }
  10849. if (!arcs) {
  10850. return 0;
  10851. }
  10852. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  10853. arc = arcs[i];
  10854. if (controller) {
  10855. controller._configure();
  10856. options = controller._resolveDataElementOptions(arc, i);
  10857. } else {
  10858. options = arc._options;
  10859. }
  10860. if (options.borderAlign !== 'inner') {
  10861. borderWidth = options.borderWidth;
  10862. hoverWidth = options.hoverBorderWidth;
  10863. max = borderWidth > max ? borderWidth : max;
  10864. max = hoverWidth > max ? hoverWidth : max;
  10865. }
  10866. }
  10867. return max;
  10868. },
  10869. /**
  10870. * @protected
  10871. */
  10872. setHoverStyle: function(arc) {
  10873. var model = arc._model;
  10874. var options = arc._options;
  10875. var getHoverColor = helpers$1.getHoverColor;
  10876. arc.$previousStyle = {
  10877. backgroundColor: model.backgroundColor,
  10878. borderColor: model.borderColor,
  10879. borderWidth: model.borderWidth,
  10880. };
  10881. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  10882. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  10883. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  10884. },
  10885. /**
  10886. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  10887. * @private
  10888. */
  10889. _getRingWeightOffset: function(datasetIndex) {
  10890. var ringWeightOffset = 0;
  10891. for (var i = 0; i < datasetIndex; ++i) {
  10892. if (this.chart.isDatasetVisible(i)) {
  10893. ringWeightOffset += this._getRingWeight(i);
  10894. }
  10895. }
  10896. return ringWeightOffset;
  10897. },
  10898. /**
  10899. * @private
  10900. */
  10901. _getRingWeight: function(dataSetIndex) {
  10902. return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  10903. },
  10904. /**
  10905. * Returns the sum of all visibile data set weights. This value can be 0.
  10906. * @private
  10907. */
  10908. _getVisibleDatasetWeightTotal: function() {
  10909. return this._getRingWeightOffset(this.chart.data.datasets.length);
  10910. }
  10911. });
  10912. core_defaults._set('horizontalBar', {
  10913. hover: {
  10914. mode: 'index',
  10915. axis: 'y'
  10916. },
  10917. scales: {
  10918. xAxes: [{
  10919. type: 'linear',
  10920. position: 'bottom'
  10921. }],
  10922. yAxes: [{
  10923. type: 'category',
  10924. position: 'left',
  10925. offset: true,
  10926. gridLines: {
  10927. offsetGridLines: true
  10928. }
  10929. }]
  10930. },
  10931. elements: {
  10932. rectangle: {
  10933. borderSkipped: 'left'
  10934. }
  10935. },
  10936. tooltips: {
  10937. mode: 'index',
  10938. axis: 'y'
  10939. }
  10940. });
  10941. core_defaults._set('global', {
  10942. datasets: {
  10943. horizontalBar: {
  10944. categoryPercentage: 0.8,
  10945. barPercentage: 0.9
  10946. }
  10947. }
  10948. });
  10949. var controller_horizontalBar = controller_bar.extend({
  10950. /**
  10951. * @private
  10952. */
  10953. _getValueScaleId: function() {
  10954. return this.getMeta().xAxisID;
  10955. },
  10956. /**
  10957. * @private
  10958. */
  10959. _getIndexScaleId: function() {
  10960. return this.getMeta().yAxisID;
  10961. }
  10962. });
  10963. var valueOrDefault$6 = helpers$1.valueOrDefault;
  10964. var resolve$2 = helpers$1.options.resolve;
  10965. var isPointInArea = helpers$1.canvas._isPointInArea;
  10966. core_defaults._set('line', {
  10967. showLines: true,
  10968. spanGaps: false,
  10969. hover: {
  10970. mode: 'label'
  10971. },
  10972. scales: {
  10973. xAxes: [{
  10974. type: 'category',
  10975. id: 'x-axis-0'
  10976. }],
  10977. yAxes: [{
  10978. type: 'linear',
  10979. id: 'y-axis-0'
  10980. }]
  10981. }
  10982. });
  10983. function scaleClip(scale, halfBorderWidth) {
  10984. var tickOpts = scale && scale.options.ticks || {};
  10985. var reverse = tickOpts.reverse;
  10986. var min = tickOpts.min === undefined ? halfBorderWidth : 0;
  10987. var max = tickOpts.max === undefined ? halfBorderWidth : 0;
  10988. return {
  10989. start: reverse ? max : min,
  10990. end: reverse ? min : max
  10991. };
  10992. }
  10993. function defaultClip(xScale, yScale, borderWidth) {
  10994. var halfBorderWidth = borderWidth / 2;
  10995. var x = scaleClip(xScale, halfBorderWidth);
  10996. var y = scaleClip(yScale, halfBorderWidth);
  10997. return {
  10998. top: y.end,
  10999. right: x.end,
  11000. bottom: y.start,
  11001. left: x.start
  11002. };
  11003. }
  11004. function toClip(value) {
  11005. var t, r, b, l;
  11006. if (helpers$1.isObject(value)) {
  11007. t = value.top;
  11008. r = value.right;
  11009. b = value.bottom;
  11010. l = value.left;
  11011. } else {
  11012. t = r = b = l = value;
  11013. }
  11014. return {
  11015. top: t,
  11016. right: r,
  11017. bottom: b,
  11018. left: l
  11019. };
  11020. }
  11021. var controller_line = core_datasetController.extend({
  11022. datasetElementType: elements.Line,
  11023. dataElementType: elements.Point,
  11024. /**
  11025. * @private
  11026. */
  11027. _datasetElementOptions: [
  11028. 'backgroundColor',
  11029. 'borderCapStyle',
  11030. 'borderColor',
  11031. 'borderDash',
  11032. 'borderDashOffset',
  11033. 'borderJoinStyle',
  11034. 'borderWidth',
  11035. 'cubicInterpolationMode',
  11036. 'fill'
  11037. ],
  11038. /**
  11039. * @private
  11040. */
  11041. _dataElementOptions: {
  11042. backgroundColor: 'pointBackgroundColor',
  11043. borderColor: 'pointBorderColor',
  11044. borderWidth: 'pointBorderWidth',
  11045. hitRadius: 'pointHitRadius',
  11046. hoverBackgroundColor: 'pointHoverBackgroundColor',
  11047. hoverBorderColor: 'pointHoverBorderColor',
  11048. hoverBorderWidth: 'pointHoverBorderWidth',
  11049. hoverRadius: 'pointHoverRadius',
  11050. pointStyle: 'pointStyle',
  11051. radius: 'pointRadius',
  11052. rotation: 'pointRotation'
  11053. },
  11054. update: function(reset) {
  11055. var me = this;
  11056. var meta = me.getMeta();
  11057. var line = meta.dataset;
  11058. var points = meta.data || [];
  11059. var options = me.chart.options;
  11060. var config = me._config;
  11061. var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);
  11062. var i, ilen;
  11063. me._xScale = me.getScaleForId(meta.xAxisID);
  11064. me._yScale = me.getScaleForId(meta.yAxisID);
  11065. // Update Line
  11066. if (showLine) {
  11067. // Compatibility: If the properties are defined with only the old name, use those values
  11068. if (config.tension !== undefined && config.lineTension === undefined) {
  11069. config.lineTension = config.tension;
  11070. }
  11071. // Utility
  11072. line._scale = me._yScale;
  11073. line._datasetIndex = me.index;
  11074. // Data
  11075. line._children = points;
  11076. // Model
  11077. line._model = me._resolveDatasetElementOptions(line);
  11078. line.pivot();
  11079. }
  11080. // Update Points
  11081. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11082. me.updateElement(points[i], i, reset);
  11083. }
  11084. if (showLine && line._model.tension !== 0) {
  11085. me.updateBezierControlPoints();
  11086. }
  11087. // Now pivot the point for animation
  11088. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11089. points[i].pivot();
  11090. }
  11091. },
  11092. updateElement: function(point, index, reset) {
  11093. var me = this;
  11094. var meta = me.getMeta();
  11095. var custom = point.custom || {};
  11096. var dataset = me.getDataset();
  11097. var datasetIndex = me.index;
  11098. var value = dataset.data[index];
  11099. var xScale = me._xScale;
  11100. var yScale = me._yScale;
  11101. var lineModel = meta.dataset._model;
  11102. var x, y;
  11103. var options = me._resolveDataElementOptions(point, index);
  11104. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  11105. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  11106. // Utility
  11107. point._xScale = xScale;
  11108. point._yScale = yScale;
  11109. point._options = options;
  11110. point._datasetIndex = datasetIndex;
  11111. point._index = index;
  11112. // Desired view properties
  11113. point._model = {
  11114. x: x,
  11115. y: y,
  11116. skip: custom.skip || isNaN(x) || isNaN(y),
  11117. // Appearance
  11118. radius: options.radius,
  11119. pointStyle: options.pointStyle,
  11120. rotation: options.rotation,
  11121. backgroundColor: options.backgroundColor,
  11122. borderColor: options.borderColor,
  11123. borderWidth: options.borderWidth,
  11124. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  11125. steppedLine: lineModel ? lineModel.steppedLine : false,
  11126. // Tooltip
  11127. hitRadius: options.hitRadius
  11128. };
  11129. },
  11130. /**
  11131. * @private
  11132. */
  11133. _resolveDatasetElementOptions: function(element) {
  11134. var me = this;
  11135. var config = me._config;
  11136. var custom = element.custom || {};
  11137. var options = me.chart.options;
  11138. var lineOptions = options.elements.line;
  11139. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  11140. // The default behavior of lines is to break at null values, according
  11141. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  11142. // This option gives lines the ability to span gaps
  11143. values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps);
  11144. values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);
  11145. values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
  11146. values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
  11147. return values;
  11148. },
  11149. calculatePointY: function(value, index, datasetIndex) {
  11150. var me = this;
  11151. var chart = me.chart;
  11152. var yScale = me._yScale;
  11153. var sumPos = 0;
  11154. var sumNeg = 0;
  11155. var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
  11156. if (yScale.options.stacked) {
  11157. rightValue = +yScale.getRightValue(value);
  11158. metasets = chart._getSortedVisibleDatasetMetas();
  11159. ilen = metasets.length;
  11160. for (i = 0; i < ilen; ++i) {
  11161. dsMeta = metasets[i];
  11162. if (dsMeta.index === datasetIndex) {
  11163. break;
  11164. }
  11165. ds = chart.data.datasets[dsMeta.index];
  11166. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
  11167. stackedRightValue = +yScale.getRightValue(ds.data[index]);
  11168. if (stackedRightValue < 0) {
  11169. sumNeg += stackedRightValue || 0;
  11170. } else {
  11171. sumPos += stackedRightValue || 0;
  11172. }
  11173. }
  11174. }
  11175. if (rightValue < 0) {
  11176. return yScale.getPixelForValue(sumNeg + rightValue);
  11177. }
  11178. return yScale.getPixelForValue(sumPos + rightValue);
  11179. }
  11180. return yScale.getPixelForValue(value);
  11181. },
  11182. updateBezierControlPoints: function() {
  11183. var me = this;
  11184. var chart = me.chart;
  11185. var meta = me.getMeta();
  11186. var lineModel = meta.dataset._model;
  11187. var area = chart.chartArea;
  11188. var points = meta.data || [];
  11189. var i, ilen, model, controlPoints;
  11190. // Only consider points that are drawn in case the spanGaps option is used
  11191. if (lineModel.spanGaps) {
  11192. points = points.filter(function(pt) {
  11193. return !pt._model.skip;
  11194. });
  11195. }
  11196. function capControlPoint(pt, min, max) {
  11197. return Math.max(Math.min(pt, max), min);
  11198. }
  11199. if (lineModel.cubicInterpolationMode === 'monotone') {
  11200. helpers$1.splineCurveMonotone(points);
  11201. } else {
  11202. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11203. model = points[i]._model;
  11204. controlPoints = helpers$1.splineCurve(
  11205. helpers$1.previousItem(points, i)._model,
  11206. model,
  11207. helpers$1.nextItem(points, i)._model,
  11208. lineModel.tension
  11209. );
  11210. model.controlPointPreviousX = controlPoints.previous.x;
  11211. model.controlPointPreviousY = controlPoints.previous.y;
  11212. model.controlPointNextX = controlPoints.next.x;
  11213. model.controlPointNextY = controlPoints.next.y;
  11214. }
  11215. }
  11216. if (chart.options.elements.line.capBezierPoints) {
  11217. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11218. model = points[i]._model;
  11219. if (isPointInArea(model, area)) {
  11220. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  11221. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  11222. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  11223. }
  11224. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  11225. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  11226. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  11227. }
  11228. }
  11229. }
  11230. }
  11231. },
  11232. draw: function() {
  11233. var me = this;
  11234. var chart = me.chart;
  11235. var meta = me.getMeta();
  11236. var points = meta.data || [];
  11237. var area = chart.chartArea;
  11238. var canvas = chart.canvas;
  11239. var i = 0;
  11240. var ilen = points.length;
  11241. var clip;
  11242. if (me._showLine) {
  11243. clip = meta.dataset._model.clip;
  11244. helpers$1.canvas.clipArea(chart.ctx, {
  11245. left: clip.left === false ? 0 : area.left - clip.left,
  11246. right: clip.right === false ? canvas.width : area.right + clip.right,
  11247. top: clip.top === false ? 0 : area.top - clip.top,
  11248. bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
  11249. });
  11250. meta.dataset.draw();
  11251. helpers$1.canvas.unclipArea(chart.ctx);
  11252. }
  11253. // Draw the points
  11254. for (; i < ilen; ++i) {
  11255. points[i].draw(area);
  11256. }
  11257. },
  11258. /**
  11259. * @protected
  11260. */
  11261. setHoverStyle: function(point) {
  11262. var model = point._model;
  11263. var options = point._options;
  11264. var getHoverColor = helpers$1.getHoverColor;
  11265. point.$previousStyle = {
  11266. backgroundColor: model.backgroundColor,
  11267. borderColor: model.borderColor,
  11268. borderWidth: model.borderWidth,
  11269. radius: model.radius
  11270. };
  11271. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  11272. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  11273. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  11274. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  11275. },
  11276. });
  11277. var resolve$3 = helpers$1.options.resolve;
  11278. core_defaults._set('polarArea', {
  11279. scale: {
  11280. type: 'radialLinear',
  11281. angleLines: {
  11282. display: false
  11283. },
  11284. gridLines: {
  11285. circular: true
  11286. },
  11287. pointLabels: {
  11288. display: false
  11289. },
  11290. ticks: {
  11291. beginAtZero: true
  11292. }
  11293. },
  11294. // Boolean - Whether to animate the rotation of the chart
  11295. animation: {
  11296. animateRotate: true,
  11297. animateScale: true
  11298. },
  11299. startAngle: -0.5 * Math.PI,
  11300. legendCallback: function(chart) {
  11301. var list = document.createElement('ul');
  11302. var data = chart.data;
  11303. var datasets = data.datasets;
  11304. var labels = data.labels;
  11305. var i, ilen, listItem, listItemSpan;
  11306. list.setAttribute('class', chart.id + '-legend');
  11307. if (datasets.length) {
  11308. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  11309. listItem = list.appendChild(document.createElement('li'));
  11310. listItemSpan = listItem.appendChild(document.createElement('span'));
  11311. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  11312. if (labels[i]) {
  11313. listItem.appendChild(document.createTextNode(labels[i]));
  11314. }
  11315. }
  11316. }
  11317. return list.outerHTML;
  11318. },
  11319. legend: {
  11320. labels: {
  11321. generateLabels: function(chart) {
  11322. var data = chart.data;
  11323. if (data.labels.length && data.datasets.length) {
  11324. return data.labels.map(function(label, i) {
  11325. var meta = chart.getDatasetMeta(0);
  11326. var style = meta.controller.getStyle(i);
  11327. return {
  11328. text: label,
  11329. fillStyle: style.backgroundColor,
  11330. strokeStyle: style.borderColor,
  11331. lineWidth: style.borderWidth,
  11332. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  11333. // Extra data used for toggling the correct item
  11334. index: i
  11335. };
  11336. });
  11337. }
  11338. return [];
  11339. }
  11340. },
  11341. onClick: function(e, legendItem) {
  11342. var index = legendItem.index;
  11343. var chart = this.chart;
  11344. var i, ilen, meta;
  11345. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  11346. meta = chart.getDatasetMeta(i);
  11347. meta.data[index].hidden = !meta.data[index].hidden;
  11348. }
  11349. chart.update();
  11350. }
  11351. },
  11352. // Need to override these to give a nice default
  11353. tooltips: {
  11354. callbacks: {
  11355. title: function() {
  11356. return '';
  11357. },
  11358. label: function(item, data) {
  11359. return data.labels[item.index] + ': ' + item.yLabel;
  11360. }
  11361. }
  11362. }
  11363. });
  11364. var controller_polarArea = core_datasetController.extend({
  11365. dataElementType: elements.Arc,
  11366. linkScales: helpers$1.noop,
  11367. /**
  11368. * @private
  11369. */
  11370. _dataElementOptions: [
  11371. 'backgroundColor',
  11372. 'borderColor',
  11373. 'borderWidth',
  11374. 'borderAlign',
  11375. 'hoverBackgroundColor',
  11376. 'hoverBorderColor',
  11377. 'hoverBorderWidth',
  11378. ],
  11379. /**
  11380. * @private
  11381. */
  11382. _getIndexScaleId: function() {
  11383. return this.chart.scale.id;
  11384. },
  11385. /**
  11386. * @private
  11387. */
  11388. _getValueScaleId: function() {
  11389. return this.chart.scale.id;
  11390. },
  11391. update: function(reset) {
  11392. var me = this;
  11393. var dataset = me.getDataset();
  11394. var meta = me.getMeta();
  11395. var start = me.chart.options.startAngle || 0;
  11396. var starts = me._starts = [];
  11397. var angles = me._angles = [];
  11398. var arcs = meta.data;
  11399. var i, ilen, angle;
  11400. me._updateRadius();
  11401. meta.count = me.countVisibleElements();
  11402. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  11403. starts[i] = start;
  11404. angle = me._computeAngle(i);
  11405. angles[i] = angle;
  11406. start += angle;
  11407. }
  11408. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  11409. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  11410. me.updateElement(arcs[i], i, reset);
  11411. }
  11412. },
  11413. /**
  11414. * @private
  11415. */
  11416. _updateRadius: function() {
  11417. var me = this;
  11418. var chart = me.chart;
  11419. var chartArea = chart.chartArea;
  11420. var opts = chart.options;
  11421. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  11422. chart.outerRadius = Math.max(minSize / 2, 0);
  11423. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  11424. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  11425. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  11426. me.innerRadius = me.outerRadius - chart.radiusLength;
  11427. },
  11428. updateElement: function(arc, index, reset) {
  11429. var me = this;
  11430. var chart = me.chart;
  11431. var dataset = me.getDataset();
  11432. var opts = chart.options;
  11433. var animationOpts = opts.animation;
  11434. var scale = chart.scale;
  11435. var labels = chart.data.labels;
  11436. var centerX = scale.xCenter;
  11437. var centerY = scale.yCenter;
  11438. // var negHalfPI = -0.5 * Math.PI;
  11439. var datasetStartAngle = opts.startAngle;
  11440. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  11441. var startAngle = me._starts[index];
  11442. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  11443. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  11444. var options = arc._options || {};
  11445. helpers$1.extend(arc, {
  11446. // Utility
  11447. _datasetIndex: me.index,
  11448. _index: index,
  11449. _scale: scale,
  11450. // Desired view properties
  11451. _model: {
  11452. backgroundColor: options.backgroundColor,
  11453. borderColor: options.borderColor,
  11454. borderWidth: options.borderWidth,
  11455. borderAlign: options.borderAlign,
  11456. x: centerX,
  11457. y: centerY,
  11458. innerRadius: 0,
  11459. outerRadius: reset ? resetRadius : distance,
  11460. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  11461. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  11462. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  11463. }
  11464. });
  11465. arc.pivot();
  11466. },
  11467. countVisibleElements: function() {
  11468. var dataset = this.getDataset();
  11469. var meta = this.getMeta();
  11470. var count = 0;
  11471. helpers$1.each(meta.data, function(element, index) {
  11472. if (!isNaN(dataset.data[index]) && !element.hidden) {
  11473. count++;
  11474. }
  11475. });
  11476. return count;
  11477. },
  11478. /**
  11479. * @protected
  11480. */
  11481. setHoverStyle: function(arc) {
  11482. var model = arc._model;
  11483. var options = arc._options;
  11484. var getHoverColor = helpers$1.getHoverColor;
  11485. var valueOrDefault = helpers$1.valueOrDefault;
  11486. arc.$previousStyle = {
  11487. backgroundColor: model.backgroundColor,
  11488. borderColor: model.borderColor,
  11489. borderWidth: model.borderWidth,
  11490. };
  11491. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  11492. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  11493. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  11494. },
  11495. /**
  11496. * @private
  11497. */
  11498. _computeAngle: function(index) {
  11499. var me = this;
  11500. var count = this.getMeta().count;
  11501. var dataset = me.getDataset();
  11502. var meta = me.getMeta();
  11503. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  11504. return 0;
  11505. }
  11506. // Scriptable options
  11507. var context = {
  11508. chart: me.chart,
  11509. dataIndex: index,
  11510. dataset: dataset,
  11511. datasetIndex: me.index
  11512. };
  11513. return resolve$3([
  11514. me.chart.options.elements.arc.angle,
  11515. (2 * Math.PI) / count
  11516. ], context, index);
  11517. }
  11518. });
  11519. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  11520. core_defaults._set('pie', {
  11521. cutoutPercentage: 0
  11522. });
  11523. // Pie charts are Doughnut chart with different defaults
  11524. var controller_pie = controller_doughnut;
  11525. var valueOrDefault$7 = helpers$1.valueOrDefault;
  11526. core_defaults._set('radar', {
  11527. spanGaps: false,
  11528. scale: {
  11529. type: 'radialLinear'
  11530. },
  11531. elements: {
  11532. line: {
  11533. fill: 'start',
  11534. tension: 0 // no bezier in radar
  11535. }
  11536. }
  11537. });
  11538. var controller_radar = core_datasetController.extend({
  11539. datasetElementType: elements.Line,
  11540. dataElementType: elements.Point,
  11541. linkScales: helpers$1.noop,
  11542. /**
  11543. * @private
  11544. */
  11545. _datasetElementOptions: [
  11546. 'backgroundColor',
  11547. 'borderWidth',
  11548. 'borderColor',
  11549. 'borderCapStyle',
  11550. 'borderDash',
  11551. 'borderDashOffset',
  11552. 'borderJoinStyle',
  11553. 'fill'
  11554. ],
  11555. /**
  11556. * @private
  11557. */
  11558. _dataElementOptions: {
  11559. backgroundColor: 'pointBackgroundColor',
  11560. borderColor: 'pointBorderColor',
  11561. borderWidth: 'pointBorderWidth',
  11562. hitRadius: 'pointHitRadius',
  11563. hoverBackgroundColor: 'pointHoverBackgroundColor',
  11564. hoverBorderColor: 'pointHoverBorderColor',
  11565. hoverBorderWidth: 'pointHoverBorderWidth',
  11566. hoverRadius: 'pointHoverRadius',
  11567. pointStyle: 'pointStyle',
  11568. radius: 'pointRadius',
  11569. rotation: 'pointRotation'
  11570. },
  11571. /**
  11572. * @private
  11573. */
  11574. _getIndexScaleId: function() {
  11575. return this.chart.scale.id;
  11576. },
  11577. /**
  11578. * @private
  11579. */
  11580. _getValueScaleId: function() {
  11581. return this.chart.scale.id;
  11582. },
  11583. update: function(reset) {
  11584. var me = this;
  11585. var meta = me.getMeta();
  11586. var line = meta.dataset;
  11587. var points = meta.data || [];
  11588. var scale = me.chart.scale;
  11589. var config = me._config;
  11590. var i, ilen;
  11591. // Compatibility: If the properties are defined with only the old name, use those values
  11592. if (config.tension !== undefined && config.lineTension === undefined) {
  11593. config.lineTension = config.tension;
  11594. }
  11595. // Utility
  11596. line._scale = scale;
  11597. line._datasetIndex = me.index;
  11598. // Data
  11599. line._children = points;
  11600. line._loop = true;
  11601. // Model
  11602. line._model = me._resolveDatasetElementOptions(line);
  11603. line.pivot();
  11604. // Update Points
  11605. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11606. me.updateElement(points[i], i, reset);
  11607. }
  11608. // Update bezier control points
  11609. me.updateBezierControlPoints();
  11610. // Now pivot the point for animation
  11611. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11612. points[i].pivot();
  11613. }
  11614. },
  11615. updateElement: function(point, index, reset) {
  11616. var me = this;
  11617. var custom = point.custom || {};
  11618. var dataset = me.getDataset();
  11619. var scale = me.chart.scale;
  11620. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  11621. var options = me._resolveDataElementOptions(point, index);
  11622. var lineModel = me.getMeta().dataset._model;
  11623. var x = reset ? scale.xCenter : pointPosition.x;
  11624. var y = reset ? scale.yCenter : pointPosition.y;
  11625. // Utility
  11626. point._scale = scale;
  11627. point._options = options;
  11628. point._datasetIndex = me.index;
  11629. point._index = index;
  11630. // Desired view properties
  11631. point._model = {
  11632. x: x, // value not used in dataset scale, but we want a consistent API between scales
  11633. y: y,
  11634. skip: custom.skip || isNaN(x) || isNaN(y),
  11635. // Appearance
  11636. radius: options.radius,
  11637. pointStyle: options.pointStyle,
  11638. rotation: options.rotation,
  11639. backgroundColor: options.backgroundColor,
  11640. borderColor: options.borderColor,
  11641. borderWidth: options.borderWidth,
  11642. tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0),
  11643. // Tooltip
  11644. hitRadius: options.hitRadius
  11645. };
  11646. },
  11647. /**
  11648. * @private
  11649. */
  11650. _resolveDatasetElementOptions: function() {
  11651. var me = this;
  11652. var config = me._config;
  11653. var options = me.chart.options;
  11654. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  11655. values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);
  11656. values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);
  11657. return values;
  11658. },
  11659. updateBezierControlPoints: function() {
  11660. var me = this;
  11661. var meta = me.getMeta();
  11662. var area = me.chart.chartArea;
  11663. var points = meta.data || [];
  11664. var i, ilen, model, controlPoints;
  11665. // Only consider points that are drawn in case the spanGaps option is used
  11666. if (meta.dataset._model.spanGaps) {
  11667. points = points.filter(function(pt) {
  11668. return !pt._model.skip;
  11669. });
  11670. }
  11671. function capControlPoint(pt, min, max) {
  11672. return Math.max(Math.min(pt, max), min);
  11673. }
  11674. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11675. model = points[i]._model;
  11676. controlPoints = helpers$1.splineCurve(
  11677. helpers$1.previousItem(points, i, true)._model,
  11678. model,
  11679. helpers$1.nextItem(points, i, true)._model,
  11680. model.tension
  11681. );
  11682. // Prevent the bezier going outside of the bounds of the graph
  11683. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  11684. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  11685. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  11686. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  11687. }
  11688. },
  11689. setHoverStyle: function(point) {
  11690. var model = point._model;
  11691. var options = point._options;
  11692. var getHoverColor = helpers$1.getHoverColor;
  11693. point.$previousStyle = {
  11694. backgroundColor: model.backgroundColor,
  11695. borderColor: model.borderColor,
  11696. borderWidth: model.borderWidth,
  11697. radius: model.radius
  11698. };
  11699. model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  11700. model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));
  11701. model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);
  11702. model.radius = valueOrDefault$7(options.hoverRadius, options.radius);
  11703. }
  11704. });
  11705. core_defaults._set('scatter', {
  11706. hover: {
  11707. mode: 'single'
  11708. },
  11709. scales: {
  11710. xAxes: [{
  11711. id: 'x-axis-1', // need an ID so datasets can reference the scale
  11712. type: 'linear', // scatter should not use a category axis
  11713. position: 'bottom'
  11714. }],
  11715. yAxes: [{
  11716. id: 'y-axis-1',
  11717. type: 'linear',
  11718. position: 'left'
  11719. }]
  11720. },
  11721. tooltips: {
  11722. callbacks: {
  11723. title: function() {
  11724. return ''; // doesn't make sense for scatter since data are formatted as a point
  11725. },
  11726. label: function(item) {
  11727. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  11728. }
  11729. }
  11730. }
  11731. });
  11732. core_defaults._set('global', {
  11733. datasets: {
  11734. scatter: {
  11735. showLine: false
  11736. }
  11737. }
  11738. });
  11739. // Scatter charts use line controllers
  11740. var controller_scatter = controller_line;
  11741. // NOTE export a map in which the key represents the controller type, not
  11742. // the class, and so must be CamelCase in order to be correctly retrieved
  11743. // by the controller in core.controller.js (`controllers[meta.type]`).
  11744. var controllers = {
  11745. bar: controller_bar,
  11746. bubble: controller_bubble,
  11747. doughnut: controller_doughnut,
  11748. horizontalBar: controller_horizontalBar,
  11749. line: controller_line,
  11750. polarArea: controller_polarArea,
  11751. pie: controller_pie,
  11752. radar: controller_radar,
  11753. scatter: controller_scatter
  11754. };
  11755. /**
  11756. * Helper function to get relative position for an event
  11757. * @param {Event|IEvent} event - The event to get the position for
  11758. * @param {Chart} chart - The chart
  11759. * @returns {object} the event position
  11760. */
  11761. function getRelativePosition(e, chart) {
  11762. if (e.native) {
  11763. return {
  11764. x: e.x,
  11765. y: e.y
  11766. };
  11767. }
  11768. return helpers$1.getRelativePosition(e, chart);
  11769. }
  11770. /**
  11771. * Helper function to traverse all of the visible elements in the chart
  11772. * @param {Chart} chart - the chart
  11773. * @param {function} handler - the callback to execute for each visible item
  11774. */
  11775. function parseVisibleItems(chart, handler) {
  11776. var metasets = chart._getSortedVisibleDatasetMetas();
  11777. var metadata, i, j, ilen, jlen, element;
  11778. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  11779. metadata = metasets[i].data;
  11780. for (j = 0, jlen = metadata.length; j < jlen; ++j) {
  11781. element = metadata[j];
  11782. if (!element._view.skip) {
  11783. handler(element);
  11784. }
  11785. }
  11786. }
  11787. }
  11788. /**
  11789. * Helper function to get the items that intersect the event position
  11790. * @param {ChartElement[]} items - elements to filter
  11791. * @param {object} position - the point to be nearest to
  11792. * @return {ChartElement[]} the nearest items
  11793. */
  11794. function getIntersectItems(chart, position) {
  11795. var elements = [];
  11796. parseVisibleItems(chart, function(element) {
  11797. if (element.inRange(position.x, position.y)) {
  11798. elements.push(element);
  11799. }
  11800. });
  11801. return elements;
  11802. }
  11803. /**
  11804. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  11805. * @param {Chart} chart - the chart to look at elements from
  11806. * @param {object} position - the point to be nearest to
  11807. * @param {boolean} intersect - if true, only consider items that intersect the position
  11808. * @param {function} distanceMetric - function to provide the distance between points
  11809. * @return {ChartElement[]} the nearest items
  11810. */
  11811. function getNearestItems(chart, position, intersect, distanceMetric) {
  11812. var minDistance = Number.POSITIVE_INFINITY;
  11813. var nearestItems = [];
  11814. parseVisibleItems(chart, function(element) {
  11815. if (intersect && !element.inRange(position.x, position.y)) {
  11816. return;
  11817. }
  11818. var center = element.getCenterPoint();
  11819. var distance = distanceMetric(position, center);
  11820. if (distance < minDistance) {
  11821. nearestItems = [element];
  11822. minDistance = distance;
  11823. } else if (distance === minDistance) {
  11824. // Can have multiple items at the same distance in which case we sort by size
  11825. nearestItems.push(element);
  11826. }
  11827. });
  11828. return nearestItems;
  11829. }
  11830. /**
  11831. * Get a distance metric function for two points based on the
  11832. * axis mode setting
  11833. * @param {string} axis - the axis mode. x|y|xy
  11834. */
  11835. function getDistanceMetricForAxis(axis) {
  11836. var useX = axis.indexOf('x') !== -1;
  11837. var useY = axis.indexOf('y') !== -1;
  11838. return function(pt1, pt2) {
  11839. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  11840. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  11841. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  11842. };
  11843. }
  11844. function indexMode(chart, e, options) {
  11845. var position = getRelativePosition(e, chart);
  11846. // Default axis for index mode is 'x' to match old behaviour
  11847. options.axis = options.axis || 'x';
  11848. var distanceMetric = getDistanceMetricForAxis(options.axis);
  11849. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  11850. var elements = [];
  11851. if (!items.length) {
  11852. return [];
  11853. }
  11854. chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
  11855. var element = meta.data[items[0]._index];
  11856. // don't count items that are skipped (null data)
  11857. if (element && !element._view.skip) {
  11858. elements.push(element);
  11859. }
  11860. });
  11861. return elements;
  11862. }
  11863. /**
  11864. * @interface IInteractionOptions
  11865. */
  11866. /**
  11867. * If true, only consider items that intersect the point
  11868. * @name IInterfaceOptions#boolean
  11869. * @type Boolean
  11870. */
  11871. /**
  11872. * Contains interaction related functions
  11873. * @namespace Chart.Interaction
  11874. */
  11875. var core_interaction = {
  11876. // Helper function for different modes
  11877. modes: {
  11878. single: function(chart, e) {
  11879. var position = getRelativePosition(e, chart);
  11880. var elements = [];
  11881. parseVisibleItems(chart, function(element) {
  11882. if (element.inRange(position.x, position.y)) {
  11883. elements.push(element);
  11884. return elements;
  11885. }
  11886. });
  11887. return elements.slice(0, 1);
  11888. },
  11889. /**
  11890. * @function Chart.Interaction.modes.label
  11891. * @deprecated since version 2.4.0
  11892. * @todo remove at version 3
  11893. * @private
  11894. */
  11895. label: indexMode,
  11896. /**
  11897. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  11898. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  11899. * @function Chart.Interaction.modes.index
  11900. * @since v2.4.0
  11901. * @param {Chart} chart - the chart we are returning items from
  11902. * @param {Event} e - the event we are find things at
  11903. * @param {IInteractionOptions} options - options to use during interaction
  11904. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11905. */
  11906. index: indexMode,
  11907. /**
  11908. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  11909. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  11910. * @function Chart.Interaction.modes.dataset
  11911. * @param {Chart} chart - the chart we are returning items from
  11912. * @param {Event} e - the event we are find things at
  11913. * @param {IInteractionOptions} options - options to use during interaction
  11914. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11915. */
  11916. dataset: function(chart, e, options) {
  11917. var position = getRelativePosition(e, chart);
  11918. options.axis = options.axis || 'xy';
  11919. var distanceMetric = getDistanceMetricForAxis(options.axis);
  11920. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  11921. if (items.length > 0) {
  11922. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  11923. }
  11924. return items;
  11925. },
  11926. /**
  11927. * @function Chart.Interaction.modes.x-axis
  11928. * @deprecated since version 2.4.0. Use index mode and intersect == true
  11929. * @todo remove at version 3
  11930. * @private
  11931. */
  11932. 'x-axis': function(chart, e) {
  11933. return indexMode(chart, e, {intersect: false});
  11934. },
  11935. /**
  11936. * Point mode returns all elements that hit test based on the event position
  11937. * of the event
  11938. * @function Chart.Interaction.modes.intersect
  11939. * @param {Chart} chart - the chart we are returning items from
  11940. * @param {Event} e - the event we are find things at
  11941. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11942. */
  11943. point: function(chart, e) {
  11944. var position = getRelativePosition(e, chart);
  11945. return getIntersectItems(chart, position);
  11946. },
  11947. /**
  11948. * nearest mode returns the element closest to the point
  11949. * @function Chart.Interaction.modes.intersect
  11950. * @param {Chart} chart - the chart we are returning items from
  11951. * @param {Event} e - the event we are find things at
  11952. * @param {IInteractionOptions} options - options to use
  11953. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11954. */
  11955. nearest: function(chart, e, options) {
  11956. var position = getRelativePosition(e, chart);
  11957. options.axis = options.axis || 'xy';
  11958. var distanceMetric = getDistanceMetricForAxis(options.axis);
  11959. return getNearestItems(chart, position, options.intersect, distanceMetric);
  11960. },
  11961. /**
  11962. * x mode returns the elements that hit-test at the current x coordinate
  11963. * @function Chart.Interaction.modes.x
  11964. * @param {Chart} chart - the chart we are returning items from
  11965. * @param {Event} e - the event we are find things at
  11966. * @param {IInteractionOptions} options - options to use
  11967. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11968. */
  11969. x: function(chart, e, options) {
  11970. var position = getRelativePosition(e, chart);
  11971. var items = [];
  11972. var intersectsItem = false;
  11973. parseVisibleItems(chart, function(element) {
  11974. if (element.inXRange(position.x)) {
  11975. items.push(element);
  11976. }
  11977. if (element.inRange(position.x, position.y)) {
  11978. intersectsItem = true;
  11979. }
  11980. });
  11981. // If we want to trigger on an intersect and we don't have any items
  11982. // that intersect the position, return nothing
  11983. if (options.intersect && !intersectsItem) {
  11984. items = [];
  11985. }
  11986. return items;
  11987. },
  11988. /**
  11989. * y mode returns the elements that hit-test at the current y coordinate
  11990. * @function Chart.Interaction.modes.y
  11991. * @param {Chart} chart - the chart we are returning items from
  11992. * @param {Event} e - the event we are find things at
  11993. * @param {IInteractionOptions} options - options to use
  11994. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11995. */
  11996. y: function(chart, e, options) {
  11997. var position = getRelativePosition(e, chart);
  11998. var items = [];
  11999. var intersectsItem = false;
  12000. parseVisibleItems(chart, function(element) {
  12001. if (element.inYRange(position.y)) {
  12002. items.push(element);
  12003. }
  12004. if (element.inRange(position.x, position.y)) {
  12005. intersectsItem = true;
  12006. }
  12007. });
  12008. // If we want to trigger on an intersect and we don't have any items
  12009. // that intersect the position, return nothing
  12010. if (options.intersect && !intersectsItem) {
  12011. items = [];
  12012. }
  12013. return items;
  12014. }
  12015. }
  12016. };
  12017. var extend = helpers$1.extend;
  12018. function filterByPosition(array, position) {
  12019. return helpers$1.where(array, function(v) {
  12020. return v.pos === position;
  12021. });
  12022. }
  12023. function sortByWeight(array, reverse) {
  12024. return array.sort(function(a, b) {
  12025. var v0 = reverse ? b : a;
  12026. var v1 = reverse ? a : b;
  12027. return v0.weight === v1.weight ?
  12028. v0.index - v1.index :
  12029. v0.weight - v1.weight;
  12030. });
  12031. }
  12032. function wrapBoxes(boxes) {
  12033. var layoutBoxes = [];
  12034. var i, ilen, box;
  12035. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  12036. box = boxes[i];
  12037. layoutBoxes.push({
  12038. index: i,
  12039. box: box,
  12040. pos: box.position,
  12041. horizontal: box.isHorizontal(),
  12042. weight: box.weight
  12043. });
  12044. }
  12045. return layoutBoxes;
  12046. }
  12047. function setLayoutDims(layouts, params) {
  12048. var i, ilen, layout;
  12049. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  12050. layout = layouts[i];
  12051. // store width used instead of chartArea.w in fitBoxes
  12052. layout.width = layout.horizontal
  12053. ? layout.box.fullWidth && params.availableWidth
  12054. : params.vBoxMaxWidth;
  12055. // store height used instead of chartArea.h in fitBoxes
  12056. layout.height = layout.horizontal && params.hBoxMaxHeight;
  12057. }
  12058. }
  12059. function buildLayoutBoxes(boxes) {
  12060. var layoutBoxes = wrapBoxes(boxes);
  12061. var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  12062. var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  12063. var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  12064. var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  12065. return {
  12066. leftAndTop: left.concat(top),
  12067. rightAndBottom: right.concat(bottom),
  12068. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  12069. vertical: left.concat(right),
  12070. horizontal: top.concat(bottom)
  12071. };
  12072. }
  12073. function getCombinedMax(maxPadding, chartArea, a, b) {
  12074. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  12075. }
  12076. function updateDims(chartArea, params, layout) {
  12077. var box = layout.box;
  12078. var maxPadding = chartArea.maxPadding;
  12079. var newWidth, newHeight;
  12080. if (layout.size) {
  12081. // this layout was already counted for, lets first reduce old size
  12082. chartArea[layout.pos] -= layout.size;
  12083. }
  12084. layout.size = layout.horizontal ? box.height : box.width;
  12085. chartArea[layout.pos] += layout.size;
  12086. if (box.getPadding) {
  12087. var boxPadding = box.getPadding();
  12088. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  12089. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  12090. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  12091. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  12092. }
  12093. newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
  12094. newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
  12095. if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
  12096. chartArea.w = newWidth;
  12097. chartArea.h = newHeight;
  12098. // return true if chart area changed in layout's direction
  12099. var sizes = layout.horizontal ? [newWidth, chartArea.w] : [newHeight, chartArea.h];
  12100. return sizes[0] !== sizes[1] && (!isNaN(sizes[0]) || !isNaN(sizes[1]));
  12101. }
  12102. }
  12103. function handleMaxPadding(chartArea) {
  12104. var maxPadding = chartArea.maxPadding;
  12105. function updatePos(pos) {
  12106. var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  12107. chartArea[pos] += change;
  12108. return change;
  12109. }
  12110. chartArea.y += updatePos('top');
  12111. chartArea.x += updatePos('left');
  12112. updatePos('right');
  12113. updatePos('bottom');
  12114. }
  12115. function getMargins(horizontal, chartArea) {
  12116. var maxPadding = chartArea.maxPadding;
  12117. function marginForPositions(positions) {
  12118. var margin = {left: 0, top: 0, right: 0, bottom: 0};
  12119. positions.forEach(function(pos) {
  12120. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  12121. });
  12122. return margin;
  12123. }
  12124. return horizontal
  12125. ? marginForPositions(['left', 'right'])
  12126. : marginForPositions(['top', 'bottom']);
  12127. }
  12128. function fitBoxes(boxes, chartArea, params) {
  12129. var refitBoxes = [];
  12130. var i, ilen, layout, box, refit, changed;
  12131. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  12132. layout = boxes[i];
  12133. box = layout.box;
  12134. box.update(
  12135. layout.width || chartArea.w,
  12136. layout.height || chartArea.h,
  12137. getMargins(layout.horizontal, chartArea)
  12138. );
  12139. if (updateDims(chartArea, params, layout)) {
  12140. changed = true;
  12141. if (refitBoxes.length) {
  12142. // Dimensions changed and there were non full width boxes before this
  12143. // -> we have to refit those
  12144. refit = true;
  12145. }
  12146. }
  12147. if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case
  12148. refitBoxes.push(layout);
  12149. }
  12150. }
  12151. return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;
  12152. }
  12153. function placeBoxes(boxes, chartArea, params) {
  12154. var userPadding = params.padding;
  12155. var x = chartArea.x;
  12156. var y = chartArea.y;
  12157. var i, ilen, layout, box;
  12158. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  12159. layout = boxes[i];
  12160. box = layout.box;
  12161. if (layout.horizontal) {
  12162. box.left = box.fullWidth ? userPadding.left : chartArea.left;
  12163. box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  12164. box.top = y;
  12165. box.bottom = y + box.height;
  12166. box.width = box.right - box.left;
  12167. y = box.bottom;
  12168. } else {
  12169. box.left = x;
  12170. box.right = x + box.width;
  12171. box.top = chartArea.top;
  12172. box.bottom = chartArea.top + chartArea.h;
  12173. box.height = box.bottom - box.top;
  12174. x = box.right;
  12175. }
  12176. }
  12177. chartArea.x = x;
  12178. chartArea.y = y;
  12179. }
  12180. core_defaults._set('global', {
  12181. layout: {
  12182. padding: {
  12183. top: 0,
  12184. right: 0,
  12185. bottom: 0,
  12186. left: 0
  12187. }
  12188. }
  12189. });
  12190. /**
  12191. * @interface ILayoutItem
  12192. * @prop {string} position - The position of the item in the chart layout. Possible values are
  12193. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  12194. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  12195. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  12196. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  12197. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  12198. * @prop {function} getPadding - Returns an object with padding on the edges
  12199. * @prop {number} width - Width of item. Must be valid after update()
  12200. * @prop {number} height - Height of item. Must be valid after update()
  12201. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  12202. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  12203. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  12204. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  12205. */
  12206. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  12207. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  12208. // It is this service's responsibility of carrying out that layout.
  12209. var core_layouts = {
  12210. defaults: {},
  12211. /**
  12212. * Register a box to a chart.
  12213. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  12214. * @param {Chart} chart - the chart to use
  12215. * @param {ILayoutItem} item - the item to add to be layed out
  12216. */
  12217. addBox: function(chart, item) {
  12218. if (!chart.boxes) {
  12219. chart.boxes = [];
  12220. }
  12221. // initialize item with default values
  12222. item.fullWidth = item.fullWidth || false;
  12223. item.position = item.position || 'top';
  12224. item.weight = item.weight || 0;
  12225. item._layers = item._layers || function() {
  12226. return [{
  12227. z: 0,
  12228. draw: function() {
  12229. item.draw.apply(item, arguments);
  12230. }
  12231. }];
  12232. };
  12233. chart.boxes.push(item);
  12234. },
  12235. /**
  12236. * Remove a layoutItem from a chart
  12237. * @param {Chart} chart - the chart to remove the box from
  12238. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  12239. */
  12240. removeBox: function(chart, layoutItem) {
  12241. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  12242. if (index !== -1) {
  12243. chart.boxes.splice(index, 1);
  12244. }
  12245. },
  12246. /**
  12247. * Sets (or updates) options on the given `item`.
  12248. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  12249. * @param {ILayoutItem} item - the item to configure with the given options
  12250. * @param {object} options - the new item options.
  12251. */
  12252. configure: function(chart, item, options) {
  12253. var props = ['fullWidth', 'position', 'weight'];
  12254. var ilen = props.length;
  12255. var i = 0;
  12256. var prop;
  12257. for (; i < ilen; ++i) {
  12258. prop = props[i];
  12259. if (options.hasOwnProperty(prop)) {
  12260. item[prop] = options[prop];
  12261. }
  12262. }
  12263. },
  12264. /**
  12265. * Fits boxes of the given chart into the given size by having each box measure itself
  12266. * then running a fitting algorithm
  12267. * @param {Chart} chart - the chart
  12268. * @param {number} width - the width to fit into
  12269. * @param {number} height - the height to fit into
  12270. */
  12271. update: function(chart, width, height) {
  12272. if (!chart) {
  12273. return;
  12274. }
  12275. var layoutOptions = chart.options.layout || {};
  12276. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  12277. var availableWidth = width - padding.width;
  12278. var availableHeight = height - padding.height;
  12279. var boxes = buildLayoutBoxes(chart.boxes);
  12280. var verticalBoxes = boxes.vertical;
  12281. var horizontalBoxes = boxes.horizontal;
  12282. // Essentially we now have any number of boxes on each of the 4 sides.
  12283. // Our canvas looks like the following.
  12284. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  12285. // B1 is the bottom axis
  12286. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  12287. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  12288. // an error will be thrown.
  12289. //
  12290. // |----------------------------------------------------|
  12291. // | T1 (Full Width) |
  12292. // |----------------------------------------------------|
  12293. // | | | T2 | |
  12294. // | |----|-------------------------------------|----|
  12295. // | | | C1 | | C2 | |
  12296. // | | |----| |----| |
  12297. // | | | | |
  12298. // | L1 | L2 | ChartArea (C0) | R1 |
  12299. // | | | | |
  12300. // | | |----| |----| |
  12301. // | | | C3 | | C4 | |
  12302. // | |----|-------------------------------------|----|
  12303. // | | | B1 | |
  12304. // |----------------------------------------------------|
  12305. // | B2 (Full Width) |
  12306. // |----------------------------------------------------|
  12307. //
  12308. var params = Object.freeze({
  12309. outerWidth: width,
  12310. outerHeight: height,
  12311. padding: padding,
  12312. availableWidth: availableWidth,
  12313. vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
  12314. hBoxMaxHeight: availableHeight / 2
  12315. });
  12316. var chartArea = extend({
  12317. maxPadding: extend({}, padding),
  12318. w: availableWidth,
  12319. h: availableHeight,
  12320. x: padding.left,
  12321. y: padding.top
  12322. }, padding);
  12323. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  12324. // First fit vertical boxes
  12325. fitBoxes(verticalBoxes, chartArea, params);
  12326. // Then fit horizontal boxes
  12327. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  12328. // if the area changed, re-fit vertical boxes
  12329. fitBoxes(verticalBoxes, chartArea, params);
  12330. }
  12331. handleMaxPadding(chartArea);
  12332. // Finally place the boxes to correct coordinates
  12333. placeBoxes(boxes.leftAndTop, chartArea, params);
  12334. // Move to opposite side of chart
  12335. chartArea.x += chartArea.w;
  12336. chartArea.y += chartArea.h;
  12337. placeBoxes(boxes.rightAndBottom, chartArea, params);
  12338. chart.chartArea = {
  12339. left: chartArea.left,
  12340. top: chartArea.top,
  12341. right: chartArea.left + chartArea.w,
  12342. bottom: chartArea.top + chartArea.h
  12343. };
  12344. // Finally update boxes in chartArea (radial scale for example)
  12345. helpers$1.each(boxes.chartArea, function(layout) {
  12346. var box = layout.box;
  12347. extend(box, chart.chartArea);
  12348. box.update(chartArea.w, chartArea.h);
  12349. });
  12350. }
  12351. };
  12352. /**
  12353. * Platform fallback implementation (minimal).
  12354. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  12355. */
  12356. var platform_basic = {
  12357. acquireContext: function(item) {
  12358. if (item && item.canvas) {
  12359. // Support for any object associated to a canvas (including a context2d)
  12360. item = item.canvas;
  12361. }
  12362. return item && item.getContext('2d') || null;
  12363. }
  12364. };
  12365. 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";
  12366. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  12367. __proto__: null,
  12368. 'default': platform_dom
  12369. });
  12370. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  12371. var EXPANDO_KEY = '$chartjs';
  12372. var CSS_PREFIX = 'chartjs-';
  12373. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  12374. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  12375. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  12376. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  12377. /**
  12378. * DOM event types -> Chart.js event types.
  12379. * Note: only events with different types are mapped.
  12380. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  12381. */
  12382. var EVENT_TYPES = {
  12383. touchstart: 'mousedown',
  12384. touchmove: 'mousemove',
  12385. touchend: 'mouseup',
  12386. pointerenter: 'mouseenter',
  12387. pointerdown: 'mousedown',
  12388. pointermove: 'mousemove',
  12389. pointerup: 'mouseup',
  12390. pointerleave: 'mouseout',
  12391. pointerout: 'mouseout'
  12392. };
  12393. /**
  12394. * The "used" size is the final value of a dimension property after all calculations have
  12395. * been performed. This method uses the computed style of `element` but returns undefined
  12396. * if the computed style is not expressed in pixels. That can happen in some cases where
  12397. * `element` has a size relative to its parent and this last one is not yet displayed,
  12398. * for example because of `display: none` on a parent node.
  12399. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  12400. * @returns {number} Size in pixels or undefined if unknown.
  12401. */
  12402. function readUsedSize(element, property) {
  12403. var value = helpers$1.getStyle(element, property);
  12404. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  12405. return matches ? Number(matches[1]) : undefined;
  12406. }
  12407. /**
  12408. * Initializes the canvas style and render size without modifying the canvas display size,
  12409. * since responsiveness is handled by the controller.resize() method. The config is used
  12410. * to determine the aspect ratio to apply in case no explicit height has been specified.
  12411. */
  12412. function initCanvas(canvas, config) {
  12413. var style = canvas.style;
  12414. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  12415. // returns null or '' if no explicit value has been set to the canvas attribute.
  12416. var renderHeight = canvas.getAttribute('height');
  12417. var renderWidth = canvas.getAttribute('width');
  12418. // Chart.js modifies some canvas values that we want to restore on destroy
  12419. canvas[EXPANDO_KEY] = {
  12420. initial: {
  12421. height: renderHeight,
  12422. width: renderWidth,
  12423. style: {
  12424. display: style.display,
  12425. height: style.height,
  12426. width: style.width
  12427. }
  12428. }
  12429. };
  12430. // Force canvas to display as block to avoid extra space caused by inline
  12431. // elements, which would interfere with the responsive resize process.
  12432. // https://github.com/chartjs/Chart.js/issues/2538
  12433. style.display = style.display || 'block';
  12434. if (renderWidth === null || renderWidth === '') {
  12435. var displayWidth = readUsedSize(canvas, 'width');
  12436. if (displayWidth !== undefined) {
  12437. canvas.width = displayWidth;
  12438. }
  12439. }
  12440. if (renderHeight === null || renderHeight === '') {
  12441. if (canvas.style.height === '') {
  12442. // If no explicit render height and style height, let's apply the aspect ratio,
  12443. // which one can be specified by the user but also by charts as default option
  12444. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  12445. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  12446. } else {
  12447. var displayHeight = readUsedSize(canvas, 'height');
  12448. if (displayWidth !== undefined) {
  12449. canvas.height = displayHeight;
  12450. }
  12451. }
  12452. }
  12453. return canvas;
  12454. }
  12455. /**
  12456. * Detects support for options object argument in addEventListener.
  12457. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  12458. * @private
  12459. */
  12460. var supportsEventListenerOptions = (function() {
  12461. var supports = false;
  12462. try {
  12463. var options = Object.defineProperty({}, 'passive', {
  12464. // eslint-disable-next-line getter-return
  12465. get: function() {
  12466. supports = true;
  12467. }
  12468. });
  12469. window.addEventListener('e', null, options);
  12470. } catch (e) {
  12471. // continue regardless of error
  12472. }
  12473. return supports;
  12474. }());
  12475. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  12476. // https://github.com/chartjs/Chart.js/issues/4287
  12477. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  12478. function addListener(node, type, listener) {
  12479. node.addEventListener(type, listener, eventListenerOptions);
  12480. }
  12481. function removeListener(node, type, listener) {
  12482. node.removeEventListener(type, listener, eventListenerOptions);
  12483. }
  12484. function createEvent(type, chart, x, y, nativeEvent) {
  12485. return {
  12486. type: type,
  12487. chart: chart,
  12488. native: nativeEvent || null,
  12489. x: x !== undefined ? x : null,
  12490. y: y !== undefined ? y : null,
  12491. };
  12492. }
  12493. function fromNativeEvent(event, chart) {
  12494. var type = EVENT_TYPES[event.type] || event.type;
  12495. var pos = helpers$1.getRelativePosition(event, chart);
  12496. return createEvent(type, chart, pos.x, pos.y, event);
  12497. }
  12498. function throttled(fn, thisArg) {
  12499. var ticking = false;
  12500. var args = [];
  12501. return function() {
  12502. args = Array.prototype.slice.call(arguments);
  12503. thisArg = thisArg || this;
  12504. if (!ticking) {
  12505. ticking = true;
  12506. helpers$1.requestAnimFrame.call(window, function() {
  12507. ticking = false;
  12508. fn.apply(thisArg, args);
  12509. });
  12510. }
  12511. };
  12512. }
  12513. function createDiv(cls) {
  12514. var el = document.createElement('div');
  12515. el.className = cls || '';
  12516. return el;
  12517. }
  12518. // Implementation based on https://github.com/marcj/css-element-queries
  12519. function createResizer(handler) {
  12520. var maxSize = 1000000;
  12521. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  12522. // https://github.com/chartjs/Chart.js/issues/5902
  12523. var resizer = createDiv(CSS_SIZE_MONITOR);
  12524. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  12525. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  12526. expand.appendChild(createDiv());
  12527. shrink.appendChild(createDiv());
  12528. resizer.appendChild(expand);
  12529. resizer.appendChild(shrink);
  12530. resizer._reset = function() {
  12531. expand.scrollLeft = maxSize;
  12532. expand.scrollTop = maxSize;
  12533. shrink.scrollLeft = maxSize;
  12534. shrink.scrollTop = maxSize;
  12535. };
  12536. var onScroll = function() {
  12537. resizer._reset();
  12538. handler();
  12539. };
  12540. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  12541. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  12542. return resizer;
  12543. }
  12544. // https://davidwalsh.name/detect-node-insertion
  12545. function watchForRender(node, handler) {
  12546. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  12547. var proxy = expando.renderProxy = function(e) {
  12548. if (e.animationName === CSS_RENDER_ANIMATION) {
  12549. handler();
  12550. }
  12551. };
  12552. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  12553. addListener(node, type, proxy);
  12554. });
  12555. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  12556. // is removed then added back immediately (same animation frame?). Accessing the
  12557. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  12558. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  12559. // https://github.com/chartjs/Chart.js/issues/4737
  12560. expando.reflow = !!node.offsetParent;
  12561. node.classList.add(CSS_RENDER_MONITOR);
  12562. }
  12563. function unwatchForRender(node) {
  12564. var expando = node[EXPANDO_KEY] || {};
  12565. var proxy = expando.renderProxy;
  12566. if (proxy) {
  12567. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  12568. removeListener(node, type, proxy);
  12569. });
  12570. delete expando.renderProxy;
  12571. }
  12572. node.classList.remove(CSS_RENDER_MONITOR);
  12573. }
  12574. function addResizeListener(node, listener, chart) {
  12575. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  12576. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  12577. var resizer = expando.resizer = createResizer(throttled(function() {
  12578. if (expando.resizer) {
  12579. var container = chart.options.maintainAspectRatio && node.parentNode;
  12580. var w = container ? container.clientWidth : 0;
  12581. listener(createEvent('resize', chart));
  12582. if (container && container.clientWidth < w && chart.canvas) {
  12583. // If the container size shrank during chart resize, let's assume
  12584. // scrollbar appeared. So we resize again with the scrollbar visible -
  12585. // effectively making chart smaller and the scrollbar hidden again.
  12586. // Because we are inside `throttled`, and currently `ticking`, scroll
  12587. // events are ignored during this whole 2 resize process.
  12588. // If we assumed wrong and something else happened, we are resizing
  12589. // twice in a frame (potential performance issue)
  12590. listener(createEvent('resize', chart));
  12591. }
  12592. }
  12593. }));
  12594. // The resizer needs to be attached to the node parent, so we first need to be
  12595. // sure that `node` is attached to the DOM before injecting the resizer element.
  12596. watchForRender(node, function() {
  12597. if (expando.resizer) {
  12598. var container = node.parentNode;
  12599. if (container && container !== resizer.parentNode) {
  12600. container.insertBefore(resizer, container.firstChild);
  12601. }
  12602. // The container size might have changed, let's reset the resizer state.
  12603. resizer._reset();
  12604. }
  12605. });
  12606. }
  12607. function removeResizeListener(node) {
  12608. var expando = node[EXPANDO_KEY] || {};
  12609. var resizer = expando.resizer;
  12610. delete expando.resizer;
  12611. unwatchForRender(node);
  12612. if (resizer && resizer.parentNode) {
  12613. resizer.parentNode.removeChild(resizer);
  12614. }
  12615. }
  12616. /**
  12617. * Injects CSS styles inline if the styles are not already present.
  12618. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.
  12619. * @param {string} css - the CSS to be injected.
  12620. */
  12621. function injectCSS(rootNode, css) {
  12622. // https://stackoverflow.com/q/3922139
  12623. var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});
  12624. if (!expando.containsStyles) {
  12625. expando.containsStyles = true;
  12626. css = '/* Chart.js */\n' + css;
  12627. var style = document.createElement('style');
  12628. style.setAttribute('type', 'text/css');
  12629. style.appendChild(document.createTextNode(css));
  12630. rootNode.appendChild(style);
  12631. }
  12632. }
  12633. var platform_dom$2 = {
  12634. /**
  12635. * When `true`, prevents the automatic injection of the stylesheet required to
  12636. * correctly detect when the chart is added to the DOM and then resized. This
  12637. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  12638. * to be manually imported to make this library compatible with any CSP.
  12639. * See https://github.com/chartjs/Chart.js/issues/5208
  12640. */
  12641. disableCSSInjection: false,
  12642. /**
  12643. * This property holds whether this platform is enabled for the current environment.
  12644. * Currently used by platform.js to select the proper implementation.
  12645. * @private
  12646. */
  12647. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  12648. /**
  12649. * Initializes resources that depend on platform options.
  12650. * @param {HTMLCanvasElement} canvas - The Canvas element.
  12651. * @private
  12652. */
  12653. _ensureLoaded: function(canvas) {
  12654. if (!this.disableCSSInjection) {
  12655. // If the canvas is in a shadow DOM, then the styles must also be inserted
  12656. // into the same shadow DOM.
  12657. // https://github.com/chartjs/Chart.js/issues/5763
  12658. var root = canvas.getRootNode ? canvas.getRootNode() : document;
  12659. var targetNode = root.host ? root : document.head;
  12660. injectCSS(targetNode, stylesheet);
  12661. }
  12662. },
  12663. acquireContext: function(item, config) {
  12664. if (typeof item === 'string') {
  12665. item = document.getElementById(item);
  12666. } else if (item.length) {
  12667. // Support for array based queries (such as jQuery)
  12668. item = item[0];
  12669. }
  12670. if (item && item.canvas) {
  12671. // Support for any object associated to a canvas (including a context2d)
  12672. item = item.canvas;
  12673. }
  12674. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  12675. // method, for example: https://github.com/kkapsner/CanvasBlocker
  12676. // https://github.com/chartjs/Chart.js/issues/2807
  12677. var context = item && item.getContext && item.getContext('2d');
  12678. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  12679. // inside an iframe or when running in a protected environment. We could guess the
  12680. // types from their toString() value but let's keep things flexible and assume it's
  12681. // a sufficient condition if the item has a context2D which has item as `canvas`.
  12682. // https://github.com/chartjs/Chart.js/issues/3887
  12683. // https://github.com/chartjs/Chart.js/issues/4102
  12684. // https://github.com/chartjs/Chart.js/issues/4152
  12685. if (context && context.canvas === item) {
  12686. // Load platform resources on first chart creation, to make it possible to
  12687. // import the library before setting platform options.
  12688. this._ensureLoaded(item);
  12689. initCanvas(item, config);
  12690. return context;
  12691. }
  12692. return null;
  12693. },
  12694. releaseContext: function(context) {
  12695. var canvas = context.canvas;
  12696. if (!canvas[EXPANDO_KEY]) {
  12697. return;
  12698. }
  12699. var initial = canvas[EXPANDO_KEY].initial;
  12700. ['height', 'width'].forEach(function(prop) {
  12701. var value = initial[prop];
  12702. if (helpers$1.isNullOrUndef(value)) {
  12703. canvas.removeAttribute(prop);
  12704. } else {
  12705. canvas.setAttribute(prop, value);
  12706. }
  12707. });
  12708. helpers$1.each(initial.style || {}, function(value, key) {
  12709. canvas.style[key] = value;
  12710. });
  12711. // The canvas render size might have been changed (and thus the state stack discarded),
  12712. // we can't use save() and restore() to restore the initial state. So make sure that at
  12713. // least the canvas context is reset to the default state by setting the canvas width.
  12714. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  12715. // eslint-disable-next-line no-self-assign
  12716. canvas.width = canvas.width;
  12717. delete canvas[EXPANDO_KEY];
  12718. },
  12719. addEventListener: function(chart, type, listener) {
  12720. var canvas = chart.canvas;
  12721. if (type === 'resize') {
  12722. // Note: the resize event is not supported on all browsers.
  12723. addResizeListener(canvas, listener, chart);
  12724. return;
  12725. }
  12726. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  12727. var proxies = expando.proxies || (expando.proxies = {});
  12728. var proxy = proxies[chart.id + '_' + type] = function(event) {
  12729. listener(fromNativeEvent(event, chart));
  12730. };
  12731. addListener(canvas, type, proxy);
  12732. },
  12733. removeEventListener: function(chart, type, listener) {
  12734. var canvas = chart.canvas;
  12735. if (type === 'resize') {
  12736. // Note: the resize event is not supported on all browsers.
  12737. removeResizeListener(canvas);
  12738. return;
  12739. }
  12740. var expando = listener[EXPANDO_KEY] || {};
  12741. var proxies = expando.proxies || {};
  12742. var proxy = proxies[chart.id + '_' + type];
  12743. if (!proxy) {
  12744. return;
  12745. }
  12746. removeListener(canvas, type, proxy);
  12747. }
  12748. };
  12749. // DEPRECATIONS
  12750. /**
  12751. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  12752. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  12753. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  12754. * @function Chart.helpers.addEvent
  12755. * @deprecated since version 2.7.0
  12756. * @todo remove at version 3
  12757. * @private
  12758. */
  12759. helpers$1.addEvent = addListener;
  12760. /**
  12761. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  12762. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  12763. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  12764. * @function Chart.helpers.removeEvent
  12765. * @deprecated since version 2.7.0
  12766. * @todo remove at version 3
  12767. * @private
  12768. */
  12769. helpers$1.removeEvent = removeListener;
  12770. // @TODO Make possible to select another platform at build time.
  12771. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  12772. /**
  12773. * @namespace Chart.platform
  12774. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  12775. * @since 2.4.0
  12776. */
  12777. var platform = helpers$1.extend({
  12778. /**
  12779. * @since 2.7.0
  12780. */
  12781. initialize: function() {},
  12782. /**
  12783. * Called at chart construction time, returns a context2d instance implementing
  12784. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  12785. * @param {*} item - The native item from which to acquire context (platform specific)
  12786. * @param {object} options - The chart options
  12787. * @returns {CanvasRenderingContext2D} context2d instance
  12788. */
  12789. acquireContext: function() {},
  12790. /**
  12791. * Called at chart destruction time, releases any resources associated to the context
  12792. * previously returned by the acquireContext() method.
  12793. * @param {CanvasRenderingContext2D} context - The context2d instance
  12794. * @returns {boolean} true if the method succeeded, else false
  12795. */
  12796. releaseContext: function() {},
  12797. /**
  12798. * Registers the specified listener on the given chart.
  12799. * @param {Chart} chart - Chart from which to listen for event
  12800. * @param {string} type - The ({@link IEvent}) type to listen for
  12801. * @param {function} listener - Receives a notification (an object that implements
  12802. * the {@link IEvent} interface) when an event of the specified type occurs.
  12803. */
  12804. addEventListener: function() {},
  12805. /**
  12806. * Removes the specified listener previously registered with addEventListener.
  12807. * @param {Chart} chart - Chart from which to remove the listener
  12808. * @param {string} type - The ({@link IEvent}) type to remove
  12809. * @param {function} listener - The listener function to remove from the event target.
  12810. */
  12811. removeEventListener: function() {}
  12812. }, implementation);
  12813. core_defaults._set('global', {
  12814. plugins: {}
  12815. });
  12816. /**
  12817. * The plugin service singleton
  12818. * @namespace Chart.plugins
  12819. * @since 2.1.0
  12820. */
  12821. var core_plugins = {
  12822. /**
  12823. * Globally registered plugins.
  12824. * @private
  12825. */
  12826. _plugins: [],
  12827. /**
  12828. * This identifier is used to invalidate the descriptors cache attached to each chart
  12829. * when a global plugin is registered or unregistered. In this case, the cache ID is
  12830. * incremented and descriptors are regenerated during following API calls.
  12831. * @private
  12832. */
  12833. _cacheId: 0,
  12834. /**
  12835. * Registers the given plugin(s) if not already registered.
  12836. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  12837. */
  12838. register: function(plugins) {
  12839. var p = this._plugins;
  12840. ([]).concat(plugins).forEach(function(plugin) {
  12841. if (p.indexOf(plugin) === -1) {
  12842. p.push(plugin);
  12843. }
  12844. });
  12845. this._cacheId++;
  12846. },
  12847. /**
  12848. * Unregisters the given plugin(s) only if registered.
  12849. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  12850. */
  12851. unregister: function(plugins) {
  12852. var p = this._plugins;
  12853. ([]).concat(plugins).forEach(function(plugin) {
  12854. var idx = p.indexOf(plugin);
  12855. if (idx !== -1) {
  12856. p.splice(idx, 1);
  12857. }
  12858. });
  12859. this._cacheId++;
  12860. },
  12861. /**
  12862. * Remove all registered plugins.
  12863. * @since 2.1.5
  12864. */
  12865. clear: function() {
  12866. this._plugins = [];
  12867. this._cacheId++;
  12868. },
  12869. /**
  12870. * Returns the number of registered plugins?
  12871. * @returns {number}
  12872. * @since 2.1.5
  12873. */
  12874. count: function() {
  12875. return this._plugins.length;
  12876. },
  12877. /**
  12878. * Returns all registered plugin instances.
  12879. * @returns {IPlugin[]} array of plugin objects.
  12880. * @since 2.1.5
  12881. */
  12882. getAll: function() {
  12883. return this._plugins;
  12884. },
  12885. /**
  12886. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  12887. * This method immediately returns as soon as a plugin explicitly returns false. The
  12888. * returned value can be used, for instance, to interrupt the current action.
  12889. * @param {Chart} chart - The chart instance for which plugins should be called.
  12890. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  12891. * @param {Array} [args] - Extra arguments to apply to the hook call.
  12892. * @returns {boolean} false if any of the plugins return false, else returns true.
  12893. */
  12894. notify: function(chart, hook, args) {
  12895. var descriptors = this.descriptors(chart);
  12896. var ilen = descriptors.length;
  12897. var i, descriptor, plugin, params, method;
  12898. for (i = 0; i < ilen; ++i) {
  12899. descriptor = descriptors[i];
  12900. plugin = descriptor.plugin;
  12901. method = plugin[hook];
  12902. if (typeof method === 'function') {
  12903. params = [chart].concat(args || []);
  12904. params.push(descriptor.options);
  12905. if (method.apply(plugin, params) === false) {
  12906. return false;
  12907. }
  12908. }
  12909. }
  12910. return true;
  12911. },
  12912. /**
  12913. * Returns descriptors of enabled plugins for the given chart.
  12914. * @returns {object[]} [{ plugin, options }]
  12915. * @private
  12916. */
  12917. descriptors: function(chart) {
  12918. var cache = chart.$plugins || (chart.$plugins = {});
  12919. if (cache.id === this._cacheId) {
  12920. return cache.descriptors;
  12921. }
  12922. var plugins = [];
  12923. var descriptors = [];
  12924. var config = (chart && chart.config) || {};
  12925. var options = (config.options && config.options.plugins) || {};
  12926. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  12927. var idx = plugins.indexOf(plugin);
  12928. if (idx !== -1) {
  12929. return;
  12930. }
  12931. var id = plugin.id;
  12932. var opts = options[id];
  12933. if (opts === false) {
  12934. return;
  12935. }
  12936. if (opts === true) {
  12937. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  12938. }
  12939. plugins.push(plugin);
  12940. descriptors.push({
  12941. plugin: plugin,
  12942. options: opts || {}
  12943. });
  12944. });
  12945. cache.descriptors = descriptors;
  12946. cache.id = this._cacheId;
  12947. return descriptors;
  12948. },
  12949. /**
  12950. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  12951. * but in some cases, this reference can be changed by the user when updating options.
  12952. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  12953. * @private
  12954. */
  12955. _invalidate: function(chart) {
  12956. delete chart.$plugins;
  12957. }
  12958. };
  12959. var core_scaleService = {
  12960. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  12961. // use the new chart options to grab the correct scale
  12962. constructors: {},
  12963. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  12964. // old browsers
  12965. // Scale config defaults
  12966. defaults: {},
  12967. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  12968. this.constructors[type] = scaleConstructor;
  12969. this.defaults[type] = helpers$1.clone(scaleDefaults);
  12970. },
  12971. getScaleConstructor: function(type) {
  12972. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  12973. },
  12974. getScaleDefaults: function(type) {
  12975. // Return the scale defaults merged with the global settings so that we always use the latest ones
  12976. return this.defaults.hasOwnProperty(type) ? helpers$1.merge(Object.create(null), [core_defaults.scale, this.defaults[type]]) : {};
  12977. },
  12978. updateScaleDefaults: function(type, additions) {
  12979. var me = this;
  12980. if (me.defaults.hasOwnProperty(type)) {
  12981. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  12982. }
  12983. },
  12984. addScalesToLayout: function(chart) {
  12985. // Adds each scale to the chart.boxes array to be sized accordingly
  12986. helpers$1.each(chart.scales, function(scale) {
  12987. // Set ILayoutItem parameters for backwards compatibility
  12988. scale.fullWidth = scale.options.fullWidth;
  12989. scale.position = scale.options.position;
  12990. scale.weight = scale.options.weight;
  12991. core_layouts.addBox(chart, scale);
  12992. });
  12993. }
  12994. };
  12995. var valueOrDefault$8 = helpers$1.valueOrDefault;
  12996. var getRtlHelper = helpers$1.rtl.getRtlAdapter;
  12997. core_defaults._set('global', {
  12998. tooltips: {
  12999. enabled: true,
  13000. custom: null,
  13001. mode: 'nearest',
  13002. position: 'average',
  13003. intersect: true,
  13004. backgroundColor: 'rgba(0,0,0,0.8)',
  13005. titleFontStyle: 'bold',
  13006. titleSpacing: 2,
  13007. titleMarginBottom: 6,
  13008. titleFontColor: '#fff',
  13009. titleAlign: 'left',
  13010. bodySpacing: 2,
  13011. bodyFontColor: '#fff',
  13012. bodyAlign: 'left',
  13013. footerFontStyle: 'bold',
  13014. footerSpacing: 2,
  13015. footerMarginTop: 6,
  13016. footerFontColor: '#fff',
  13017. footerAlign: 'left',
  13018. yPadding: 6,
  13019. xPadding: 6,
  13020. caretPadding: 2,
  13021. caretSize: 5,
  13022. cornerRadius: 6,
  13023. multiKeyBackground: '#fff',
  13024. displayColors: true,
  13025. borderColor: 'rgba(0,0,0,0)',
  13026. borderWidth: 0,
  13027. callbacks: {
  13028. // Args are: (tooltipItems, data)
  13029. beforeTitle: helpers$1.noop,
  13030. title: function(tooltipItems, data) {
  13031. var title = '';
  13032. var labels = data.labels;
  13033. var labelCount = labels ? labels.length : 0;
  13034. if (tooltipItems.length > 0) {
  13035. var item = tooltipItems[0];
  13036. if (item.label) {
  13037. title = item.label;
  13038. } else if (item.xLabel) {
  13039. title = item.xLabel;
  13040. } else if (labelCount > 0 && item.index < labelCount) {
  13041. title = labels[item.index];
  13042. }
  13043. }
  13044. return title;
  13045. },
  13046. afterTitle: helpers$1.noop,
  13047. // Args are: (tooltipItems, data)
  13048. beforeBody: helpers$1.noop,
  13049. // Args are: (tooltipItem, data)
  13050. beforeLabel: helpers$1.noop,
  13051. label: function(tooltipItem, data) {
  13052. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  13053. if (label) {
  13054. label += ': ';
  13055. }
  13056. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  13057. label += tooltipItem.value;
  13058. } else {
  13059. label += tooltipItem.yLabel;
  13060. }
  13061. return label;
  13062. },
  13063. labelColor: function(tooltipItem, chart) {
  13064. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  13065. var activeElement = meta.data[tooltipItem.index];
  13066. var view = activeElement._view;
  13067. return {
  13068. borderColor: view.borderColor,
  13069. backgroundColor: view.backgroundColor
  13070. };
  13071. },
  13072. labelTextColor: function() {
  13073. return this._options.bodyFontColor;
  13074. },
  13075. afterLabel: helpers$1.noop,
  13076. // Args are: (tooltipItems, data)
  13077. afterBody: helpers$1.noop,
  13078. // Args are: (tooltipItems, data)
  13079. beforeFooter: helpers$1.noop,
  13080. footer: helpers$1.noop,
  13081. afterFooter: helpers$1.noop
  13082. }
  13083. }
  13084. });
  13085. var positioners = {
  13086. /**
  13087. * Average mode places the tooltip at the average position of the elements shown
  13088. * @function Chart.Tooltip.positioners.average
  13089. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  13090. * @returns {object} tooltip position
  13091. */
  13092. average: function(elements) {
  13093. if (!elements.length) {
  13094. return false;
  13095. }
  13096. var i, len;
  13097. var x = 0;
  13098. var y = 0;
  13099. var count = 0;
  13100. for (i = 0, len = elements.length; i < len; ++i) {
  13101. var el = elements[i];
  13102. if (el && el.hasValue()) {
  13103. var pos = el.tooltipPosition();
  13104. x += pos.x;
  13105. y += pos.y;
  13106. ++count;
  13107. }
  13108. }
  13109. return {
  13110. x: x / count,
  13111. y: y / count
  13112. };
  13113. },
  13114. /**
  13115. * Gets the tooltip position nearest of the item nearest to the event position
  13116. * @function Chart.Tooltip.positioners.nearest
  13117. * @param elements {Chart.Element[]} the tooltip elements
  13118. * @param eventPosition {object} the position of the event in canvas coordinates
  13119. * @returns {object} the tooltip position
  13120. */
  13121. nearest: function(elements, eventPosition) {
  13122. var x = eventPosition.x;
  13123. var y = eventPosition.y;
  13124. var minDistance = Number.POSITIVE_INFINITY;
  13125. var i, len, nearestElement;
  13126. for (i = 0, len = elements.length; i < len; ++i) {
  13127. var el = elements[i];
  13128. if (el && el.hasValue()) {
  13129. var center = el.getCenterPoint();
  13130. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  13131. if (d < minDistance) {
  13132. minDistance = d;
  13133. nearestElement = el;
  13134. }
  13135. }
  13136. }
  13137. if (nearestElement) {
  13138. var tp = nearestElement.tooltipPosition();
  13139. x = tp.x;
  13140. y = tp.y;
  13141. }
  13142. return {
  13143. x: x,
  13144. y: y
  13145. };
  13146. }
  13147. };
  13148. // Helper to push or concat based on if the 2nd parameter is an array or not
  13149. function pushOrConcat(base, toPush) {
  13150. if (toPush) {
  13151. if (helpers$1.isArray(toPush)) {
  13152. // base = base.concat(toPush);
  13153. Array.prototype.push.apply(base, toPush);
  13154. } else {
  13155. base.push(toPush);
  13156. }
  13157. }
  13158. return base;
  13159. }
  13160. /**
  13161. * Returns array of strings split by newline
  13162. * @param {string} value - The value to split by newline.
  13163. * @returns {string[]} value if newline present - Returned from String split() method
  13164. * @function
  13165. */
  13166. function splitNewlines(str) {
  13167. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  13168. return str.split('\n');
  13169. }
  13170. return str;
  13171. }
  13172. /**
  13173. * Private helper to create a tooltip item model
  13174. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  13175. * @return new tooltip item
  13176. */
  13177. function createTooltipItem(element) {
  13178. var xScale = element._xScale;
  13179. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  13180. var index = element._index;
  13181. var datasetIndex = element._datasetIndex;
  13182. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  13183. var indexScale = controller._getIndexScale();
  13184. var valueScale = controller._getValueScale();
  13185. return {
  13186. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  13187. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  13188. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  13189. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  13190. index: index,
  13191. datasetIndex: datasetIndex,
  13192. x: element._model.x,
  13193. y: element._model.y
  13194. };
  13195. }
  13196. /**
  13197. * Helper to get the reset model for the tooltip
  13198. * @param tooltipOpts {object} the tooltip options
  13199. */
  13200. function getBaseModel(tooltipOpts) {
  13201. var globalDefaults = core_defaults.global;
  13202. return {
  13203. // Positioning
  13204. xPadding: tooltipOpts.xPadding,
  13205. yPadding: tooltipOpts.yPadding,
  13206. xAlign: tooltipOpts.xAlign,
  13207. yAlign: tooltipOpts.yAlign,
  13208. // Drawing direction and text direction
  13209. rtl: tooltipOpts.rtl,
  13210. textDirection: tooltipOpts.textDirection,
  13211. // Body
  13212. bodyFontColor: tooltipOpts.bodyFontColor,
  13213. _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  13214. _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  13215. _bodyAlign: tooltipOpts.bodyAlign,
  13216. bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  13217. bodySpacing: tooltipOpts.bodySpacing,
  13218. // Title
  13219. titleFontColor: tooltipOpts.titleFontColor,
  13220. _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  13221. _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  13222. titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  13223. _titleAlign: tooltipOpts.titleAlign,
  13224. titleSpacing: tooltipOpts.titleSpacing,
  13225. titleMarginBottom: tooltipOpts.titleMarginBottom,
  13226. // Footer
  13227. footerFontColor: tooltipOpts.footerFontColor,
  13228. _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  13229. _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  13230. footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  13231. _footerAlign: tooltipOpts.footerAlign,
  13232. footerSpacing: tooltipOpts.footerSpacing,
  13233. footerMarginTop: tooltipOpts.footerMarginTop,
  13234. // Appearance
  13235. caretSize: tooltipOpts.caretSize,
  13236. cornerRadius: tooltipOpts.cornerRadius,
  13237. backgroundColor: tooltipOpts.backgroundColor,
  13238. opacity: 0,
  13239. legendColorBackground: tooltipOpts.multiKeyBackground,
  13240. displayColors: tooltipOpts.displayColors,
  13241. borderColor: tooltipOpts.borderColor,
  13242. borderWidth: tooltipOpts.borderWidth
  13243. };
  13244. }
  13245. /**
  13246. * Get the size of the tooltip
  13247. */
  13248. function getTooltipSize(tooltip, model) {
  13249. var ctx = tooltip._chart.ctx;
  13250. var height = model.yPadding * 2; // Tooltip Padding
  13251. var width = 0;
  13252. // Count of all lines in the body
  13253. var body = model.body;
  13254. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  13255. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  13256. }, 0);
  13257. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  13258. var titleLineCount = model.title.length;
  13259. var footerLineCount = model.footer.length;
  13260. var titleFontSize = model.titleFontSize;
  13261. var bodyFontSize = model.bodyFontSize;
  13262. var footerFontSize = model.footerFontSize;
  13263. height += titleLineCount * titleFontSize; // Title Lines
  13264. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  13265. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  13266. height += combinedBodyLength * bodyFontSize; // Body Lines
  13267. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  13268. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  13269. height += footerLineCount * (footerFontSize); // Footer Lines
  13270. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  13271. // Title width
  13272. var widthPadding = 0;
  13273. var maxLineWidth = function(line) {
  13274. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  13275. };
  13276. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  13277. helpers$1.each(model.title, maxLineWidth);
  13278. // Body width
  13279. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  13280. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  13281. // Body lines may include some extra width due to the color box
  13282. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  13283. helpers$1.each(body, function(bodyItem) {
  13284. helpers$1.each(bodyItem.before, maxLineWidth);
  13285. helpers$1.each(bodyItem.lines, maxLineWidth);
  13286. helpers$1.each(bodyItem.after, maxLineWidth);
  13287. });
  13288. // Reset back to 0
  13289. widthPadding = 0;
  13290. // Footer width
  13291. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  13292. helpers$1.each(model.footer, maxLineWidth);
  13293. // Add padding
  13294. width += 2 * model.xPadding;
  13295. return {
  13296. width: width,
  13297. height: height
  13298. };
  13299. }
  13300. /**
  13301. * Helper to get the alignment of a tooltip given the size
  13302. */
  13303. function determineAlignment(tooltip, size) {
  13304. var model = tooltip._model;
  13305. var chart = tooltip._chart;
  13306. var chartArea = tooltip._chart.chartArea;
  13307. var xAlign = 'center';
  13308. var yAlign = 'center';
  13309. if (model.y < size.height) {
  13310. yAlign = 'top';
  13311. } else if (model.y > (chart.height - size.height)) {
  13312. yAlign = 'bottom';
  13313. }
  13314. var lf, rf; // functions to determine left, right alignment
  13315. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  13316. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  13317. var midX = (chartArea.left + chartArea.right) / 2;
  13318. var midY = (chartArea.top + chartArea.bottom) / 2;
  13319. if (yAlign === 'center') {
  13320. lf = function(x) {
  13321. return x <= midX;
  13322. };
  13323. rf = function(x) {
  13324. return x > midX;
  13325. };
  13326. } else {
  13327. lf = function(x) {
  13328. return x <= (size.width / 2);
  13329. };
  13330. rf = function(x) {
  13331. return x >= (chart.width - (size.width / 2));
  13332. };
  13333. }
  13334. olf = function(x) {
  13335. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  13336. };
  13337. orf = function(x) {
  13338. return x - size.width - model.caretSize - model.caretPadding < 0;
  13339. };
  13340. yf = function(y) {
  13341. return y <= midY ? 'top' : 'bottom';
  13342. };
  13343. if (lf(model.x)) {
  13344. xAlign = 'left';
  13345. // Is tooltip too wide and goes over the right side of the chart.?
  13346. if (olf(model.x)) {
  13347. xAlign = 'center';
  13348. yAlign = yf(model.y);
  13349. }
  13350. } else if (rf(model.x)) {
  13351. xAlign = 'right';
  13352. // Is tooltip too wide and goes outside left edge of canvas?
  13353. if (orf(model.x)) {
  13354. xAlign = 'center';
  13355. yAlign = yf(model.y);
  13356. }
  13357. }
  13358. var opts = tooltip._options;
  13359. return {
  13360. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  13361. yAlign: opts.yAlign ? opts.yAlign : yAlign
  13362. };
  13363. }
  13364. /**
  13365. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  13366. */
  13367. function getBackgroundPoint(vm, size, alignment, chart) {
  13368. // Background Position
  13369. var x = vm.x;
  13370. var y = vm.y;
  13371. var caretSize = vm.caretSize;
  13372. var caretPadding = vm.caretPadding;
  13373. var cornerRadius = vm.cornerRadius;
  13374. var xAlign = alignment.xAlign;
  13375. var yAlign = alignment.yAlign;
  13376. var paddingAndSize = caretSize + caretPadding;
  13377. var radiusAndPadding = cornerRadius + caretPadding;
  13378. if (xAlign === 'right') {
  13379. x -= size.width;
  13380. } else if (xAlign === 'center') {
  13381. x -= (size.width / 2);
  13382. if (x + size.width > chart.width) {
  13383. x = chart.width - size.width;
  13384. }
  13385. if (x < 0) {
  13386. x = 0;
  13387. }
  13388. }
  13389. if (yAlign === 'top') {
  13390. y += paddingAndSize;
  13391. } else if (yAlign === 'bottom') {
  13392. y -= size.height + paddingAndSize;
  13393. } else {
  13394. y -= (size.height / 2);
  13395. }
  13396. if (yAlign === 'center') {
  13397. if (xAlign === 'left') {
  13398. x += paddingAndSize;
  13399. } else if (xAlign === 'right') {
  13400. x -= paddingAndSize;
  13401. }
  13402. } else if (xAlign === 'left') {
  13403. x -= radiusAndPadding;
  13404. } else if (xAlign === 'right') {
  13405. x += radiusAndPadding;
  13406. }
  13407. return {
  13408. x: x,
  13409. y: y
  13410. };
  13411. }
  13412. function getAlignedX(vm, align) {
  13413. return align === 'center'
  13414. ? vm.x + vm.width / 2
  13415. : align === 'right'
  13416. ? vm.x + vm.width - vm.xPadding
  13417. : vm.x + vm.xPadding;
  13418. }
  13419. /**
  13420. * Helper to build before and after body lines
  13421. */
  13422. function getBeforeAfterBodyLines(callback) {
  13423. return pushOrConcat([], splitNewlines(callback));
  13424. }
  13425. var exports$4 = core_element.extend({
  13426. initialize: function() {
  13427. this._model = getBaseModel(this._options);
  13428. this._lastActive = [];
  13429. },
  13430. // Get the title
  13431. // Args are: (tooltipItem, data)
  13432. getTitle: function() {
  13433. var me = this;
  13434. var opts = me._options;
  13435. var callbacks = opts.callbacks;
  13436. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  13437. var title = callbacks.title.apply(me, arguments);
  13438. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  13439. var lines = [];
  13440. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  13441. lines = pushOrConcat(lines, splitNewlines(title));
  13442. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  13443. return lines;
  13444. },
  13445. // Args are: (tooltipItem, data)
  13446. getBeforeBody: function() {
  13447. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  13448. },
  13449. // Args are: (tooltipItem, data)
  13450. getBody: function(tooltipItems, data) {
  13451. var me = this;
  13452. var callbacks = me._options.callbacks;
  13453. var bodyItems = [];
  13454. helpers$1.each(tooltipItems, function(tooltipItem) {
  13455. var bodyItem = {
  13456. before: [],
  13457. lines: [],
  13458. after: []
  13459. };
  13460. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  13461. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  13462. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  13463. bodyItems.push(bodyItem);
  13464. });
  13465. return bodyItems;
  13466. },
  13467. // Args are: (tooltipItem, data)
  13468. getAfterBody: function() {
  13469. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  13470. },
  13471. // Get the footer and beforeFooter and afterFooter lines
  13472. // Args are: (tooltipItem, data)
  13473. getFooter: function() {
  13474. var me = this;
  13475. var callbacks = me._options.callbacks;
  13476. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  13477. var footer = callbacks.footer.apply(me, arguments);
  13478. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  13479. var lines = [];
  13480. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  13481. lines = pushOrConcat(lines, splitNewlines(footer));
  13482. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  13483. return lines;
  13484. },
  13485. update: function(changed) {
  13486. var me = this;
  13487. var opts = me._options;
  13488. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  13489. // 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
  13490. // which breaks any animations.
  13491. var existingModel = me._model;
  13492. var model = me._model = getBaseModel(opts);
  13493. var active = me._active;
  13494. var data = me._data;
  13495. // In the case where active.length === 0 we need to keep these at existing values for good animations
  13496. var alignment = {
  13497. xAlign: existingModel.xAlign,
  13498. yAlign: existingModel.yAlign
  13499. };
  13500. var backgroundPoint = {
  13501. x: existingModel.x,
  13502. y: existingModel.y
  13503. };
  13504. var tooltipSize = {
  13505. width: existingModel.width,
  13506. height: existingModel.height
  13507. };
  13508. var tooltipPosition = {
  13509. x: existingModel.caretX,
  13510. y: existingModel.caretY
  13511. };
  13512. var i, len;
  13513. if (active.length) {
  13514. model.opacity = 1;
  13515. var labelColors = [];
  13516. var labelTextColors = [];
  13517. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  13518. var tooltipItems = [];
  13519. for (i = 0, len = active.length; i < len; ++i) {
  13520. tooltipItems.push(createTooltipItem(active[i]));
  13521. }
  13522. // If the user provided a filter function, use it to modify the tooltip items
  13523. if (opts.filter) {
  13524. tooltipItems = tooltipItems.filter(function(a) {
  13525. return opts.filter(a, data);
  13526. });
  13527. }
  13528. // If the user provided a sorting function, use it to modify the tooltip items
  13529. if (opts.itemSort) {
  13530. tooltipItems = tooltipItems.sort(function(a, b) {
  13531. return opts.itemSort(a, b, data);
  13532. });
  13533. }
  13534. // Determine colors for boxes
  13535. helpers$1.each(tooltipItems, function(tooltipItem) {
  13536. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  13537. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  13538. });
  13539. // Build the Text Lines
  13540. model.title = me.getTitle(tooltipItems, data);
  13541. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  13542. model.body = me.getBody(tooltipItems, data);
  13543. model.afterBody = me.getAfterBody(tooltipItems, data);
  13544. model.footer = me.getFooter(tooltipItems, data);
  13545. // Initial positioning and colors
  13546. model.x = tooltipPosition.x;
  13547. model.y = tooltipPosition.y;
  13548. model.caretPadding = opts.caretPadding;
  13549. model.labelColors = labelColors;
  13550. model.labelTextColors = labelTextColors;
  13551. // data points
  13552. model.dataPoints = tooltipItems;
  13553. // We need to determine alignment of the tooltip
  13554. tooltipSize = getTooltipSize(this, model);
  13555. alignment = determineAlignment(this, tooltipSize);
  13556. // Final Size and Position
  13557. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  13558. } else {
  13559. model.opacity = 0;
  13560. }
  13561. model.xAlign = alignment.xAlign;
  13562. model.yAlign = alignment.yAlign;
  13563. model.x = backgroundPoint.x;
  13564. model.y = backgroundPoint.y;
  13565. model.width = tooltipSize.width;
  13566. model.height = tooltipSize.height;
  13567. // Point where the caret on the tooltip points to
  13568. model.caretX = tooltipPosition.x;
  13569. model.caretY = tooltipPosition.y;
  13570. me._model = model;
  13571. if (changed && opts.custom) {
  13572. opts.custom.call(me, model);
  13573. }
  13574. return me;
  13575. },
  13576. drawCaret: function(tooltipPoint, size) {
  13577. var ctx = this._chart.ctx;
  13578. var vm = this._view;
  13579. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  13580. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  13581. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  13582. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  13583. },
  13584. getCaretPosition: function(tooltipPoint, size, vm) {
  13585. var x1, x2, x3, y1, y2, y3;
  13586. var caretSize = vm.caretSize;
  13587. var cornerRadius = vm.cornerRadius;
  13588. var xAlign = vm.xAlign;
  13589. var yAlign = vm.yAlign;
  13590. var ptX = tooltipPoint.x;
  13591. var ptY = tooltipPoint.y;
  13592. var width = size.width;
  13593. var height = size.height;
  13594. if (yAlign === 'center') {
  13595. y2 = ptY + (height / 2);
  13596. if (xAlign === 'left') {
  13597. x1 = ptX;
  13598. x2 = x1 - caretSize;
  13599. x3 = x1;
  13600. y1 = y2 + caretSize;
  13601. y3 = y2 - caretSize;
  13602. } else {
  13603. x1 = ptX + width;
  13604. x2 = x1 + caretSize;
  13605. x3 = x1;
  13606. y1 = y2 - caretSize;
  13607. y3 = y2 + caretSize;
  13608. }
  13609. } else {
  13610. if (xAlign === 'left') {
  13611. x2 = ptX + cornerRadius + (caretSize);
  13612. x1 = x2 - caretSize;
  13613. x3 = x2 + caretSize;
  13614. } else if (xAlign === 'right') {
  13615. x2 = ptX + width - cornerRadius - caretSize;
  13616. x1 = x2 - caretSize;
  13617. x3 = x2 + caretSize;
  13618. } else {
  13619. x2 = vm.caretX;
  13620. x1 = x2 - caretSize;
  13621. x3 = x2 + caretSize;
  13622. }
  13623. if (yAlign === 'top') {
  13624. y1 = ptY;
  13625. y2 = y1 - caretSize;
  13626. y3 = y1;
  13627. } else {
  13628. y1 = ptY + height;
  13629. y2 = y1 + caretSize;
  13630. y3 = y1;
  13631. // invert drawing order
  13632. var tmp = x3;
  13633. x3 = x1;
  13634. x1 = tmp;
  13635. }
  13636. }
  13637. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  13638. },
  13639. drawTitle: function(pt, vm, ctx) {
  13640. var title = vm.title;
  13641. var length = title.length;
  13642. var titleFontSize, titleSpacing, i;
  13643. if (length) {
  13644. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  13645. pt.x = getAlignedX(vm, vm._titleAlign);
  13646. ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);
  13647. ctx.textBaseline = 'middle';
  13648. titleFontSize = vm.titleFontSize;
  13649. titleSpacing = vm.titleSpacing;
  13650. ctx.fillStyle = vm.titleFontColor;
  13651. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  13652. for (i = 0; i < length; ++i) {
  13653. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);
  13654. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  13655. if (i + 1 === length) {
  13656. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  13657. }
  13658. }
  13659. }
  13660. },
  13661. drawBody: function(pt, vm, ctx) {
  13662. var bodyFontSize = vm.bodyFontSize;
  13663. var bodySpacing = vm.bodySpacing;
  13664. var bodyAlign = vm._bodyAlign;
  13665. var body = vm.body;
  13666. var drawColorBoxes = vm.displayColors;
  13667. var xLinePadding = 0;
  13668. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  13669. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  13670. var fillLineOfText = function(line) {
  13671. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
  13672. pt.y += bodyFontSize + bodySpacing;
  13673. };
  13674. var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;
  13675. var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  13676. ctx.textAlign = bodyAlign;
  13677. ctx.textBaseline = 'middle';
  13678. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  13679. pt.x = getAlignedX(vm, bodyAlignForCalculation);
  13680. // Before body lines
  13681. ctx.fillStyle = vm.bodyFontColor;
  13682. helpers$1.each(vm.beforeBody, fillLineOfText);
  13683. xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'
  13684. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  13685. : 0;
  13686. // Draw body lines now
  13687. for (i = 0, ilen = body.length; i < ilen; ++i) {
  13688. bodyItem = body[i];
  13689. textColor = vm.labelTextColors[i];
  13690. labelColors = vm.labelColors[i];
  13691. ctx.fillStyle = textColor;
  13692. helpers$1.each(bodyItem.before, fillLineOfText);
  13693. lines = bodyItem.lines;
  13694. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  13695. // Draw Legend-like boxes if needed
  13696. if (drawColorBoxes) {
  13697. var rtlColorX = rtlHelper.x(colorX);
  13698. // Fill a white rect so that colours merge nicely if the opacity is < 1
  13699. ctx.fillStyle = vm.legendColorBackground;
  13700. ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  13701. // Border
  13702. ctx.lineWidth = 1;
  13703. ctx.strokeStyle = labelColors.borderColor;
  13704. ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  13705. // Inner square
  13706. ctx.fillStyle = labelColors.backgroundColor;
  13707. ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  13708. ctx.fillStyle = textColor;
  13709. }
  13710. fillLineOfText(lines[j]);
  13711. }
  13712. helpers$1.each(bodyItem.after, fillLineOfText);
  13713. }
  13714. // Reset back to 0 for after body
  13715. xLinePadding = 0;
  13716. // After body lines
  13717. helpers$1.each(vm.afterBody, fillLineOfText);
  13718. pt.y -= bodySpacing; // Remove last body spacing
  13719. },
  13720. drawFooter: function(pt, vm, ctx) {
  13721. var footer = vm.footer;
  13722. var length = footer.length;
  13723. var footerFontSize, i;
  13724. if (length) {
  13725. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  13726. pt.x = getAlignedX(vm, vm._footerAlign);
  13727. pt.y += vm.footerMarginTop;
  13728. ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);
  13729. ctx.textBaseline = 'middle';
  13730. footerFontSize = vm.footerFontSize;
  13731. ctx.fillStyle = vm.footerFontColor;
  13732. ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  13733. for (i = 0; i < length; ++i) {
  13734. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);
  13735. pt.y += footerFontSize + vm.footerSpacing;
  13736. }
  13737. }
  13738. },
  13739. drawBackground: function(pt, vm, ctx, tooltipSize) {
  13740. ctx.fillStyle = vm.backgroundColor;
  13741. ctx.strokeStyle = vm.borderColor;
  13742. ctx.lineWidth = vm.borderWidth;
  13743. var xAlign = vm.xAlign;
  13744. var yAlign = vm.yAlign;
  13745. var x = pt.x;
  13746. var y = pt.y;
  13747. var width = tooltipSize.width;
  13748. var height = tooltipSize.height;
  13749. var radius = vm.cornerRadius;
  13750. ctx.beginPath();
  13751. ctx.moveTo(x + radius, y);
  13752. if (yAlign === 'top') {
  13753. this.drawCaret(pt, tooltipSize);
  13754. }
  13755. ctx.lineTo(x + width - radius, y);
  13756. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  13757. if (yAlign === 'center' && xAlign === 'right') {
  13758. this.drawCaret(pt, tooltipSize);
  13759. }
  13760. ctx.lineTo(x + width, y + height - radius);
  13761. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  13762. if (yAlign === 'bottom') {
  13763. this.drawCaret(pt, tooltipSize);
  13764. }
  13765. ctx.lineTo(x + radius, y + height);
  13766. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  13767. if (yAlign === 'center' && xAlign === 'left') {
  13768. this.drawCaret(pt, tooltipSize);
  13769. }
  13770. ctx.lineTo(x, y + radius);
  13771. ctx.quadraticCurveTo(x, y, x + radius, y);
  13772. ctx.closePath();
  13773. ctx.fill();
  13774. if (vm.borderWidth > 0) {
  13775. ctx.stroke();
  13776. }
  13777. },
  13778. draw: function() {
  13779. var ctx = this._chart.ctx;
  13780. var vm = this._view;
  13781. if (vm.opacity === 0) {
  13782. return;
  13783. }
  13784. var tooltipSize = {
  13785. width: vm.width,
  13786. height: vm.height
  13787. };
  13788. var pt = {
  13789. x: vm.x,
  13790. y: vm.y
  13791. };
  13792. // IE11/Edge does not like very small opacities, so snap to 0
  13793. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  13794. // Truthy/falsey value for empty tooltip
  13795. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  13796. if (this._options.enabled && hasTooltipContent) {
  13797. ctx.save();
  13798. ctx.globalAlpha = opacity;
  13799. // Draw Background
  13800. this.drawBackground(pt, vm, ctx, tooltipSize);
  13801. // Draw Title, Body, and Footer
  13802. pt.y += vm.yPadding;
  13803. helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);
  13804. // Titles
  13805. this.drawTitle(pt, vm, ctx);
  13806. // Body
  13807. this.drawBody(pt, vm, ctx);
  13808. // Footer
  13809. this.drawFooter(pt, vm, ctx);
  13810. helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);
  13811. ctx.restore();
  13812. }
  13813. },
  13814. /**
  13815. * Handle an event
  13816. * @private
  13817. * @param {IEvent} event - The event to handle
  13818. * @returns {boolean} true if the tooltip changed
  13819. */
  13820. handleEvent: function(e) {
  13821. var me = this;
  13822. var options = me._options;
  13823. var changed = false;
  13824. me._lastActive = me._lastActive || [];
  13825. // Find Active Elements for tooltips
  13826. if (e.type === 'mouseout') {
  13827. me._active = [];
  13828. } else {
  13829. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  13830. if (options.reverse) {
  13831. me._active.reverse();
  13832. }
  13833. }
  13834. // Remember Last Actives
  13835. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  13836. // Only handle target event on tooltip change
  13837. if (changed) {
  13838. me._lastActive = me._active;
  13839. if (options.enabled || options.custom) {
  13840. me._eventPosition = {
  13841. x: e.x,
  13842. y: e.y
  13843. };
  13844. me.update(true);
  13845. me.pivot();
  13846. }
  13847. }
  13848. return changed;
  13849. }
  13850. });
  13851. /**
  13852. * @namespace Chart.Tooltip.positioners
  13853. */
  13854. var positioners_1 = positioners;
  13855. var core_tooltip = exports$4;
  13856. core_tooltip.positioners = positioners_1;
  13857. var valueOrDefault$9 = helpers$1.valueOrDefault;
  13858. core_defaults._set('global', {
  13859. elements: {},
  13860. events: [
  13861. 'mousemove',
  13862. 'mouseout',
  13863. 'click',
  13864. 'touchstart',
  13865. 'touchmove'
  13866. ],
  13867. hover: {
  13868. onHover: null,
  13869. mode: 'nearest',
  13870. intersect: true,
  13871. animationDuration: 400
  13872. },
  13873. onClick: null,
  13874. maintainAspectRatio: true,
  13875. responsive: true,
  13876. responsiveAnimationDuration: 0
  13877. });
  13878. /**
  13879. * Recursively merge the given config objects representing the `scales` option
  13880. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  13881. * returns a deep copy of the result, thus doesn't alter inputs.
  13882. */
  13883. function mergeScaleConfig(/* config objects ... */) {
  13884. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  13885. merger: function(key, target, source, options) {
  13886. if (key === 'xAxes' || key === 'yAxes') {
  13887. var slen = source[key].length;
  13888. var i, type, scale;
  13889. if (!target[key]) {
  13890. target[key] = [];
  13891. }
  13892. for (i = 0; i < slen; ++i) {
  13893. scale = source[key][i];
  13894. type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');
  13895. if (i >= target[key].length) {
  13896. target[key].push({});
  13897. }
  13898. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  13899. // new/untyped scale or type changed: let's apply the new defaults
  13900. // then merge source scale to correctly overwrite the defaults.
  13901. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  13902. } else {
  13903. // scales type are the same
  13904. helpers$1.merge(target[key][i], scale);
  13905. }
  13906. }
  13907. } else {
  13908. helpers$1._merger(key, target, source, options);
  13909. }
  13910. }
  13911. });
  13912. }
  13913. /**
  13914. * Recursively merge the given config objects as the root options by handling
  13915. * default scale options for the `scales` and `scale` properties, then returns
  13916. * a deep copy of the result, thus doesn't alter inputs.
  13917. */
  13918. function mergeConfig(/* config objects ... */) {
  13919. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  13920. merger: function(key, target, source, options) {
  13921. var tval = target[key] || Object.create(null);
  13922. var sval = source[key];
  13923. if (key === 'scales') {
  13924. // scale config merging is complex. Add our own function here for that
  13925. target[key] = mergeScaleConfig(tval, sval);
  13926. } else if (key === 'scale') {
  13927. // used in polar area & radar charts since there is only one scale
  13928. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  13929. } else {
  13930. helpers$1._merger(key, target, source, options);
  13931. }
  13932. }
  13933. });
  13934. }
  13935. function initConfig(config) {
  13936. config = config || Object.create(null);
  13937. // Do NOT use mergeConfig for the data object because this method merges arrays
  13938. // and so would change references to labels and datasets, preventing data updates.
  13939. var data = config.data = config.data || {};
  13940. data.datasets = data.datasets || [];
  13941. data.labels = data.labels || [];
  13942. config.options = mergeConfig(
  13943. core_defaults.global,
  13944. core_defaults[config.type],
  13945. config.options || {});
  13946. return config;
  13947. }
  13948. function updateConfig(chart) {
  13949. var newOptions = chart.options;
  13950. helpers$1.each(chart.scales, function(scale) {
  13951. core_layouts.removeBox(chart, scale);
  13952. });
  13953. newOptions = mergeConfig(
  13954. core_defaults.global,
  13955. core_defaults[chart.config.type],
  13956. newOptions);
  13957. chart.options = chart.config.options = newOptions;
  13958. chart.ensureScalesHaveIDs();
  13959. chart.buildOrUpdateScales();
  13960. // Tooltip
  13961. chart.tooltip._options = newOptions.tooltips;
  13962. chart.tooltip.initialize();
  13963. }
  13964. function nextAvailableScaleId(axesOpts, prefix, index) {
  13965. var id;
  13966. var hasId = function(obj) {
  13967. return obj.id === id;
  13968. };
  13969. do {
  13970. id = prefix + index++;
  13971. } while (helpers$1.findIndex(axesOpts, hasId) >= 0);
  13972. return id;
  13973. }
  13974. function positionIsHorizontal(position) {
  13975. return position === 'top' || position === 'bottom';
  13976. }
  13977. function compare2Level(l1, l2) {
  13978. return function(a, b) {
  13979. return a[l1] === b[l1]
  13980. ? a[l2] - b[l2]
  13981. : a[l1] - b[l1];
  13982. };
  13983. }
  13984. var Chart = function(item, config) {
  13985. this.construct(item, config);
  13986. return this;
  13987. };
  13988. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  13989. /**
  13990. * @private
  13991. */
  13992. construct: function(item, config) {
  13993. var me = this;
  13994. config = initConfig(config);
  13995. var context = platform.acquireContext(item, config);
  13996. var canvas = context && context.canvas;
  13997. var height = canvas && canvas.height;
  13998. var width = canvas && canvas.width;
  13999. me.id = helpers$1.uid();
  14000. me.ctx = context;
  14001. me.canvas = canvas;
  14002. me.config = config;
  14003. me.width = width;
  14004. me.height = height;
  14005. me.aspectRatio = height ? width / height : null;
  14006. me.options = config.options;
  14007. me._bufferedRender = false;
  14008. me._layers = [];
  14009. /**
  14010. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  14011. * the "instance" still need to be defined since it might be called from plugins.
  14012. * @prop Chart#chart
  14013. * @deprecated since version 2.6.0
  14014. * @todo remove at version 3
  14015. * @private
  14016. */
  14017. me.chart = me;
  14018. me.controller = me; // chart.chart.controller #inception
  14019. // Add the chart instance to the global namespace
  14020. Chart.instances[me.id] = me;
  14021. // Define alias to the config data: `chart.data === chart.config.data`
  14022. Object.defineProperty(me, 'data', {
  14023. get: function() {
  14024. return me.config.data;
  14025. },
  14026. set: function(value) {
  14027. me.config.data = value;
  14028. }
  14029. });
  14030. if (!context || !canvas) {
  14031. // The given item is not a compatible context2d element, let's return before finalizing
  14032. // the chart initialization but after setting basic chart / controller properties that
  14033. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  14034. // https://github.com/chartjs/Chart.js/issues/2807
  14035. console.error("Failed to create chart: can't acquire context from the given item");
  14036. return;
  14037. }
  14038. me.initialize();
  14039. me.update();
  14040. },
  14041. /**
  14042. * @private
  14043. */
  14044. initialize: function() {
  14045. var me = this;
  14046. // Before init plugin notification
  14047. core_plugins.notify(me, 'beforeInit');
  14048. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  14049. me.bindEvents();
  14050. if (me.options.responsive) {
  14051. // Initial resize before chart draws (must be silent to preserve initial animations).
  14052. me.resize(true);
  14053. }
  14054. me.initToolTip();
  14055. // After init plugin notification
  14056. core_plugins.notify(me, 'afterInit');
  14057. return me;
  14058. },
  14059. clear: function() {
  14060. helpers$1.canvas.clear(this);
  14061. return this;
  14062. },
  14063. stop: function() {
  14064. // Stops any current animation loop occurring
  14065. core_animations.cancelAnimation(this);
  14066. return this;
  14067. },
  14068. resize: function(silent) {
  14069. var me = this;
  14070. var options = me.options;
  14071. var canvas = me.canvas;
  14072. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  14073. // the canvas render width and height will be casted to integers so make sure that
  14074. // the canvas display style uses the same integer values to avoid blurring effect.
  14075. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  14076. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  14077. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  14078. if (me.width === newWidth && me.height === newHeight) {
  14079. return;
  14080. }
  14081. canvas.width = me.width = newWidth;
  14082. canvas.height = me.height = newHeight;
  14083. canvas.style.width = newWidth + 'px';
  14084. canvas.style.height = newHeight + 'px';
  14085. helpers$1.retinaScale(me, options.devicePixelRatio);
  14086. if (!silent) {
  14087. // Notify any plugins about the resize
  14088. var newSize = {width: newWidth, height: newHeight};
  14089. core_plugins.notify(me, 'resize', [newSize]);
  14090. // Notify of resize
  14091. if (options.onResize) {
  14092. options.onResize(me, newSize);
  14093. }
  14094. me.stop();
  14095. me.update({
  14096. duration: options.responsiveAnimationDuration
  14097. });
  14098. }
  14099. },
  14100. ensureScalesHaveIDs: function() {
  14101. var options = this.options;
  14102. var scalesOptions = options.scales || {};
  14103. var scaleOptions = options.scale;
  14104. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  14105. if (!xAxisOptions.id) {
  14106. xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);
  14107. }
  14108. });
  14109. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  14110. if (!yAxisOptions.id) {
  14111. yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);
  14112. }
  14113. });
  14114. if (scaleOptions) {
  14115. scaleOptions.id = scaleOptions.id || 'scale';
  14116. }
  14117. },
  14118. /**
  14119. * Builds a map of scale ID to scale object for future lookup.
  14120. */
  14121. buildOrUpdateScales: function() {
  14122. var me = this;
  14123. var options = me.options;
  14124. var scales = me.scales || {};
  14125. var items = [];
  14126. var updated = Object.keys(scales).reduce(function(obj, id) {
  14127. obj[id] = false;
  14128. return obj;
  14129. }, {});
  14130. if (options.scales) {
  14131. items = items.concat(
  14132. (options.scales.xAxes || []).map(function(xAxisOptions) {
  14133. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  14134. }),
  14135. (options.scales.yAxes || []).map(function(yAxisOptions) {
  14136. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  14137. })
  14138. );
  14139. }
  14140. if (options.scale) {
  14141. items.push({
  14142. options: options.scale,
  14143. dtype: 'radialLinear',
  14144. isDefault: true,
  14145. dposition: 'chartArea'
  14146. });
  14147. }
  14148. helpers$1.each(items, function(item) {
  14149. var scaleOptions = item.options;
  14150. var id = scaleOptions.id;
  14151. var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);
  14152. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  14153. scaleOptions.position = item.dposition;
  14154. }
  14155. updated[id] = true;
  14156. var scale = null;
  14157. if (id in scales && scales[id].type === scaleType) {
  14158. scale = scales[id];
  14159. scale.options = scaleOptions;
  14160. scale.ctx = me.ctx;
  14161. scale.chart = me;
  14162. } else {
  14163. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  14164. if (!scaleClass) {
  14165. return;
  14166. }
  14167. scale = new scaleClass({
  14168. id: id,
  14169. type: scaleType,
  14170. options: scaleOptions,
  14171. ctx: me.ctx,
  14172. chart: me
  14173. });
  14174. scales[scale.id] = scale;
  14175. }
  14176. scale.mergeTicksOptions();
  14177. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  14178. // and consider it as a regular scale part of the "scales"" map only! This would
  14179. // make the logic easier and remove some useless? custom code.
  14180. if (item.isDefault) {
  14181. me.scale = scale;
  14182. }
  14183. });
  14184. // clear up discarded scales
  14185. helpers$1.each(updated, function(hasUpdated, id) {
  14186. if (!hasUpdated) {
  14187. delete scales[id];
  14188. }
  14189. });
  14190. me.scales = scales;
  14191. core_scaleService.addScalesToLayout(this);
  14192. },
  14193. buildOrUpdateControllers: function() {
  14194. var me = this;
  14195. var newControllers = [];
  14196. var datasets = me.data.datasets;
  14197. var i, ilen;
  14198. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  14199. var dataset = datasets[i];
  14200. var meta = me.getDatasetMeta(i);
  14201. var type = dataset.type || me.config.type;
  14202. if (meta.type && meta.type !== type) {
  14203. me.destroyDatasetMeta(i);
  14204. meta = me.getDatasetMeta(i);
  14205. }
  14206. meta.type = type;
  14207. meta.order = dataset.order || 0;
  14208. meta.index = i;
  14209. if (meta.controller) {
  14210. meta.controller.updateIndex(i);
  14211. meta.controller.linkScales();
  14212. } else {
  14213. var ControllerClass = controllers[meta.type];
  14214. if (ControllerClass === undefined) {
  14215. throw new Error('"' + meta.type + '" is not a chart type.');
  14216. }
  14217. meta.controller = new ControllerClass(me, i);
  14218. newControllers.push(meta.controller);
  14219. }
  14220. }
  14221. return newControllers;
  14222. },
  14223. /**
  14224. * Reset the elements of all datasets
  14225. * @private
  14226. */
  14227. resetElements: function() {
  14228. var me = this;
  14229. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  14230. me.getDatasetMeta(datasetIndex).controller.reset();
  14231. }, me);
  14232. },
  14233. /**
  14234. * Resets the chart back to it's state before the initial animation
  14235. */
  14236. reset: function() {
  14237. this.resetElements();
  14238. this.tooltip.initialize();
  14239. },
  14240. update: function(config) {
  14241. var me = this;
  14242. var i, ilen;
  14243. if (!config || typeof config !== 'object') {
  14244. // backwards compatibility
  14245. config = {
  14246. duration: config,
  14247. lazy: arguments[1]
  14248. };
  14249. }
  14250. updateConfig(me);
  14251. // plugins options references might have change, let's invalidate the cache
  14252. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  14253. core_plugins._invalidate(me);
  14254. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  14255. return;
  14256. }
  14257. // In case the entire data object changed
  14258. me.tooltip._data = me.data;
  14259. // Make sure dataset controllers are updated and new controllers are reset
  14260. var newControllers = me.buildOrUpdateControllers();
  14261. // Make sure all dataset controllers have correct meta data counts
  14262. for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  14263. me.getDatasetMeta(i).controller.buildOrUpdateElements();
  14264. }
  14265. me.updateLayout();
  14266. // Can only reset the new controllers after the scales have been updated
  14267. if (me.options.animation && me.options.animation.duration) {
  14268. helpers$1.each(newControllers, function(controller) {
  14269. controller.reset();
  14270. });
  14271. }
  14272. me.updateDatasets();
  14273. // Need to reset tooltip in case it is displayed with elements that are removed
  14274. // after update.
  14275. me.tooltip.initialize();
  14276. // Last active contains items that were previously in the tooltip.
  14277. // When we reset the tooltip, we need to clear it
  14278. me.lastActive = [];
  14279. // Do this before render so that any plugins that need final scale updates can use it
  14280. core_plugins.notify(me, 'afterUpdate');
  14281. me._layers.sort(compare2Level('z', '_idx'));
  14282. if (me._bufferedRender) {
  14283. me._bufferedRequest = {
  14284. duration: config.duration,
  14285. easing: config.easing,
  14286. lazy: config.lazy
  14287. };
  14288. } else {
  14289. me.render(config);
  14290. }
  14291. },
  14292. /**
  14293. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  14294. * hook, in which case, plugins will not be called on `afterLayout`.
  14295. * @private
  14296. */
  14297. updateLayout: function() {
  14298. var me = this;
  14299. if (core_plugins.notify(me, 'beforeLayout') === false) {
  14300. return;
  14301. }
  14302. core_layouts.update(this, this.width, this.height);
  14303. me._layers = [];
  14304. helpers$1.each(me.boxes, function(box) {
  14305. // _configure is called twice, once in core.scale.update and once here.
  14306. // Here the boxes are fully updated and at their final positions.
  14307. if (box._configure) {
  14308. box._configure();
  14309. }
  14310. me._layers.push.apply(me._layers, box._layers());
  14311. }, me);
  14312. me._layers.forEach(function(item, index) {
  14313. item._idx = index;
  14314. });
  14315. /**
  14316. * Provided for backward compatibility, use `afterLayout` instead.
  14317. * @method IPlugin#afterScaleUpdate
  14318. * @deprecated since version 2.5.0
  14319. * @todo remove at version 3
  14320. * @private
  14321. */
  14322. core_plugins.notify(me, 'afterScaleUpdate');
  14323. core_plugins.notify(me, 'afterLayout');
  14324. },
  14325. /**
  14326. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  14327. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  14328. * @private
  14329. */
  14330. updateDatasets: function() {
  14331. var me = this;
  14332. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  14333. return;
  14334. }
  14335. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  14336. me.updateDataset(i);
  14337. }
  14338. core_plugins.notify(me, 'afterDatasetsUpdate');
  14339. },
  14340. /**
  14341. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  14342. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  14343. * @private
  14344. */
  14345. updateDataset: function(index) {
  14346. var me = this;
  14347. var meta = me.getDatasetMeta(index);
  14348. var args = {
  14349. meta: meta,
  14350. index: index
  14351. };
  14352. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  14353. return;
  14354. }
  14355. meta.controller._update();
  14356. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  14357. },
  14358. render: function(config) {
  14359. var me = this;
  14360. if (!config || typeof config !== 'object') {
  14361. // backwards compatibility
  14362. config = {
  14363. duration: config,
  14364. lazy: arguments[1]
  14365. };
  14366. }
  14367. var animationOptions = me.options.animation;
  14368. var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);
  14369. var lazy = config.lazy;
  14370. if (core_plugins.notify(me, 'beforeRender') === false) {
  14371. return;
  14372. }
  14373. var onComplete = function(animation) {
  14374. core_plugins.notify(me, 'afterRender');
  14375. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  14376. };
  14377. if (animationOptions && duration) {
  14378. var animation = new core_animation({
  14379. numSteps: duration / 16.66, // 60 fps
  14380. easing: config.easing || animationOptions.easing,
  14381. render: function(chart, animationObject) {
  14382. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  14383. var currentStep = animationObject.currentStep;
  14384. var stepDecimal = currentStep / animationObject.numSteps;
  14385. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  14386. },
  14387. onAnimationProgress: animationOptions.onProgress,
  14388. onAnimationComplete: onComplete
  14389. });
  14390. core_animations.addAnimation(me, animation, duration, lazy);
  14391. } else {
  14392. me.draw();
  14393. // See https://github.com/chartjs/Chart.js/issues/3781
  14394. onComplete(new core_animation({numSteps: 0, chart: me}));
  14395. }
  14396. return me;
  14397. },
  14398. draw: function(easingValue) {
  14399. var me = this;
  14400. var i, layers;
  14401. me.clear();
  14402. if (helpers$1.isNullOrUndef(easingValue)) {
  14403. easingValue = 1;
  14404. }
  14405. me.transition(easingValue);
  14406. if (me.width <= 0 || me.height <= 0) {
  14407. return;
  14408. }
  14409. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  14410. return;
  14411. }
  14412. // Because of plugin hooks (before/afterDatasetsDraw), datasets can't
  14413. // currently be part of layers. Instead, we draw
  14414. // layers <= 0 before(default, backward compat), and the rest after
  14415. layers = me._layers;
  14416. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  14417. layers[i].draw(me.chartArea);
  14418. }
  14419. me.drawDatasets(easingValue);
  14420. // Rest of layers
  14421. for (; i < layers.length; ++i) {
  14422. layers[i].draw(me.chartArea);
  14423. }
  14424. me._drawTooltip(easingValue);
  14425. core_plugins.notify(me, 'afterDraw', [easingValue]);
  14426. },
  14427. /**
  14428. * @private
  14429. */
  14430. transition: function(easingValue) {
  14431. var me = this;
  14432. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  14433. if (me.isDatasetVisible(i)) {
  14434. me.getDatasetMeta(i).controller.transition(easingValue);
  14435. }
  14436. }
  14437. me.tooltip.transition(easingValue);
  14438. },
  14439. /**
  14440. * @private
  14441. */
  14442. _getSortedDatasetMetas: function(filterVisible) {
  14443. var me = this;
  14444. var datasets = me.data.datasets || [];
  14445. var result = [];
  14446. var i, ilen;
  14447. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  14448. if (!filterVisible || me.isDatasetVisible(i)) {
  14449. result.push(me.getDatasetMeta(i));
  14450. }
  14451. }
  14452. result.sort(compare2Level('order', 'index'));
  14453. return result;
  14454. },
  14455. /**
  14456. * @private
  14457. */
  14458. _getSortedVisibleDatasetMetas: function() {
  14459. return this._getSortedDatasetMetas(true);
  14460. },
  14461. /**
  14462. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  14463. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  14464. * @private
  14465. */
  14466. drawDatasets: function(easingValue) {
  14467. var me = this;
  14468. var metasets, i;
  14469. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  14470. return;
  14471. }
  14472. metasets = me._getSortedVisibleDatasetMetas();
  14473. for (i = metasets.length - 1; i >= 0; --i) {
  14474. me.drawDataset(metasets[i], easingValue);
  14475. }
  14476. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  14477. },
  14478. /**
  14479. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  14480. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  14481. * @private
  14482. */
  14483. drawDataset: function(meta, easingValue) {
  14484. var me = this;
  14485. var args = {
  14486. meta: meta,
  14487. index: meta.index,
  14488. easingValue: easingValue
  14489. };
  14490. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  14491. return;
  14492. }
  14493. meta.controller.draw(easingValue);
  14494. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  14495. },
  14496. /**
  14497. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  14498. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  14499. * @private
  14500. */
  14501. _drawTooltip: function(easingValue) {
  14502. var me = this;
  14503. var tooltip = me.tooltip;
  14504. var args = {
  14505. tooltip: tooltip,
  14506. easingValue: easingValue
  14507. };
  14508. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  14509. return;
  14510. }
  14511. tooltip.draw();
  14512. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  14513. },
  14514. /**
  14515. * Get the single element that was clicked on
  14516. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  14517. */
  14518. getElementAtEvent: function(e) {
  14519. return core_interaction.modes.single(this, e);
  14520. },
  14521. getElementsAtEvent: function(e) {
  14522. return core_interaction.modes.label(this, e, {intersect: true});
  14523. },
  14524. getElementsAtXAxis: function(e) {
  14525. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  14526. },
  14527. getElementsAtEventForMode: function(e, mode, options) {
  14528. var method = core_interaction.modes[mode];
  14529. if (typeof method === 'function') {
  14530. return method(this, e, options);
  14531. }
  14532. return [];
  14533. },
  14534. getDatasetAtEvent: function(e) {
  14535. return core_interaction.modes.dataset(this, e, {intersect: true});
  14536. },
  14537. getDatasetMeta: function(datasetIndex) {
  14538. var me = this;
  14539. var dataset = me.data.datasets[datasetIndex];
  14540. if (!dataset._meta) {
  14541. dataset._meta = {};
  14542. }
  14543. var meta = dataset._meta[me.id];
  14544. if (!meta) {
  14545. meta = dataset._meta[me.id] = {
  14546. type: null,
  14547. data: [],
  14548. dataset: null,
  14549. controller: null,
  14550. hidden: null, // See isDatasetVisible() comment
  14551. xAxisID: null,
  14552. yAxisID: null,
  14553. order: dataset.order || 0,
  14554. index: datasetIndex
  14555. };
  14556. }
  14557. return meta;
  14558. },
  14559. getVisibleDatasetCount: function() {
  14560. var count = 0;
  14561. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  14562. if (this.isDatasetVisible(i)) {
  14563. count++;
  14564. }
  14565. }
  14566. return count;
  14567. },
  14568. isDatasetVisible: function(datasetIndex) {
  14569. var meta = this.getDatasetMeta(datasetIndex);
  14570. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  14571. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  14572. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  14573. },
  14574. generateLegend: function() {
  14575. return this.options.legendCallback(this);
  14576. },
  14577. /**
  14578. * @private
  14579. */
  14580. destroyDatasetMeta: function(datasetIndex) {
  14581. var id = this.id;
  14582. var dataset = this.data.datasets[datasetIndex];
  14583. var meta = dataset._meta && dataset._meta[id];
  14584. if (meta) {
  14585. meta.controller.destroy();
  14586. delete dataset._meta[id];
  14587. }
  14588. },
  14589. destroy: function() {
  14590. var me = this;
  14591. var canvas = me.canvas;
  14592. var i, ilen;
  14593. me.stop();
  14594. // dataset controllers need to cleanup associated data
  14595. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  14596. me.destroyDatasetMeta(i);
  14597. }
  14598. if (canvas) {
  14599. me.unbindEvents();
  14600. helpers$1.canvas.clear(me);
  14601. platform.releaseContext(me.ctx);
  14602. me.canvas = null;
  14603. me.ctx = null;
  14604. }
  14605. core_plugins.notify(me, 'destroy');
  14606. delete Chart.instances[me.id];
  14607. },
  14608. toBase64Image: function() {
  14609. return this.canvas.toDataURL.apply(this.canvas, arguments);
  14610. },
  14611. initToolTip: function() {
  14612. var me = this;
  14613. me.tooltip = new core_tooltip({
  14614. _chart: me,
  14615. _chartInstance: me, // deprecated, backward compatibility
  14616. _data: me.data,
  14617. _options: me.options.tooltips
  14618. }, me);
  14619. },
  14620. /**
  14621. * @private
  14622. */
  14623. bindEvents: function() {
  14624. var me = this;
  14625. var listeners = me._listeners = {};
  14626. var listener = function() {
  14627. me.eventHandler.apply(me, arguments);
  14628. };
  14629. helpers$1.each(me.options.events, function(type) {
  14630. platform.addEventListener(me, type, listener);
  14631. listeners[type] = listener;
  14632. });
  14633. // Elements used to detect size change should not be injected for non responsive charts.
  14634. // See https://github.com/chartjs/Chart.js/issues/2210
  14635. if (me.options.responsive) {
  14636. listener = function() {
  14637. me.resize();
  14638. };
  14639. platform.addEventListener(me, 'resize', listener);
  14640. listeners.resize = listener;
  14641. }
  14642. },
  14643. /**
  14644. * @private
  14645. */
  14646. unbindEvents: function() {
  14647. var me = this;
  14648. var listeners = me._listeners;
  14649. if (!listeners) {
  14650. return;
  14651. }
  14652. delete me._listeners;
  14653. helpers$1.each(listeners, function(listener, type) {
  14654. platform.removeEventListener(me, type, listener);
  14655. });
  14656. },
  14657. updateHoverStyle: function(elements, mode, enabled) {
  14658. var prefix = enabled ? 'set' : 'remove';
  14659. var element, i, ilen;
  14660. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  14661. element = elements[i];
  14662. if (element) {
  14663. this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);
  14664. }
  14665. }
  14666. if (mode === 'dataset') {
  14667. this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();
  14668. }
  14669. },
  14670. /**
  14671. * @private
  14672. */
  14673. eventHandler: function(e) {
  14674. var me = this;
  14675. var tooltip = me.tooltip;
  14676. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  14677. return;
  14678. }
  14679. // Buffer any update calls so that renders do not occur
  14680. me._bufferedRender = true;
  14681. me._bufferedRequest = null;
  14682. var changed = me.handleEvent(e);
  14683. // for smooth tooltip animations issue #4989
  14684. // the tooltip should be the source of change
  14685. // Animation check workaround:
  14686. // tooltip._start will be null when tooltip isn't animating
  14687. if (tooltip) {
  14688. changed = tooltip._start
  14689. ? tooltip.handleEvent(e)
  14690. : changed | tooltip.handleEvent(e);
  14691. }
  14692. core_plugins.notify(me, 'afterEvent', [e]);
  14693. var bufferedRequest = me._bufferedRequest;
  14694. if (bufferedRequest) {
  14695. // If we have an update that was triggered, we need to do a normal render
  14696. me.render(bufferedRequest);
  14697. } else if (changed && !me.animating) {
  14698. // If entering, leaving, or changing elements, animate the change via pivot
  14699. me.stop();
  14700. // We only need to render at this point. Updating will cause scales to be
  14701. // recomputed generating flicker & using more memory than necessary.
  14702. me.render({
  14703. duration: me.options.hover.animationDuration,
  14704. lazy: true
  14705. });
  14706. }
  14707. me._bufferedRender = false;
  14708. me._bufferedRequest = null;
  14709. return me;
  14710. },
  14711. /**
  14712. * Handle an event
  14713. * @private
  14714. * @param {IEvent} event the event to handle
  14715. * @return {boolean} true if the chart needs to re-render
  14716. */
  14717. handleEvent: function(e) {
  14718. var me = this;
  14719. var options = me.options || {};
  14720. var hoverOptions = options.hover;
  14721. var changed = false;
  14722. me.lastActive = me.lastActive || [];
  14723. // Find Active Elements for hover and tooltips
  14724. if (e.type === 'mouseout') {
  14725. me.active = [];
  14726. } else {
  14727. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  14728. }
  14729. // Invoke onHover hook
  14730. // Need to call with native event here to not break backwards compatibility
  14731. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  14732. if (e.type === 'mouseup' || e.type === 'click') {
  14733. if (options.onClick) {
  14734. // Use e.native here for backwards compatibility
  14735. options.onClick.call(me, e.native, me.active);
  14736. }
  14737. }
  14738. // Remove styling for last active (even if it may still be active)
  14739. if (me.lastActive.length) {
  14740. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  14741. }
  14742. // Built in hover styling
  14743. if (me.active.length && hoverOptions.mode) {
  14744. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  14745. }
  14746. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  14747. // Remember Last Actives
  14748. me.lastActive = me.active;
  14749. return changed;
  14750. }
  14751. });
  14752. /**
  14753. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  14754. * for backward compatibility. Though, it can still be useful for plugins that
  14755. * would need to work on multiple charts?!
  14756. */
  14757. Chart.instances = {};
  14758. var core_controller = Chart;
  14759. // DEPRECATIONS
  14760. /**
  14761. * Provided for backward compatibility, use Chart instead.
  14762. * @class Chart.Controller
  14763. * @deprecated since version 2.6
  14764. * @todo remove at version 3
  14765. * @private
  14766. */
  14767. Chart.Controller = Chart;
  14768. /**
  14769. * Provided for backward compatibility, not available anymore.
  14770. * @namespace Chart
  14771. * @deprecated since version 2.8
  14772. * @todo remove at version 3
  14773. * @private
  14774. */
  14775. Chart.types = {};
  14776. /**
  14777. * Provided for backward compatibility, not available anymore.
  14778. * @namespace Chart.helpers.configMerge
  14779. * @deprecated since version 2.8.0
  14780. * @todo remove at version 3
  14781. * @private
  14782. */
  14783. helpers$1.configMerge = mergeConfig;
  14784. /**
  14785. * Provided for backward compatibility, not available anymore.
  14786. * @namespace Chart.helpers.scaleMerge
  14787. * @deprecated since version 2.8.0
  14788. * @todo remove at version 3
  14789. * @private
  14790. */
  14791. helpers$1.scaleMerge = mergeScaleConfig;
  14792. var core_helpers = function() {
  14793. // -- Basic js utility methods
  14794. helpers$1.where = function(collection, filterCallback) {
  14795. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  14796. return collection.filter(filterCallback);
  14797. }
  14798. var filtered = [];
  14799. helpers$1.each(collection, function(item) {
  14800. if (filterCallback(item)) {
  14801. filtered.push(item);
  14802. }
  14803. });
  14804. return filtered;
  14805. };
  14806. helpers$1.findIndex = Array.prototype.findIndex ?
  14807. function(array, callback, scope) {
  14808. return array.findIndex(callback, scope);
  14809. } :
  14810. function(array, callback, scope) {
  14811. scope = scope === undefined ? array : scope;
  14812. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  14813. if (callback.call(scope, array[i], i, array)) {
  14814. return i;
  14815. }
  14816. }
  14817. return -1;
  14818. };
  14819. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  14820. // Default to start of the array
  14821. if (helpers$1.isNullOrUndef(startIndex)) {
  14822. startIndex = -1;
  14823. }
  14824. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  14825. var currentItem = arrayToSearch[i];
  14826. if (filterCallback(currentItem)) {
  14827. return currentItem;
  14828. }
  14829. }
  14830. };
  14831. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  14832. // Default to end of the array
  14833. if (helpers$1.isNullOrUndef(startIndex)) {
  14834. startIndex = arrayToSearch.length;
  14835. }
  14836. for (var i = startIndex - 1; i >= 0; i--) {
  14837. var currentItem = arrayToSearch[i];
  14838. if (filterCallback(currentItem)) {
  14839. return currentItem;
  14840. }
  14841. }
  14842. };
  14843. // -- Math methods
  14844. helpers$1.isNumber = function(n) {
  14845. return !isNaN(parseFloat(n)) && isFinite(n);
  14846. };
  14847. helpers$1.almostEquals = function(x, y, epsilon) {
  14848. return Math.abs(x - y) < epsilon;
  14849. };
  14850. helpers$1.almostWhole = function(x, epsilon) {
  14851. var rounded = Math.round(x);
  14852. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  14853. };
  14854. helpers$1.max = function(array) {
  14855. return array.reduce(function(max, value) {
  14856. if (!isNaN(value)) {
  14857. return Math.max(max, value);
  14858. }
  14859. return max;
  14860. }, Number.NEGATIVE_INFINITY);
  14861. };
  14862. helpers$1.min = function(array) {
  14863. return array.reduce(function(min, value) {
  14864. if (!isNaN(value)) {
  14865. return Math.min(min, value);
  14866. }
  14867. return min;
  14868. }, Number.POSITIVE_INFINITY);
  14869. };
  14870. helpers$1.sign = Math.sign ?
  14871. function(x) {
  14872. return Math.sign(x);
  14873. } :
  14874. function(x) {
  14875. x = +x; // convert to a number
  14876. if (x === 0 || isNaN(x)) {
  14877. return x;
  14878. }
  14879. return x > 0 ? 1 : -1;
  14880. };
  14881. helpers$1.toRadians = function(degrees) {
  14882. return degrees * (Math.PI / 180);
  14883. };
  14884. helpers$1.toDegrees = function(radians) {
  14885. return radians * (180 / Math.PI);
  14886. };
  14887. /**
  14888. * Returns the number of decimal places
  14889. * i.e. the number of digits after the decimal point, of the value of this Number.
  14890. * @param {number} x - A number.
  14891. * @returns {number} The number of decimal places.
  14892. * @private
  14893. */
  14894. helpers$1._decimalPlaces = function(x) {
  14895. if (!helpers$1.isFinite(x)) {
  14896. return;
  14897. }
  14898. var e = 1;
  14899. var p = 0;
  14900. while (Math.round(x * e) / e !== x) {
  14901. e *= 10;
  14902. p++;
  14903. }
  14904. return p;
  14905. };
  14906. // Gets the angle from vertical upright to the point about a centre.
  14907. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  14908. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  14909. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  14910. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  14911. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  14912. if (angle < (-0.5 * Math.PI)) {
  14913. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  14914. }
  14915. return {
  14916. angle: angle,
  14917. distance: radialDistanceFromCenter
  14918. };
  14919. };
  14920. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  14921. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  14922. };
  14923. /**
  14924. * Provided for backward compatibility, not available anymore
  14925. * @function Chart.helpers.aliasPixel
  14926. * @deprecated since version 2.8.0
  14927. * @todo remove at version 3
  14928. */
  14929. helpers$1.aliasPixel = function(pixelWidth) {
  14930. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  14931. };
  14932. /**
  14933. * Returns the aligned pixel value to avoid anti-aliasing blur
  14934. * @param {Chart} chart - The chart instance.
  14935. * @param {number} pixel - A pixel value.
  14936. * @param {number} width - The width of the element.
  14937. * @returns {number} The aligned pixel value.
  14938. * @private
  14939. */
  14940. helpers$1._alignPixel = function(chart, pixel, width) {
  14941. var devicePixelRatio = chart.currentDevicePixelRatio;
  14942. var halfWidth = width / 2;
  14943. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  14944. };
  14945. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  14946. // Props to Rob Spencer at scaled innovation for his post on splining between points
  14947. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  14948. // This function must also respect "skipped" points
  14949. var previous = firstPoint.skip ? middlePoint : firstPoint;
  14950. var current = middlePoint;
  14951. var next = afterPoint.skip ? middlePoint : afterPoint;
  14952. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  14953. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  14954. var s01 = d01 / (d01 + d12);
  14955. var s12 = d12 / (d01 + d12);
  14956. // If all points are the same, s01 & s02 will be inf
  14957. s01 = isNaN(s01) ? 0 : s01;
  14958. s12 = isNaN(s12) ? 0 : s12;
  14959. var fa = t * s01; // scaling factor for triangle Ta
  14960. var fb = t * s12;
  14961. return {
  14962. previous: {
  14963. x: current.x - fa * (next.x - previous.x),
  14964. y: current.y - fa * (next.y - previous.y)
  14965. },
  14966. next: {
  14967. x: current.x + fb * (next.x - previous.x),
  14968. y: current.y + fb * (next.y - previous.y)
  14969. }
  14970. };
  14971. };
  14972. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  14973. helpers$1.splineCurveMonotone = function(points) {
  14974. // This function calculates Bézier control points in a similar way than |splineCurve|,
  14975. // but preserves monotonicity of the provided data and ensures no local extremums are added
  14976. // between the dataset discrete points due to the interpolation.
  14977. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  14978. var pointsWithTangents = (points || []).map(function(point) {
  14979. return {
  14980. model: point._model,
  14981. deltaK: 0,
  14982. mK: 0
  14983. };
  14984. });
  14985. // Calculate slopes (deltaK) and initialize tangents (mK)
  14986. var pointsLen = pointsWithTangents.length;
  14987. var i, pointBefore, pointCurrent, pointAfter;
  14988. for (i = 0; i < pointsLen; ++i) {
  14989. pointCurrent = pointsWithTangents[i];
  14990. if (pointCurrent.model.skip) {
  14991. continue;
  14992. }
  14993. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  14994. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  14995. if (pointAfter && !pointAfter.model.skip) {
  14996. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  14997. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  14998. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  14999. }
  15000. if (!pointBefore || pointBefore.model.skip) {
  15001. pointCurrent.mK = pointCurrent.deltaK;
  15002. } else if (!pointAfter || pointAfter.model.skip) {
  15003. pointCurrent.mK = pointBefore.deltaK;
  15004. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  15005. pointCurrent.mK = 0;
  15006. } else {
  15007. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  15008. }
  15009. }
  15010. // Adjust tangents to ensure monotonic properties
  15011. var alphaK, betaK, tauK, squaredMagnitude;
  15012. for (i = 0; i < pointsLen - 1; ++i) {
  15013. pointCurrent = pointsWithTangents[i];
  15014. pointAfter = pointsWithTangents[i + 1];
  15015. if (pointCurrent.model.skip || pointAfter.model.skip) {
  15016. continue;
  15017. }
  15018. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  15019. pointCurrent.mK = pointAfter.mK = 0;
  15020. continue;
  15021. }
  15022. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  15023. betaK = pointAfter.mK / pointCurrent.deltaK;
  15024. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  15025. if (squaredMagnitude <= 9) {
  15026. continue;
  15027. }
  15028. tauK = 3 / Math.sqrt(squaredMagnitude);
  15029. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  15030. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  15031. }
  15032. // Compute control points
  15033. var deltaX;
  15034. for (i = 0; i < pointsLen; ++i) {
  15035. pointCurrent = pointsWithTangents[i];
  15036. if (pointCurrent.model.skip) {
  15037. continue;
  15038. }
  15039. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  15040. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  15041. if (pointBefore && !pointBefore.model.skip) {
  15042. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  15043. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  15044. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  15045. }
  15046. if (pointAfter && !pointAfter.model.skip) {
  15047. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  15048. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  15049. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  15050. }
  15051. }
  15052. };
  15053. helpers$1.nextItem = function(collection, index, loop) {
  15054. if (loop) {
  15055. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  15056. }
  15057. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  15058. };
  15059. helpers$1.previousItem = function(collection, index, loop) {
  15060. if (loop) {
  15061. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  15062. }
  15063. return index <= 0 ? collection[0] : collection[index - 1];
  15064. };
  15065. // Implementation of the nice number algorithm used in determining where axis labels will go
  15066. helpers$1.niceNum = function(range, round) {
  15067. var exponent = Math.floor(helpers$1.log10(range));
  15068. var fraction = range / Math.pow(10, exponent);
  15069. var niceFraction;
  15070. if (round) {
  15071. if (fraction < 1.5) {
  15072. niceFraction = 1;
  15073. } else if (fraction < 3) {
  15074. niceFraction = 2;
  15075. } else if (fraction < 7) {
  15076. niceFraction = 5;
  15077. } else {
  15078. niceFraction = 10;
  15079. }
  15080. } else if (fraction <= 1.0) {
  15081. niceFraction = 1;
  15082. } else if (fraction <= 2) {
  15083. niceFraction = 2;
  15084. } else if (fraction <= 5) {
  15085. niceFraction = 5;
  15086. } else {
  15087. niceFraction = 10;
  15088. }
  15089. return niceFraction * Math.pow(10, exponent);
  15090. };
  15091. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  15092. helpers$1.requestAnimFrame = (function() {
  15093. if (typeof window === 'undefined') {
  15094. return function(callback) {
  15095. callback();
  15096. };
  15097. }
  15098. return window.requestAnimationFrame ||
  15099. window.webkitRequestAnimationFrame ||
  15100. window.mozRequestAnimationFrame ||
  15101. window.oRequestAnimationFrame ||
  15102. window.msRequestAnimationFrame ||
  15103. function(callback) {
  15104. return window.setTimeout(callback, 1000 / 60);
  15105. };
  15106. }());
  15107. // -- DOM methods
  15108. helpers$1.getRelativePosition = function(evt, chart) {
  15109. var mouseX, mouseY;
  15110. var e = evt.originalEvent || evt;
  15111. var canvas = evt.target || evt.srcElement;
  15112. var boundingRect = canvas.getBoundingClientRect();
  15113. var touches = e.touches;
  15114. if (touches && touches.length > 0) {
  15115. mouseX = touches[0].clientX;
  15116. mouseY = touches[0].clientY;
  15117. } else {
  15118. mouseX = e.clientX;
  15119. mouseY = e.clientY;
  15120. }
  15121. // Scale mouse coordinates into canvas coordinates
  15122. // by following the pattern laid out by 'jerryj' in the comments of
  15123. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  15124. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  15125. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  15126. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  15127. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  15128. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  15129. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  15130. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  15131. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  15132. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  15133. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  15134. return {
  15135. x: mouseX,
  15136. y: mouseY
  15137. };
  15138. };
  15139. // Private helper function to convert max-width/max-height values that may be percentages into a number
  15140. function parseMaxStyle(styleValue, node, parentProperty) {
  15141. var valueInPixels;
  15142. if (typeof styleValue === 'string') {
  15143. valueInPixels = parseInt(styleValue, 10);
  15144. if (styleValue.indexOf('%') !== -1) {
  15145. // percentage * size in dimension
  15146. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  15147. }
  15148. } else {
  15149. valueInPixels = styleValue;
  15150. }
  15151. return valueInPixels;
  15152. }
  15153. /**
  15154. * Returns if the given value contains an effective constraint.
  15155. * @private
  15156. */
  15157. function isConstrainedValue(value) {
  15158. return value !== undefined && value !== null && value !== 'none';
  15159. }
  15160. /**
  15161. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  15162. * @param {HTMLElement} domNode - the node to check the constraint on
  15163. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  15164. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  15165. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  15166. */
  15167. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  15168. var view = document.defaultView;
  15169. var parentNode = helpers$1._getParentNode(domNode);
  15170. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  15171. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  15172. var hasCNode = isConstrainedValue(constrainedNode);
  15173. var hasCContainer = isConstrainedValue(constrainedContainer);
  15174. var infinity = Number.POSITIVE_INFINITY;
  15175. if (hasCNode || hasCContainer) {
  15176. return Math.min(
  15177. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  15178. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  15179. }
  15180. return 'none';
  15181. }
  15182. // returns Number or undefined if no constraint
  15183. helpers$1.getConstraintWidth = function(domNode) {
  15184. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  15185. };
  15186. // returns Number or undefined if no constraint
  15187. helpers$1.getConstraintHeight = function(domNode) {
  15188. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  15189. };
  15190. /**
  15191. * @private
  15192. */
  15193. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  15194. padding = helpers$1.getStyle(container, padding);
  15195. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  15196. };
  15197. /**
  15198. * @private
  15199. */
  15200. helpers$1._getParentNode = function(domNode) {
  15201. var parent = domNode.parentNode;
  15202. if (parent && parent.toString() === '[object ShadowRoot]') {
  15203. parent = parent.host;
  15204. }
  15205. return parent;
  15206. };
  15207. helpers$1.getMaximumWidth = function(domNode) {
  15208. var container = helpers$1._getParentNode(domNode);
  15209. if (!container) {
  15210. return domNode.clientWidth;
  15211. }
  15212. var clientWidth = container.clientWidth;
  15213. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  15214. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  15215. var w = clientWidth - paddingLeft - paddingRight;
  15216. var cw = helpers$1.getConstraintWidth(domNode);
  15217. return isNaN(cw) ? w : Math.min(w, cw);
  15218. };
  15219. helpers$1.getMaximumHeight = function(domNode) {
  15220. var container = helpers$1._getParentNode(domNode);
  15221. if (!container) {
  15222. return domNode.clientHeight;
  15223. }
  15224. var clientHeight = container.clientHeight;
  15225. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  15226. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  15227. var h = clientHeight - paddingTop - paddingBottom;
  15228. var ch = helpers$1.getConstraintHeight(domNode);
  15229. return isNaN(ch) ? h : Math.min(h, ch);
  15230. };
  15231. helpers$1.getStyle = function(el, property) {
  15232. return el.currentStyle ?
  15233. el.currentStyle[property] :
  15234. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  15235. };
  15236. helpers$1.retinaScale = function(chart, forceRatio) {
  15237. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  15238. if (pixelRatio === 1) {
  15239. return;
  15240. }
  15241. var canvas = chart.canvas;
  15242. var height = chart.height;
  15243. var width = chart.width;
  15244. canvas.height = height * pixelRatio;
  15245. canvas.width = width * pixelRatio;
  15246. chart.ctx.scale(pixelRatio, pixelRatio);
  15247. // If no style has been set on the canvas, the render size is used as display size,
  15248. // making the chart visually bigger, so let's enforce it to the "correct" values.
  15249. // See https://github.com/chartjs/Chart.js/issues/3575
  15250. if (!canvas.style.height && !canvas.style.width) {
  15251. canvas.style.height = height + 'px';
  15252. canvas.style.width = width + 'px';
  15253. }
  15254. };
  15255. // -- Canvas methods
  15256. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  15257. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  15258. };
  15259. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  15260. cache = cache || {};
  15261. var data = cache.data = cache.data || {};
  15262. var gc = cache.garbageCollect = cache.garbageCollect || [];
  15263. if (cache.font !== font) {
  15264. data = cache.data = {};
  15265. gc = cache.garbageCollect = [];
  15266. cache.font = font;
  15267. }
  15268. ctx.font = font;
  15269. var longest = 0;
  15270. var ilen = arrayOfThings.length;
  15271. var i, j, jlen, thing, nestedThing;
  15272. for (i = 0; i < ilen; i++) {
  15273. thing = arrayOfThings[i];
  15274. // Undefined strings and arrays should not be measured
  15275. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  15276. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  15277. } else if (helpers$1.isArray(thing)) {
  15278. // if it is an array lets measure each element
  15279. // to do maybe simplify this function a bit so we can do this more recursively?
  15280. for (j = 0, jlen = thing.length; j < jlen; j++) {
  15281. nestedThing = thing[j];
  15282. // Undefined strings and arrays should not be measured
  15283. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  15284. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  15285. }
  15286. }
  15287. }
  15288. }
  15289. var gcLen = gc.length / 2;
  15290. if (gcLen > arrayOfThings.length) {
  15291. for (i = 0; i < gcLen; i++) {
  15292. delete data[gc[i]];
  15293. }
  15294. gc.splice(0, gcLen);
  15295. }
  15296. return longest;
  15297. };
  15298. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  15299. var textWidth = data[string];
  15300. if (!textWidth) {
  15301. textWidth = data[string] = ctx.measureText(string).width;
  15302. gc.push(string);
  15303. }
  15304. if (textWidth > longest) {
  15305. longest = textWidth;
  15306. }
  15307. return longest;
  15308. };
  15309. /**
  15310. * @deprecated
  15311. */
  15312. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  15313. var numberOfLines = 1;
  15314. helpers$1.each(arrayOfThings, function(thing) {
  15315. if (helpers$1.isArray(thing)) {
  15316. if (thing.length > numberOfLines) {
  15317. numberOfLines = thing.length;
  15318. }
  15319. }
  15320. });
  15321. return numberOfLines;
  15322. };
  15323. helpers$1.color = !chartjsColor ?
  15324. function(value) {
  15325. console.error('Color.js not found!');
  15326. return value;
  15327. } :
  15328. function(value) {
  15329. /* global CanvasGradient */
  15330. if (value instanceof CanvasGradient) {
  15331. value = core_defaults.global.defaultColor;
  15332. }
  15333. return chartjsColor(value);
  15334. };
  15335. helpers$1.getHoverColor = function(colorValue) {
  15336. /* global CanvasPattern */
  15337. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  15338. colorValue :
  15339. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  15340. };
  15341. };
  15342. function abstract() {
  15343. throw new Error(
  15344. 'This method is not implemented: either no adapter can ' +
  15345. 'be found or an incomplete integration was provided.'
  15346. );
  15347. }
  15348. /**
  15349. * Date adapter (current used by the time scale)
  15350. * @namespace Chart._adapters._date
  15351. * @memberof Chart._adapters
  15352. * @private
  15353. */
  15354. /**
  15355. * Currently supported unit string values.
  15356. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  15357. * @memberof Chart._adapters._date
  15358. * @name Unit
  15359. */
  15360. /**
  15361. * @class
  15362. */
  15363. function DateAdapter(options) {
  15364. this.options = options || {};
  15365. }
  15366. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  15367. /**
  15368. * Returns a map of time formats for the supported formatting units defined
  15369. * in Unit as well as 'datetime' representing a detailed date/time string.
  15370. * @returns {{string: string}}
  15371. */
  15372. formats: abstract,
  15373. /**
  15374. * Parses the given `value` and return the associated timestamp.
  15375. * @param {any} value - the value to parse (usually comes from the data)
  15376. * @param {string} [format] - the expected data format
  15377. * @returns {(number|null)}
  15378. * @function
  15379. */
  15380. parse: abstract,
  15381. /**
  15382. * Returns the formatted date in the specified `format` for a given `timestamp`.
  15383. * @param {number} timestamp - the timestamp to format
  15384. * @param {string} format - the date/time token
  15385. * @return {string}
  15386. * @function
  15387. */
  15388. format: abstract,
  15389. /**
  15390. * Adds the specified `amount` of `unit` to the given `timestamp`.
  15391. * @param {number} timestamp - the input timestamp
  15392. * @param {number} amount - the amount to add
  15393. * @param {Unit} unit - the unit as string
  15394. * @return {number}
  15395. * @function
  15396. */
  15397. add: abstract,
  15398. /**
  15399. * Returns the number of `unit` between the given timestamps.
  15400. * @param {number} max - the input timestamp (reference)
  15401. * @param {number} min - the timestamp to substract
  15402. * @param {Unit} unit - the unit as string
  15403. * @return {number}
  15404. * @function
  15405. */
  15406. diff: abstract,
  15407. /**
  15408. * Returns start of `unit` for the given `timestamp`.
  15409. * @param {number} timestamp - the input timestamp
  15410. * @param {Unit} unit - the unit as string
  15411. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  15412. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  15413. * @function
  15414. */
  15415. startOf: abstract,
  15416. /**
  15417. * Returns end of `unit` for the given `timestamp`.
  15418. * @param {number} timestamp - the input timestamp
  15419. * @param {Unit} unit - the unit as string
  15420. * @function
  15421. */
  15422. endOf: abstract,
  15423. // DEPRECATIONS
  15424. /**
  15425. * Provided for backward compatibility for scale.getValueForPixel(),
  15426. * this method should be overridden only by the moment adapter.
  15427. * @deprecated since version 2.8.0
  15428. * @todo remove at version 3
  15429. * @private
  15430. */
  15431. _create: function(value) {
  15432. return value;
  15433. }
  15434. });
  15435. DateAdapter.override = function(members) {
  15436. helpers$1.extend(DateAdapter.prototype, members);
  15437. };
  15438. var _date = DateAdapter;
  15439. var core_adapters = {
  15440. _date: _date
  15441. };
  15442. /**
  15443. * Namespace to hold static tick generation functions
  15444. * @namespace Chart.Ticks
  15445. */
  15446. var core_ticks = {
  15447. /**
  15448. * Namespace to hold formatters for different types of ticks
  15449. * @namespace Chart.Ticks.formatters
  15450. */
  15451. formatters: {
  15452. /**
  15453. * Formatter for value labels
  15454. * @method Chart.Ticks.formatters.values
  15455. * @param value the value to display
  15456. * @return {string|string[]} the label to display
  15457. */
  15458. values: function(value) {
  15459. return helpers$1.isArray(value) ? value : '' + value;
  15460. },
  15461. /**
  15462. * Formatter for linear numeric ticks
  15463. * @method Chart.Ticks.formatters.linear
  15464. * @param tickValue {number} the value to be formatted
  15465. * @param index {number} the position of the tickValue parameter in the ticks array
  15466. * @param ticks {number[]} the list of ticks being converted
  15467. * @return {string} string representation of the tickValue parameter
  15468. */
  15469. linear: function(tickValue, index, ticks) {
  15470. // If we have lots of ticks, don't use the ones
  15471. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  15472. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  15473. if (Math.abs(delta) > 1) {
  15474. if (tickValue !== Math.floor(tickValue)) {
  15475. // not an integer
  15476. delta = tickValue - Math.floor(tickValue);
  15477. }
  15478. }
  15479. var logDelta = helpers$1.log10(Math.abs(delta));
  15480. var tickString = '';
  15481. if (tickValue !== 0) {
  15482. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  15483. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  15484. var logTick = helpers$1.log10(Math.abs(tickValue));
  15485. var numExponential = Math.floor(logTick) - Math.floor(logDelta);
  15486. numExponential = Math.max(Math.min(numExponential, 20), 0);
  15487. tickString = tickValue.toExponential(numExponential);
  15488. } else {
  15489. var numDecimal = -1 * Math.floor(logDelta);
  15490. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  15491. tickString = tickValue.toFixed(numDecimal);
  15492. }
  15493. } else {
  15494. tickString = '0'; // never show decimal places for 0
  15495. }
  15496. return tickString;
  15497. },
  15498. logarithmic: function(tickValue, index, ticks) {
  15499. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  15500. if (tickValue === 0) {
  15501. return '0';
  15502. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  15503. return tickValue.toExponential();
  15504. }
  15505. return '';
  15506. }
  15507. }
  15508. };
  15509. var isArray = helpers$1.isArray;
  15510. var isNullOrUndef = helpers$1.isNullOrUndef;
  15511. var valueOrDefault$a = helpers$1.valueOrDefault;
  15512. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  15513. core_defaults._set('scale', {
  15514. display: true,
  15515. position: 'left',
  15516. offset: false,
  15517. // grid line settings
  15518. gridLines: {
  15519. display: true,
  15520. color: 'rgba(0,0,0,0.1)',
  15521. lineWidth: 1,
  15522. drawBorder: true,
  15523. drawOnChartArea: true,
  15524. drawTicks: true,
  15525. tickMarkLength: 10,
  15526. zeroLineWidth: 1,
  15527. zeroLineColor: 'rgba(0,0,0,0.25)',
  15528. zeroLineBorderDash: [],
  15529. zeroLineBorderDashOffset: 0.0,
  15530. offsetGridLines: false,
  15531. borderDash: [],
  15532. borderDashOffset: 0.0
  15533. },
  15534. // scale label
  15535. scaleLabel: {
  15536. // display property
  15537. display: false,
  15538. // actual label
  15539. labelString: '',
  15540. // top/bottom padding
  15541. padding: {
  15542. top: 4,
  15543. bottom: 4
  15544. }
  15545. },
  15546. // label settings
  15547. ticks: {
  15548. beginAtZero: false,
  15549. minRotation: 0,
  15550. maxRotation: 50,
  15551. mirror: false,
  15552. padding: 0,
  15553. reverse: false,
  15554. display: true,
  15555. autoSkip: true,
  15556. autoSkipPadding: 0,
  15557. labelOffset: 0,
  15558. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  15559. callback: core_ticks.formatters.values,
  15560. minor: {},
  15561. major: {}
  15562. }
  15563. });
  15564. /** Returns a new array containing numItems from arr */
  15565. function sample(arr, numItems) {
  15566. var result = [];
  15567. var increment = arr.length / numItems;
  15568. var i = 0;
  15569. var len = arr.length;
  15570. for (; i < len; i += increment) {
  15571. result.push(arr[Math.floor(i)]);
  15572. }
  15573. return result;
  15574. }
  15575. function getPixelForGridLine(scale, index, offsetGridLines) {
  15576. var length = scale.getTicks().length;
  15577. var validIndex = Math.min(index, length - 1);
  15578. var lineValue = scale.getPixelForTick(validIndex);
  15579. var start = scale._startPixel;
  15580. var end = scale._endPixel;
  15581. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  15582. var offset;
  15583. if (offsetGridLines) {
  15584. if (length === 1) {
  15585. offset = Math.max(lineValue - start, end - lineValue);
  15586. } else if (index === 0) {
  15587. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  15588. } else {
  15589. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  15590. }
  15591. lineValue += validIndex < index ? offset : -offset;
  15592. // Return undefined if the pixel is out of the range
  15593. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  15594. return;
  15595. }
  15596. }
  15597. return lineValue;
  15598. }
  15599. function garbageCollect(caches, length) {
  15600. helpers$1.each(caches, function(cache) {
  15601. var gc = cache.gc;
  15602. var gcLen = gc.length / 2;
  15603. var i;
  15604. if (gcLen > length) {
  15605. for (i = 0; i < gcLen; ++i) {
  15606. delete cache.data[gc[i]];
  15607. }
  15608. gc.splice(0, gcLen);
  15609. }
  15610. });
  15611. }
  15612. /**
  15613. * Returns {width, height, offset} objects for the first, last, widest, highest tick
  15614. * labels where offset indicates the anchor point offset from the top in pixels.
  15615. */
  15616. function computeLabelSizes(ctx, tickFonts, ticks, caches) {
  15617. var length = ticks.length;
  15618. var widths = [];
  15619. var heights = [];
  15620. var offsets = [];
  15621. var widestLabelSize = 0;
  15622. var highestLabelSize = 0;
  15623. var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
  15624. for (i = 0; i < length; ++i) {
  15625. label = ticks[i].label;
  15626. tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
  15627. ctx.font = fontString = tickFont.string;
  15628. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  15629. lineHeight = tickFont.lineHeight;
  15630. width = height = 0;
  15631. // Undefined labels and arrays should not be measured
  15632. if (!isNullOrUndef(label) && !isArray(label)) {
  15633. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);
  15634. height = lineHeight;
  15635. } else if (isArray(label)) {
  15636. // if it is an array let's measure each element
  15637. for (j = 0, jlen = label.length; j < jlen; ++j) {
  15638. nestedLabel = label[j];
  15639. // Undefined labels and arrays should not be measured
  15640. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  15641. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  15642. height += lineHeight;
  15643. }
  15644. }
  15645. }
  15646. widths.push(width);
  15647. heights.push(height);
  15648. offsets.push(lineHeight / 2);
  15649. widestLabelSize = Math.max(width, widestLabelSize);
  15650. highestLabelSize = Math.max(height, highestLabelSize);
  15651. }
  15652. garbageCollect(caches, length);
  15653. widest = widths.indexOf(widestLabelSize);
  15654. highest = heights.indexOf(highestLabelSize);
  15655. function valueAt(idx) {
  15656. return {
  15657. width: widths[idx] || 0,
  15658. height: heights[idx] || 0,
  15659. offset: offsets[idx] || 0
  15660. };
  15661. }
  15662. return {
  15663. first: valueAt(0),
  15664. last: valueAt(length - 1),
  15665. widest: valueAt(widest),
  15666. highest: valueAt(highest)
  15667. };
  15668. }
  15669. function getTickMarkLength(options) {
  15670. return options.drawTicks ? options.tickMarkLength : 0;
  15671. }
  15672. function getScaleLabelHeight(options) {
  15673. var font, padding;
  15674. if (!options.display) {
  15675. return 0;
  15676. }
  15677. font = helpers$1.options._parseFont(options);
  15678. padding = helpers$1.options.toPadding(options.padding);
  15679. return font.lineHeight + padding.height;
  15680. }
  15681. function parseFontOptions(options, nestedOpts) {
  15682. return helpers$1.extend(helpers$1.options._parseFont({
  15683. fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),
  15684. fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),
  15685. fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),
  15686. lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)
  15687. }), {
  15688. color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])
  15689. });
  15690. }
  15691. function parseTickFontOptions(options) {
  15692. var minor = parseFontOptions(options, options.minor);
  15693. var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
  15694. return {minor: minor, major: major};
  15695. }
  15696. function nonSkipped(ticksToFilter) {
  15697. var filtered = [];
  15698. var item, index, len;
  15699. for (index = 0, len = ticksToFilter.length; index < len; ++index) {
  15700. item = ticksToFilter[index];
  15701. if (typeof item._index !== 'undefined') {
  15702. filtered.push(item);
  15703. }
  15704. }
  15705. return filtered;
  15706. }
  15707. function getEvenSpacing(arr) {
  15708. var len = arr.length;
  15709. var i, diff;
  15710. if (len < 2) {
  15711. return false;
  15712. }
  15713. for (diff = arr[0], i = 1; i < len; ++i) {
  15714. if (arr[i] - arr[i - 1] !== diff) {
  15715. return false;
  15716. }
  15717. }
  15718. return diff;
  15719. }
  15720. function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
  15721. var evenMajorSpacing = getEvenSpacing(majorIndices);
  15722. var spacing = (ticks.length - 1) / ticksLimit;
  15723. var factors, factor, i, ilen;
  15724. // If the major ticks are evenly spaced apart, place the minor ticks
  15725. // so that they divide the major ticks into even chunks
  15726. if (!evenMajorSpacing) {
  15727. return Math.max(spacing, 1);
  15728. }
  15729. factors = helpers$1.math._factorize(evenMajorSpacing);
  15730. for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
  15731. factor = factors[i];
  15732. if (factor > spacing) {
  15733. return factor;
  15734. }
  15735. }
  15736. return Math.max(spacing, 1);
  15737. }
  15738. function getMajorIndices(ticks) {
  15739. var result = [];
  15740. var i, ilen;
  15741. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  15742. if (ticks[i].major) {
  15743. result.push(i);
  15744. }
  15745. }
  15746. return result;
  15747. }
  15748. function skipMajors(ticks, majorIndices, spacing) {
  15749. var count = 0;
  15750. var next = majorIndices[0];
  15751. var i, tick;
  15752. spacing = Math.ceil(spacing);
  15753. for (i = 0; i < ticks.length; i++) {
  15754. tick = ticks[i];
  15755. if (i === next) {
  15756. tick._index = i;
  15757. count++;
  15758. next = majorIndices[count * spacing];
  15759. } else {
  15760. delete tick.label;
  15761. }
  15762. }
  15763. }
  15764. function skip(ticks, spacing, majorStart, majorEnd) {
  15765. var start = valueOrDefault$a(majorStart, 0);
  15766. var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);
  15767. var count = 0;
  15768. var length, i, tick, next;
  15769. spacing = Math.ceil(spacing);
  15770. if (majorEnd) {
  15771. length = majorEnd - majorStart;
  15772. spacing = length / Math.floor(length / spacing);
  15773. }
  15774. next = start;
  15775. while (next < 0) {
  15776. count++;
  15777. next = Math.round(start + count * spacing);
  15778. }
  15779. for (i = Math.max(start, 0); i < end; i++) {
  15780. tick = ticks[i];
  15781. if (i === next) {
  15782. tick._index = i;
  15783. count++;
  15784. next = Math.round(start + count * spacing);
  15785. } else {
  15786. delete tick.label;
  15787. }
  15788. }
  15789. }
  15790. var Scale = core_element.extend({
  15791. zeroLineIndex: 0,
  15792. /**
  15793. * Get the padding needed for the scale
  15794. * @method getPadding
  15795. * @private
  15796. * @returns {Padding} the necessary padding
  15797. */
  15798. getPadding: function() {
  15799. var me = this;
  15800. return {
  15801. left: me.paddingLeft || 0,
  15802. top: me.paddingTop || 0,
  15803. right: me.paddingRight || 0,
  15804. bottom: me.paddingBottom || 0
  15805. };
  15806. },
  15807. /**
  15808. * Returns the scale tick objects ({label, major})
  15809. * @since 2.7
  15810. */
  15811. getTicks: function() {
  15812. return this._ticks;
  15813. },
  15814. /**
  15815. * @private
  15816. */
  15817. _getLabels: function() {
  15818. var data = this.chart.data;
  15819. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  15820. },
  15821. // These methods are ordered by lifecyle. Utilities then follow.
  15822. // Any function defined here is inherited by all scale types.
  15823. // Any function can be extended by the scale type
  15824. /**
  15825. * Provided for backward compatibility, not available anymore
  15826. * @function Chart.Scale.mergeTicksOptions
  15827. * @deprecated since version 2.8.0
  15828. * @todo remove at version 3
  15829. */
  15830. mergeTicksOptions: function() {
  15831. // noop
  15832. },
  15833. beforeUpdate: function() {
  15834. helpers$1.callback(this.options.beforeUpdate, [this]);
  15835. },
  15836. /**
  15837. * @param {number} maxWidth - the max width in pixels
  15838. * @param {number} maxHeight - the max height in pixels
  15839. * @param {object} margins - the space between the edge of the other scales and edge of the chart
  15840. * This space comes from two sources:
  15841. * - padding - space that's required to show the labels at the edges of the scale
  15842. * - thickness of scales or legends in another orientation
  15843. */
  15844. update: function(maxWidth, maxHeight, margins) {
  15845. var me = this;
  15846. var tickOpts = me.options.ticks;
  15847. var sampleSize = tickOpts.sampleSize;
  15848. var i, ilen, labels, ticks, samplingEnabled;
  15849. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  15850. me.beforeUpdate();
  15851. // Absorb the master measurements
  15852. me.maxWidth = maxWidth;
  15853. me.maxHeight = maxHeight;
  15854. me.margins = helpers$1.extend({
  15855. left: 0,
  15856. right: 0,
  15857. top: 0,
  15858. bottom: 0
  15859. }, margins);
  15860. me._ticks = null;
  15861. me.ticks = null;
  15862. me._labelSizes = null;
  15863. me._maxLabelLines = 0;
  15864. me.longestLabelWidth = 0;
  15865. me.longestTextCache = me.longestTextCache || {};
  15866. me._gridLineItems = null;
  15867. me._labelItems = null;
  15868. // Dimensions
  15869. me.beforeSetDimensions();
  15870. me.setDimensions();
  15871. me.afterSetDimensions();
  15872. // Data min/max
  15873. me.beforeDataLimits();
  15874. me.determineDataLimits();
  15875. me.afterDataLimits();
  15876. // Ticks - `this.ticks` is now DEPRECATED!
  15877. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  15878. // and must not be accessed directly from outside this class. `this.ticks` being
  15879. // around for long time and not marked as private, we can't change its structure
  15880. // without unexpected breaking changes. If you need to access the scale ticks,
  15881. // use scale.getTicks() instead.
  15882. me.beforeBuildTicks();
  15883. // New implementations should return an array of objects but for BACKWARD COMPAT,
  15884. // we still support no return (`this.ticks` internally set by calling this method).
  15885. ticks = me.buildTicks() || [];
  15886. // Allow modification of ticks in callback.
  15887. ticks = me.afterBuildTicks(ticks) || ticks;
  15888. // Ensure ticks contains ticks in new tick format
  15889. if ((!ticks || !ticks.length) && me.ticks) {
  15890. ticks = [];
  15891. for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
  15892. ticks.push({
  15893. value: me.ticks[i],
  15894. major: false
  15895. });
  15896. }
  15897. }
  15898. me._ticks = ticks;
  15899. // Compute tick rotation and fit using a sampled subset of labels
  15900. // We generally don't need to compute the size of every single label for determining scale size
  15901. samplingEnabled = sampleSize < ticks.length;
  15902. labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);
  15903. // _configure is called twice, once here, once from core.controller.updateLayout.
  15904. // Here we haven't been positioned yet, but dimensions are correct.
  15905. // Variables set in _configure are needed for calculateTickRotation, and
  15906. // it's ok that coordinates are not correct there, only dimensions matter.
  15907. me._configure();
  15908. // Tick Rotation
  15909. me.beforeCalculateTickRotation();
  15910. me.calculateTickRotation();
  15911. me.afterCalculateTickRotation();
  15912. me.beforeFit();
  15913. me.fit();
  15914. me.afterFit();
  15915. // Auto-skip
  15916. me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;
  15917. if (samplingEnabled) {
  15918. // Generate labels using all non-skipped ticks
  15919. labels = me._convertTicksToLabels(me._ticksToDraw);
  15920. }
  15921. me.ticks = labels; // BACKWARD COMPATIBILITY
  15922. // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
  15923. me.afterUpdate();
  15924. // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
  15925. // make maxWidth and maxHeight private
  15926. return me.minSize;
  15927. },
  15928. /**
  15929. * @private
  15930. */
  15931. _configure: function() {
  15932. var me = this;
  15933. var reversePixels = me.options.ticks.reverse;
  15934. var startPixel, endPixel;
  15935. if (me.isHorizontal()) {
  15936. startPixel = me.left;
  15937. endPixel = me.right;
  15938. } else {
  15939. startPixel = me.top;
  15940. endPixel = me.bottom;
  15941. // by default vertical scales are from bottom to top, so pixels are reversed
  15942. reversePixels = !reversePixels;
  15943. }
  15944. me._startPixel = startPixel;
  15945. me._endPixel = endPixel;
  15946. me._reversePixels = reversePixels;
  15947. me._length = endPixel - startPixel;
  15948. },
  15949. afterUpdate: function() {
  15950. helpers$1.callback(this.options.afterUpdate, [this]);
  15951. },
  15952. //
  15953. beforeSetDimensions: function() {
  15954. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  15955. },
  15956. setDimensions: function() {
  15957. var me = this;
  15958. // Set the unconstrained dimension before label rotation
  15959. if (me.isHorizontal()) {
  15960. // Reset position before calculating rotation
  15961. me.width = me.maxWidth;
  15962. me.left = 0;
  15963. me.right = me.width;
  15964. } else {
  15965. me.height = me.maxHeight;
  15966. // Reset position before calculating rotation
  15967. me.top = 0;
  15968. me.bottom = me.height;
  15969. }
  15970. // Reset padding
  15971. me.paddingLeft = 0;
  15972. me.paddingTop = 0;
  15973. me.paddingRight = 0;
  15974. me.paddingBottom = 0;
  15975. },
  15976. afterSetDimensions: function() {
  15977. helpers$1.callback(this.options.afterSetDimensions, [this]);
  15978. },
  15979. // Data limits
  15980. beforeDataLimits: function() {
  15981. helpers$1.callback(this.options.beforeDataLimits, [this]);
  15982. },
  15983. determineDataLimits: helpers$1.noop,
  15984. afterDataLimits: function() {
  15985. helpers$1.callback(this.options.afterDataLimits, [this]);
  15986. },
  15987. //
  15988. beforeBuildTicks: function() {
  15989. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  15990. },
  15991. buildTicks: helpers$1.noop,
  15992. afterBuildTicks: function(ticks) {
  15993. var me = this;
  15994. // ticks is empty for old axis implementations here
  15995. if (isArray(ticks) && ticks.length) {
  15996. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  15997. }
  15998. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  15999. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  16000. return ticks;
  16001. },
  16002. beforeTickToLabelConversion: function() {
  16003. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  16004. },
  16005. convertTicksToLabels: function() {
  16006. var me = this;
  16007. // Convert ticks to strings
  16008. var tickOpts = me.options.ticks;
  16009. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  16010. },
  16011. afterTickToLabelConversion: function() {
  16012. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  16013. },
  16014. //
  16015. beforeCalculateTickRotation: function() {
  16016. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  16017. },
  16018. calculateTickRotation: function() {
  16019. var me = this;
  16020. var options = me.options;
  16021. var tickOpts = options.ticks;
  16022. var numTicks = me.getTicks().length;
  16023. var minRotation = tickOpts.minRotation || 0;
  16024. var maxRotation = tickOpts.maxRotation;
  16025. var labelRotation = minRotation;
  16026. var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
  16027. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  16028. me.labelRotation = minRotation;
  16029. return;
  16030. }
  16031. labelSizes = me._getLabelSizes();
  16032. maxLabelWidth = labelSizes.widest.width;
  16033. maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
  16034. // Estimate the width of each grid based on the canvas width, the maximum
  16035. // label width and the number of tick intervals
  16036. maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
  16037. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  16038. // Allow 3 pixels x2 padding either side for label readability
  16039. if (maxLabelWidth + 6 > tickWidth) {
  16040. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  16041. maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
  16042. - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
  16043. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  16044. labelRotation = helpers$1.toDegrees(Math.min(
  16045. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  16046. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  16047. ));
  16048. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  16049. }
  16050. me.labelRotation = labelRotation;
  16051. },
  16052. afterCalculateTickRotation: function() {
  16053. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  16054. },
  16055. //
  16056. beforeFit: function() {
  16057. helpers$1.callback(this.options.beforeFit, [this]);
  16058. },
  16059. fit: function() {
  16060. var me = this;
  16061. // Reset
  16062. var minSize = me.minSize = {
  16063. width: 0,
  16064. height: 0
  16065. };
  16066. var chart = me.chart;
  16067. var opts = me.options;
  16068. var tickOpts = opts.ticks;
  16069. var scaleLabelOpts = opts.scaleLabel;
  16070. var gridLineOpts = opts.gridLines;
  16071. var display = me._isVisible();
  16072. var isBottom = opts.position === 'bottom';
  16073. var isHorizontal = me.isHorizontal();
  16074. // Width
  16075. if (isHorizontal) {
  16076. minSize.width = me.maxWidth;
  16077. } else if (display) {
  16078. minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  16079. }
  16080. // height
  16081. if (!isHorizontal) {
  16082. minSize.height = me.maxHeight; // fill all the height
  16083. } else if (display) {
  16084. minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  16085. }
  16086. // Don't bother fitting the ticks if we are not showing the labels
  16087. if (tickOpts.display && display) {
  16088. var tickFonts = parseTickFontOptions(tickOpts);
  16089. var labelSizes = me._getLabelSizes();
  16090. var firstLabelSize = labelSizes.first;
  16091. var lastLabelSize = labelSizes.last;
  16092. var widestLabelSize = labelSizes.widest;
  16093. var highestLabelSize = labelSizes.highest;
  16094. var lineSpace = tickFonts.minor.lineHeight * 0.4;
  16095. var tickPadding = tickOpts.padding;
  16096. if (isHorizontal) {
  16097. // A horizontal axis is more constrained by the height.
  16098. var isRotated = me.labelRotation !== 0;
  16099. var angleRadians = helpers$1.toRadians(me.labelRotation);
  16100. var cosRotation = Math.cos(angleRadians);
  16101. var sinRotation = Math.sin(angleRadians);
  16102. var labelHeight = sinRotation * widestLabelSize.width
  16103. + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
  16104. + (isRotated ? 0 : lineSpace); // padding
  16105. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  16106. var offsetLeft = me.getPixelForTick(0) - me.left;
  16107. var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
  16108. var paddingLeft, paddingRight;
  16109. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  16110. // which means that the right padding is dominated by the font height
  16111. if (isRotated) {
  16112. paddingLeft = isBottom ?
  16113. cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
  16114. sinRotation * (firstLabelSize.height - firstLabelSize.offset);
  16115. paddingRight = isBottom ?
  16116. sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
  16117. cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
  16118. } else {
  16119. paddingLeft = firstLabelSize.width / 2;
  16120. paddingRight = lastLabelSize.width / 2;
  16121. }
  16122. // Adjust padding taking into account changes in offsets
  16123. // and add 3 px to move away from canvas edges
  16124. me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
  16125. me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
  16126. } else {
  16127. // A vertical axis is more constrained by the width. Labels are the
  16128. // dominant factor here, so get that length first and account for padding
  16129. var labelWidth = tickOpts.mirror ? 0 :
  16130. // use lineSpace for consistency with horizontal axis
  16131. // tickPadding is not implemented for horizontal
  16132. widestLabelSize.width + tickPadding + lineSpace;
  16133. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
  16134. me.paddingTop = firstLabelSize.height / 2;
  16135. me.paddingBottom = lastLabelSize.height / 2;
  16136. }
  16137. }
  16138. me.handleMargins();
  16139. if (isHorizontal) {
  16140. me.width = me._length = chart.width - me.margins.left - me.margins.right;
  16141. me.height = minSize.height;
  16142. } else {
  16143. me.width = minSize.width;
  16144. me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
  16145. }
  16146. },
  16147. /**
  16148. * Handle margins and padding interactions
  16149. * @private
  16150. */
  16151. handleMargins: function() {
  16152. var me = this;
  16153. if (me.margins) {
  16154. me.margins.left = Math.max(me.paddingLeft, me.margins.left);
  16155. me.margins.top = Math.max(me.paddingTop, me.margins.top);
  16156. me.margins.right = Math.max(me.paddingRight, me.margins.right);
  16157. me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
  16158. }
  16159. },
  16160. afterFit: function() {
  16161. helpers$1.callback(this.options.afterFit, [this]);
  16162. },
  16163. // Shared Methods
  16164. isHorizontal: function() {
  16165. var pos = this.options.position;
  16166. return pos === 'top' || pos === 'bottom';
  16167. },
  16168. isFullWidth: function() {
  16169. return this.options.fullWidth;
  16170. },
  16171. // 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
  16172. getRightValue: function(rawValue) {
  16173. // Null and undefined values first
  16174. if (isNullOrUndef(rawValue)) {
  16175. return NaN;
  16176. }
  16177. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  16178. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  16179. return NaN;
  16180. }
  16181. // If it is in fact an object, dive in one more level
  16182. if (rawValue) {
  16183. if (this.isHorizontal()) {
  16184. if (rawValue.x !== undefined) {
  16185. return this.getRightValue(rawValue.x);
  16186. }
  16187. } else if (rawValue.y !== undefined) {
  16188. return this.getRightValue(rawValue.y);
  16189. }
  16190. }
  16191. // Value is good, return it
  16192. return rawValue;
  16193. },
  16194. _convertTicksToLabels: function(ticks) {
  16195. var me = this;
  16196. var labels, i, ilen;
  16197. me.ticks = ticks.map(function(tick) {
  16198. return tick.value;
  16199. });
  16200. me.beforeTickToLabelConversion();
  16201. // New implementations should return the formatted tick labels but for BACKWARD
  16202. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  16203. // this method and supposed to contain only string values).
  16204. labels = me.convertTicksToLabels(ticks) || me.ticks;
  16205. me.afterTickToLabelConversion();
  16206. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  16207. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  16208. ticks[i].label = labels[i];
  16209. }
  16210. return labels;
  16211. },
  16212. /**
  16213. * @private
  16214. */
  16215. _getLabelSizes: function() {
  16216. var me = this;
  16217. var labelSizes = me._labelSizes;
  16218. if (!labelSizes) {
  16219. me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
  16220. me.longestLabelWidth = labelSizes.widest.width;
  16221. }
  16222. return labelSizes;
  16223. },
  16224. /**
  16225. * @private
  16226. */
  16227. _parseValue: function(value) {
  16228. var start, end, min, max;
  16229. if (isArray(value)) {
  16230. start = +this.getRightValue(value[0]);
  16231. end = +this.getRightValue(value[1]);
  16232. min = Math.min(start, end);
  16233. max = Math.max(start, end);
  16234. } else {
  16235. value = +this.getRightValue(value);
  16236. start = undefined;
  16237. end = value;
  16238. min = value;
  16239. max = value;
  16240. }
  16241. return {
  16242. min: min,
  16243. max: max,
  16244. start: start,
  16245. end: end
  16246. };
  16247. },
  16248. /**
  16249. * @private
  16250. */
  16251. _getScaleLabel: function(rawValue) {
  16252. var v = this._parseValue(rawValue);
  16253. if (v.start !== undefined) {
  16254. return '[' + v.start + ', ' + v.end + ']';
  16255. }
  16256. return +this.getRightValue(rawValue);
  16257. },
  16258. /**
  16259. * Used to get the value to display in the tooltip for the data at the given index
  16260. * @param index
  16261. * @param datasetIndex
  16262. */
  16263. getLabelForIndex: helpers$1.noop,
  16264. /**
  16265. * Returns the location of the given data point. Value can either be an index or a numerical value
  16266. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16267. * @param value
  16268. * @param index
  16269. * @param datasetIndex
  16270. */
  16271. getPixelForValue: helpers$1.noop,
  16272. /**
  16273. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  16274. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16275. * @param pixel
  16276. */
  16277. getValueForPixel: helpers$1.noop,
  16278. /**
  16279. * Returns the location of the tick at the given index
  16280. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16281. */
  16282. getPixelForTick: function(index) {
  16283. var me = this;
  16284. var offset = me.options.offset;
  16285. var numTicks = me._ticks.length;
  16286. var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
  16287. return index < 0 || index > numTicks - 1
  16288. ? null
  16289. : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
  16290. },
  16291. /**
  16292. * Utility for getting the pixel location of a percentage of scale
  16293. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16294. */
  16295. getPixelForDecimal: function(decimal) {
  16296. var me = this;
  16297. if (me._reversePixels) {
  16298. decimal = 1 - decimal;
  16299. }
  16300. return me._startPixel + decimal * me._length;
  16301. },
  16302. getDecimalForPixel: function(pixel) {
  16303. var decimal = (pixel - this._startPixel) / this._length;
  16304. return this._reversePixels ? 1 - decimal : decimal;
  16305. },
  16306. /**
  16307. * Returns the pixel for the minimum chart value
  16308. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16309. */
  16310. getBasePixel: function() {
  16311. return this.getPixelForValue(this.getBaseValue());
  16312. },
  16313. getBaseValue: function() {
  16314. var me = this;
  16315. var min = me.min;
  16316. var max = me.max;
  16317. return me.beginAtZero ? 0 :
  16318. min < 0 && max < 0 ? max :
  16319. min > 0 && max > 0 ? min :
  16320. 0;
  16321. },
  16322. /**
  16323. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  16324. * @private
  16325. */
  16326. _autoSkip: function(ticks) {
  16327. var me = this;
  16328. var tickOpts = me.options.ticks;
  16329. var axisLength = me._length;
  16330. var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;
  16331. var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  16332. var numMajorIndices = majorIndices.length;
  16333. var first = majorIndices[0];
  16334. var last = majorIndices[numMajorIndices - 1];
  16335. var i, ilen, spacing, avgMajorSpacing;
  16336. // If there are too many major ticks to display them all
  16337. if (numMajorIndices > ticksLimit) {
  16338. skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);
  16339. return nonSkipped(ticks);
  16340. }
  16341. spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
  16342. if (numMajorIndices > 0) {
  16343. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  16344. skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);
  16345. }
  16346. avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;
  16347. skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  16348. skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  16349. return nonSkipped(ticks);
  16350. }
  16351. skip(ticks, spacing);
  16352. return nonSkipped(ticks);
  16353. },
  16354. /**
  16355. * @private
  16356. */
  16357. _tickSize: function() {
  16358. var me = this;
  16359. var optionTicks = me.options.ticks;
  16360. // Calculate space needed by label in axis direction.
  16361. var rot = helpers$1.toRadians(me.labelRotation);
  16362. var cos = Math.abs(Math.cos(rot));
  16363. var sin = Math.abs(Math.sin(rot));
  16364. var labelSizes = me._getLabelSizes();
  16365. var padding = optionTicks.autoSkipPadding || 0;
  16366. var w = labelSizes ? labelSizes.widest.width + padding : 0;
  16367. var h = labelSizes ? labelSizes.highest.height + padding : 0;
  16368. // Calculate space needed for 1 tick in axis direction.
  16369. return me.isHorizontal()
  16370. ? h * cos > w * sin ? w / cos : h / sin
  16371. : h * sin < w * cos ? h / cos : w / sin;
  16372. },
  16373. /**
  16374. * @private
  16375. */
  16376. _isVisible: function() {
  16377. var me = this;
  16378. var chart = me.chart;
  16379. var display = me.options.display;
  16380. var i, ilen, meta;
  16381. if (display !== 'auto') {
  16382. return !!display;
  16383. }
  16384. // When 'auto', the scale is visible if at least one associated dataset is visible.
  16385. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  16386. if (chart.isDatasetVisible(i)) {
  16387. meta = chart.getDatasetMeta(i);
  16388. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  16389. return true;
  16390. }
  16391. }
  16392. }
  16393. return false;
  16394. },
  16395. /**
  16396. * @private
  16397. */
  16398. _computeGridLineItems: function(chartArea) {
  16399. var me = this;
  16400. var chart = me.chart;
  16401. var options = me.options;
  16402. var gridLines = options.gridLines;
  16403. var position = options.position;
  16404. var offsetGridLines = gridLines.offsetGridLines;
  16405. var isHorizontal = me.isHorizontal();
  16406. var ticks = me._ticksToDraw;
  16407. var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
  16408. var tl = getTickMarkLength(gridLines);
  16409. var items = [];
  16410. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  16411. var axisHalfWidth = axisWidth / 2;
  16412. var alignPixel = helpers$1._alignPixel;
  16413. var alignBorderValue = function(pixel) {
  16414. return alignPixel(chart, pixel, axisWidth);
  16415. };
  16416. var borderValue, i, tick, lineValue, alignedLineValue;
  16417. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
  16418. if (position === 'top') {
  16419. borderValue = alignBorderValue(me.bottom);
  16420. ty1 = me.bottom - tl;
  16421. ty2 = borderValue - axisHalfWidth;
  16422. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  16423. y2 = chartArea.bottom;
  16424. } else if (position === 'bottom') {
  16425. borderValue = alignBorderValue(me.top);
  16426. y1 = chartArea.top;
  16427. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  16428. ty1 = borderValue + axisHalfWidth;
  16429. ty2 = me.top + tl;
  16430. } else if (position === 'left') {
  16431. borderValue = alignBorderValue(me.right);
  16432. tx1 = me.right - tl;
  16433. tx2 = borderValue - axisHalfWidth;
  16434. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  16435. x2 = chartArea.right;
  16436. } else {
  16437. borderValue = alignBorderValue(me.left);
  16438. x1 = chartArea.left;
  16439. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  16440. tx1 = borderValue + axisHalfWidth;
  16441. tx2 = me.left + tl;
  16442. }
  16443. for (i = 0; i < ticksLength; ++i) {
  16444. tick = ticks[i] || {};
  16445. // autoskipper skipped this tick (#4635)
  16446. if (isNullOrUndef(tick.label) && i < ticks.length) {
  16447. continue;
  16448. }
  16449. if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
  16450. // Draw the first index specially
  16451. lineWidth = gridLines.zeroLineWidth;
  16452. lineColor = gridLines.zeroLineColor;
  16453. borderDash = gridLines.zeroLineBorderDash || [];
  16454. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  16455. } else {
  16456. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);
  16457. lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');
  16458. borderDash = gridLines.borderDash || [];
  16459. borderDashOffset = gridLines.borderDashOffset || 0.0;
  16460. }
  16461. lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
  16462. // Skip if the pixel is out of the range
  16463. if (lineValue === undefined) {
  16464. continue;
  16465. }
  16466. alignedLineValue = alignPixel(chart, lineValue, lineWidth);
  16467. if (isHorizontal) {
  16468. tx1 = tx2 = x1 = x2 = alignedLineValue;
  16469. } else {
  16470. ty1 = ty2 = y1 = y2 = alignedLineValue;
  16471. }
  16472. items.push({
  16473. tx1: tx1,
  16474. ty1: ty1,
  16475. tx2: tx2,
  16476. ty2: ty2,
  16477. x1: x1,
  16478. y1: y1,
  16479. x2: x2,
  16480. y2: y2,
  16481. width: lineWidth,
  16482. color: lineColor,
  16483. borderDash: borderDash,
  16484. borderDashOffset: borderDashOffset,
  16485. });
  16486. }
  16487. items.ticksLength = ticksLength;
  16488. items.borderValue = borderValue;
  16489. return items;
  16490. },
  16491. /**
  16492. * @private
  16493. */
  16494. _computeLabelItems: function() {
  16495. var me = this;
  16496. var options = me.options;
  16497. var optionTicks = options.ticks;
  16498. var position = options.position;
  16499. var isMirrored = optionTicks.mirror;
  16500. var isHorizontal = me.isHorizontal();
  16501. var ticks = me._ticksToDraw;
  16502. var fonts = parseTickFontOptions(optionTicks);
  16503. var tickPadding = optionTicks.padding;
  16504. var tl = getTickMarkLength(options.gridLines);
  16505. var rotation = -helpers$1.toRadians(me.labelRotation);
  16506. var items = [];
  16507. var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  16508. if (position === 'top') {
  16509. y = me.bottom - tl - tickPadding;
  16510. textAlign = !rotation ? 'center' : 'left';
  16511. } else if (position === 'bottom') {
  16512. y = me.top + tl + tickPadding;
  16513. textAlign = !rotation ? 'center' : 'right';
  16514. } else if (position === 'left') {
  16515. x = me.right - (isMirrored ? 0 : tl) - tickPadding;
  16516. textAlign = isMirrored ? 'left' : 'right';
  16517. } else {
  16518. x = me.left + (isMirrored ? 0 : tl) + tickPadding;
  16519. textAlign = isMirrored ? 'right' : 'left';
  16520. }
  16521. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  16522. tick = ticks[i];
  16523. label = tick.label;
  16524. // autoskipper skipped this tick (#4635)
  16525. if (isNullOrUndef(label)) {
  16526. continue;
  16527. }
  16528. pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
  16529. font = tick.major ? fonts.major : fonts.minor;
  16530. lineHeight = font.lineHeight;
  16531. lineCount = isArray(label) ? label.length : 1;
  16532. if (isHorizontal) {
  16533. x = pixel;
  16534. textOffset = position === 'top'
  16535. ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight
  16536. : (!rotation ? 0.5 : 0) * lineHeight;
  16537. } else {
  16538. y = pixel;
  16539. textOffset = (1 - lineCount) * lineHeight / 2;
  16540. }
  16541. items.push({
  16542. x: x,
  16543. y: y,
  16544. rotation: rotation,
  16545. label: label,
  16546. font: font,
  16547. textOffset: textOffset,
  16548. textAlign: textAlign
  16549. });
  16550. }
  16551. return items;
  16552. },
  16553. /**
  16554. * @private
  16555. */
  16556. _drawGrid: function(chartArea) {
  16557. var me = this;
  16558. var gridLines = me.options.gridLines;
  16559. if (!gridLines.display) {
  16560. return;
  16561. }
  16562. var ctx = me.ctx;
  16563. var chart = me.chart;
  16564. var alignPixel = helpers$1._alignPixel;
  16565. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  16566. var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  16567. var width, color, i, ilen, item;
  16568. for (i = 0, ilen = items.length; i < ilen; ++i) {
  16569. item = items[i];
  16570. width = item.width;
  16571. color = item.color;
  16572. if (width && color) {
  16573. ctx.save();
  16574. ctx.lineWidth = width;
  16575. ctx.strokeStyle = color;
  16576. if (ctx.setLineDash) {
  16577. ctx.setLineDash(item.borderDash);
  16578. ctx.lineDashOffset = item.borderDashOffset;
  16579. }
  16580. ctx.beginPath();
  16581. if (gridLines.drawTicks) {
  16582. ctx.moveTo(item.tx1, item.ty1);
  16583. ctx.lineTo(item.tx2, item.ty2);
  16584. }
  16585. if (gridLines.drawOnChartArea) {
  16586. ctx.moveTo(item.x1, item.y1);
  16587. ctx.lineTo(item.x2, item.y2);
  16588. }
  16589. ctx.stroke();
  16590. ctx.restore();
  16591. }
  16592. }
  16593. if (axisWidth) {
  16594. // Draw the line at the edge of the axis
  16595. var firstLineWidth = axisWidth;
  16596. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);
  16597. var borderValue = items.borderValue;
  16598. var x1, x2, y1, y2;
  16599. if (me.isHorizontal()) {
  16600. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  16601. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  16602. y1 = y2 = borderValue;
  16603. } else {
  16604. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  16605. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  16606. x1 = x2 = borderValue;
  16607. }
  16608. ctx.lineWidth = axisWidth;
  16609. ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  16610. ctx.beginPath();
  16611. ctx.moveTo(x1, y1);
  16612. ctx.lineTo(x2, y2);
  16613. ctx.stroke();
  16614. }
  16615. },
  16616. /**
  16617. * @private
  16618. */
  16619. _drawLabels: function() {
  16620. var me = this;
  16621. var optionTicks = me.options.ticks;
  16622. if (!optionTicks.display) {
  16623. return;
  16624. }
  16625. var ctx = me.ctx;
  16626. var items = me._labelItems || (me._labelItems = me._computeLabelItems());
  16627. var i, j, ilen, jlen, item, tickFont, label, y;
  16628. for (i = 0, ilen = items.length; i < ilen; ++i) {
  16629. item = items[i];
  16630. tickFont = item.font;
  16631. // Make sure we draw text in the correct color and font
  16632. ctx.save();
  16633. ctx.translate(item.x, item.y);
  16634. ctx.rotate(item.rotation);
  16635. ctx.font = tickFont.string;
  16636. ctx.fillStyle = tickFont.color;
  16637. ctx.textBaseline = 'middle';
  16638. ctx.textAlign = item.textAlign;
  16639. label = item.label;
  16640. y = item.textOffset;
  16641. if (isArray(label)) {
  16642. for (j = 0, jlen = label.length; j < jlen; ++j) {
  16643. // We just make sure the multiline element is a string here..
  16644. ctx.fillText('' + label[j], 0, y);
  16645. y += tickFont.lineHeight;
  16646. }
  16647. } else {
  16648. ctx.fillText(label, 0, y);
  16649. }
  16650. ctx.restore();
  16651. }
  16652. },
  16653. /**
  16654. * @private
  16655. */
  16656. _drawTitle: function() {
  16657. var me = this;
  16658. var ctx = me.ctx;
  16659. var options = me.options;
  16660. var scaleLabel = options.scaleLabel;
  16661. if (!scaleLabel.display) {
  16662. return;
  16663. }
  16664. var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);
  16665. var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);
  16666. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  16667. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  16668. var position = options.position;
  16669. var rotation = 0;
  16670. var scaleLabelX, scaleLabelY;
  16671. if (me.isHorizontal()) {
  16672. scaleLabelX = me.left + me.width / 2; // midpoint of the width
  16673. scaleLabelY = position === 'bottom'
  16674. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  16675. : me.top + halfLineHeight + scaleLabelPadding.top;
  16676. } else {
  16677. var isLeft = position === 'left';
  16678. scaleLabelX = isLeft
  16679. ? me.left + halfLineHeight + scaleLabelPadding.top
  16680. : me.right - halfLineHeight - scaleLabelPadding.top;
  16681. scaleLabelY = me.top + me.height / 2;
  16682. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  16683. }
  16684. ctx.save();
  16685. ctx.translate(scaleLabelX, scaleLabelY);
  16686. ctx.rotate(rotation);
  16687. ctx.textAlign = 'center';
  16688. ctx.textBaseline = 'middle';
  16689. ctx.fillStyle = scaleLabelFontColor; // render in correct colour
  16690. ctx.font = scaleLabelFont.string;
  16691. ctx.fillText(scaleLabel.labelString, 0, 0);
  16692. ctx.restore();
  16693. },
  16694. draw: function(chartArea) {
  16695. var me = this;
  16696. if (!me._isVisible()) {
  16697. return;
  16698. }
  16699. me._drawGrid(chartArea);
  16700. me._drawTitle();
  16701. me._drawLabels();
  16702. },
  16703. /**
  16704. * @private
  16705. */
  16706. _layers: function() {
  16707. var me = this;
  16708. var opts = me.options;
  16709. var tz = opts.ticks && opts.ticks.z || 0;
  16710. var gz = opts.gridLines && opts.gridLines.z || 0;
  16711. if (!me._isVisible() || tz === gz || me.draw !== me._draw) {
  16712. // backward compatibility: draw has been overridden by custom scale
  16713. return [{
  16714. z: tz,
  16715. draw: function() {
  16716. me.draw.apply(me, arguments);
  16717. }
  16718. }];
  16719. }
  16720. return [{
  16721. z: gz,
  16722. draw: function() {
  16723. me._drawGrid.apply(me, arguments);
  16724. me._drawTitle.apply(me, arguments);
  16725. }
  16726. }, {
  16727. z: tz,
  16728. draw: function() {
  16729. me._drawLabels.apply(me, arguments);
  16730. }
  16731. }];
  16732. },
  16733. /**
  16734. * @private
  16735. */
  16736. _getMatchingVisibleMetas: function(type) {
  16737. var me = this;
  16738. var isHorizontal = me.isHorizontal();
  16739. return me.chart._getSortedVisibleDatasetMetas()
  16740. .filter(function(meta) {
  16741. return (!type || meta.type === type)
  16742. && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);
  16743. });
  16744. }
  16745. });
  16746. Scale.prototype._draw = Scale.prototype.draw;
  16747. var core_scale = Scale;
  16748. var isNullOrUndef$1 = helpers$1.isNullOrUndef;
  16749. var defaultConfig = {
  16750. position: 'bottom'
  16751. };
  16752. var scale_category = core_scale.extend({
  16753. determineDataLimits: function() {
  16754. var me = this;
  16755. var labels = me._getLabels();
  16756. var ticksOpts = me.options.ticks;
  16757. var min = ticksOpts.min;
  16758. var max = ticksOpts.max;
  16759. var minIndex = 0;
  16760. var maxIndex = labels.length - 1;
  16761. var findIndex;
  16762. if (min !== undefined) {
  16763. // user specified min value
  16764. findIndex = labels.indexOf(min);
  16765. if (findIndex >= 0) {
  16766. minIndex = findIndex;
  16767. }
  16768. }
  16769. if (max !== undefined) {
  16770. // user specified max value
  16771. findIndex = labels.indexOf(max);
  16772. if (findIndex >= 0) {
  16773. maxIndex = findIndex;
  16774. }
  16775. }
  16776. me.minIndex = minIndex;
  16777. me.maxIndex = maxIndex;
  16778. me.min = labels[minIndex];
  16779. me.max = labels[maxIndex];
  16780. },
  16781. buildTicks: function() {
  16782. var me = this;
  16783. var labels = me._getLabels();
  16784. var minIndex = me.minIndex;
  16785. var maxIndex = me.maxIndex;
  16786. // If we are viewing some subset of labels, slice the original array
  16787. me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);
  16788. },
  16789. getLabelForIndex: function(index, datasetIndex) {
  16790. var me = this;
  16791. var chart = me.chart;
  16792. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  16793. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  16794. }
  16795. return me._getLabels()[index];
  16796. },
  16797. _configure: function() {
  16798. var me = this;
  16799. var offset = me.options.offset;
  16800. var ticks = me.ticks;
  16801. core_scale.prototype._configure.call(me);
  16802. if (!me.isHorizontal()) {
  16803. // For backward compatibility, vertical category scale reverse is inverted.
  16804. me._reversePixels = !me._reversePixels;
  16805. }
  16806. if (!ticks) {
  16807. return;
  16808. }
  16809. me._startValue = me.minIndex - (offset ? 0.5 : 0);
  16810. me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);
  16811. },
  16812. // Used to get data value locations. Value can either be an index or a numerical value
  16813. getPixelForValue: function(value, index, datasetIndex) {
  16814. var me = this;
  16815. var valueCategory, labels, idx;
  16816. if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {
  16817. value = me.chart.data.datasets[datasetIndex].data[index];
  16818. }
  16819. // If value is a data object, then index is the index in the data array,
  16820. // not the index of the scale. We need to change that.
  16821. if (!isNullOrUndef$1(value)) {
  16822. valueCategory = me.isHorizontal() ? value.x : value.y;
  16823. }
  16824. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  16825. labels = me._getLabels();
  16826. value = helpers$1.valueOrDefault(valueCategory, value);
  16827. idx = labels.indexOf(value);
  16828. index = idx !== -1 ? idx : index;
  16829. if (isNaN(index)) {
  16830. index = value;
  16831. }
  16832. }
  16833. return me.getPixelForDecimal((index - me._startValue) / me._valueRange);
  16834. },
  16835. getPixelForTick: function(index) {
  16836. var ticks = this.ticks;
  16837. return index < 0 || index > ticks.length - 1
  16838. ? null
  16839. : this.getPixelForValue(ticks[index], index + this.minIndex);
  16840. },
  16841. getValueForPixel: function(pixel) {
  16842. var me = this;
  16843. var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  16844. return Math.min(Math.max(value, 0), me.ticks.length - 1);
  16845. },
  16846. getBasePixel: function() {
  16847. return this.bottom;
  16848. }
  16849. });
  16850. // INTERNAL: static default options, registered in src/index.js
  16851. var _defaults = defaultConfig;
  16852. scale_category._defaults = _defaults;
  16853. var noop = helpers$1.noop;
  16854. var isNullOrUndef$2 = helpers$1.isNullOrUndef;
  16855. /**
  16856. * Generate a set of linear ticks
  16857. * @param generationOptions the options used to generate the ticks
  16858. * @param dataRange the range of the data
  16859. * @returns {number[]} array of tick values
  16860. */
  16861. function generateTicks(generationOptions, dataRange) {
  16862. var ticks = [];
  16863. // To get a "nice" value for the tick spacing, we will use the appropriately named
  16864. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  16865. // for details.
  16866. var MIN_SPACING = 1e-14;
  16867. var stepSize = generationOptions.stepSize;
  16868. var unit = stepSize || 1;
  16869. var maxNumSpaces = generationOptions.maxTicks - 1;
  16870. var min = generationOptions.min;
  16871. var max = generationOptions.max;
  16872. var precision = generationOptions.precision;
  16873. var rmin = dataRange.min;
  16874. var rmax = dataRange.max;
  16875. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  16876. var factor, niceMin, niceMax, numSpaces;
  16877. // Beyond MIN_SPACING floating point numbers being to lose precision
  16878. // such that we can't do the math necessary to generate ticks
  16879. if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {
  16880. return [rmin, rmax];
  16881. }
  16882. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  16883. if (numSpaces > maxNumSpaces) {
  16884. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  16885. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  16886. }
  16887. if (stepSize || isNullOrUndef$2(precision)) {
  16888. // If a precision is not specified, calculate factor based on spacing
  16889. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  16890. } else {
  16891. // If the user specified a precision, round to that number of decimal places
  16892. factor = Math.pow(10, precision);
  16893. spacing = Math.ceil(spacing * factor) / factor;
  16894. }
  16895. niceMin = Math.floor(rmin / spacing) * spacing;
  16896. niceMax = Math.ceil(rmax / spacing) * spacing;
  16897. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  16898. if (stepSize) {
  16899. // If very close to our whole number, use it.
  16900. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  16901. niceMin = min;
  16902. }
  16903. if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  16904. niceMax = max;
  16905. }
  16906. }
  16907. numSpaces = (niceMax - niceMin) / spacing;
  16908. // If very close to our rounded value, use it.
  16909. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  16910. numSpaces = Math.round(numSpaces);
  16911. } else {
  16912. numSpaces = Math.ceil(numSpaces);
  16913. }
  16914. niceMin = Math.round(niceMin * factor) / factor;
  16915. niceMax = Math.round(niceMax * factor) / factor;
  16916. ticks.push(isNullOrUndef$2(min) ? niceMin : min);
  16917. for (var j = 1; j < numSpaces; ++j) {
  16918. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  16919. }
  16920. ticks.push(isNullOrUndef$2(max) ? niceMax : max);
  16921. return ticks;
  16922. }
  16923. var scale_linearbase = core_scale.extend({
  16924. getRightValue: function(value) {
  16925. if (typeof value === 'string') {
  16926. return +value;
  16927. }
  16928. return core_scale.prototype.getRightValue.call(this, value);
  16929. },
  16930. handleTickRangeOptions: function() {
  16931. var me = this;
  16932. var opts = me.options;
  16933. var tickOpts = opts.ticks;
  16934. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  16935. // do nothing since that would make the chart weird. If the user really wants a weird chart
  16936. // axis, they can manually override it
  16937. if (tickOpts.beginAtZero) {
  16938. var minSign = helpers$1.sign(me.min);
  16939. var maxSign = helpers$1.sign(me.max);
  16940. if (minSign < 0 && maxSign < 0) {
  16941. // move the top up to 0
  16942. me.max = 0;
  16943. } else if (minSign > 0 && maxSign > 0) {
  16944. // move the bottom down to 0
  16945. me.min = 0;
  16946. }
  16947. }
  16948. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  16949. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  16950. if (tickOpts.min !== undefined) {
  16951. me.min = tickOpts.min;
  16952. } else if (tickOpts.suggestedMin !== undefined) {
  16953. if (me.min === null) {
  16954. me.min = tickOpts.suggestedMin;
  16955. } else {
  16956. me.min = Math.min(me.min, tickOpts.suggestedMin);
  16957. }
  16958. }
  16959. if (tickOpts.max !== undefined) {
  16960. me.max = tickOpts.max;
  16961. } else if (tickOpts.suggestedMax !== undefined) {
  16962. if (me.max === null) {
  16963. me.max = tickOpts.suggestedMax;
  16964. } else {
  16965. me.max = Math.max(me.max, tickOpts.suggestedMax);
  16966. }
  16967. }
  16968. if (setMin !== setMax) {
  16969. // We set the min or the max but not both.
  16970. // So ensure that our range is good
  16971. // Inverted or 0 length range can happen when
  16972. // ticks.min is set, and no datasets are visible
  16973. if (me.min >= me.max) {
  16974. if (setMin) {
  16975. me.max = me.min + 1;
  16976. } else {
  16977. me.min = me.max - 1;
  16978. }
  16979. }
  16980. }
  16981. if (me.min === me.max) {
  16982. me.max++;
  16983. if (!tickOpts.beginAtZero) {
  16984. me.min--;
  16985. }
  16986. }
  16987. },
  16988. getTickLimit: function() {
  16989. var me = this;
  16990. var tickOpts = me.options.ticks;
  16991. var stepSize = tickOpts.stepSize;
  16992. var maxTicksLimit = tickOpts.maxTicksLimit;
  16993. var maxTicks;
  16994. if (stepSize) {
  16995. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  16996. } else {
  16997. maxTicks = me._computeTickLimit();
  16998. maxTicksLimit = maxTicksLimit || 11;
  16999. }
  17000. if (maxTicksLimit) {
  17001. maxTicks = Math.min(maxTicksLimit, maxTicks);
  17002. }
  17003. return maxTicks;
  17004. },
  17005. _computeTickLimit: function() {
  17006. return Number.POSITIVE_INFINITY;
  17007. },
  17008. handleDirectionalChanges: noop,
  17009. buildTicks: function() {
  17010. var me = this;
  17011. var opts = me.options;
  17012. var tickOpts = opts.ticks;
  17013. // Figure out what the max number of ticks we can support it is based on the size of
  17014. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  17015. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  17016. // the graph. Make sure we always have at least 2 ticks
  17017. var maxTicks = me.getTickLimit();
  17018. maxTicks = Math.max(2, maxTicks);
  17019. var numericGeneratorOptions = {
  17020. maxTicks: maxTicks,
  17021. min: tickOpts.min,
  17022. max: tickOpts.max,
  17023. precision: tickOpts.precision,
  17024. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  17025. };
  17026. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  17027. me.handleDirectionalChanges();
  17028. // At this point, we need to update our max and min given the tick values since we have expanded the
  17029. // range of the scale
  17030. me.max = helpers$1.max(ticks);
  17031. me.min = helpers$1.min(ticks);
  17032. if (tickOpts.reverse) {
  17033. ticks.reverse();
  17034. me.start = me.max;
  17035. me.end = me.min;
  17036. } else {
  17037. me.start = me.min;
  17038. me.end = me.max;
  17039. }
  17040. },
  17041. convertTicksToLabels: function() {
  17042. var me = this;
  17043. me.ticksAsNumbers = me.ticks.slice();
  17044. me.zeroLineIndex = me.ticks.indexOf(0);
  17045. core_scale.prototype.convertTicksToLabels.call(me);
  17046. },
  17047. _configure: function() {
  17048. var me = this;
  17049. var ticks = me.getTicks();
  17050. var start = me.min;
  17051. var end = me.max;
  17052. var offset;
  17053. core_scale.prototype._configure.call(me);
  17054. if (me.options.offset && ticks.length) {
  17055. offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  17056. start -= offset;
  17057. end += offset;
  17058. }
  17059. me._startValue = start;
  17060. me._endValue = end;
  17061. me._valueRange = end - start;
  17062. }
  17063. });
  17064. var defaultConfig$1 = {
  17065. position: 'left',
  17066. ticks: {
  17067. callback: core_ticks.formatters.linear
  17068. }
  17069. };
  17070. var DEFAULT_MIN = 0;
  17071. var DEFAULT_MAX = 1;
  17072. function getOrCreateStack(stacks, stacked, meta) {
  17073. var key = [
  17074. meta.type,
  17075. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  17076. stacked === undefined && meta.stack === undefined ? meta.index : '',
  17077. meta.stack
  17078. ].join('.');
  17079. if (stacks[key] === undefined) {
  17080. stacks[key] = {
  17081. pos: [],
  17082. neg: []
  17083. };
  17084. }
  17085. return stacks[key];
  17086. }
  17087. function stackData(scale, stacks, meta, data) {
  17088. var opts = scale.options;
  17089. var stacked = opts.stacked;
  17090. var stack = getOrCreateStack(stacks, stacked, meta);
  17091. var pos = stack.pos;
  17092. var neg = stack.neg;
  17093. var ilen = data.length;
  17094. var i, value;
  17095. for (i = 0; i < ilen; ++i) {
  17096. value = scale._parseValue(data[i]);
  17097. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  17098. continue;
  17099. }
  17100. pos[i] = pos[i] || 0;
  17101. neg[i] = neg[i] || 0;
  17102. if (opts.relativePoints) {
  17103. pos[i] = 100;
  17104. } else if (value.min < 0 || value.max < 0) {
  17105. neg[i] += value.min;
  17106. } else {
  17107. pos[i] += value.max;
  17108. }
  17109. }
  17110. }
  17111. function updateMinMax(scale, meta, data) {
  17112. var ilen = data.length;
  17113. var i, value;
  17114. for (i = 0; i < ilen; ++i) {
  17115. value = scale._parseValue(data[i]);
  17116. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  17117. continue;
  17118. }
  17119. scale.min = Math.min(scale.min, value.min);
  17120. scale.max = Math.max(scale.max, value.max);
  17121. }
  17122. }
  17123. var scale_linear = scale_linearbase.extend({
  17124. determineDataLimits: function() {
  17125. var me = this;
  17126. var opts = me.options;
  17127. var chart = me.chart;
  17128. var datasets = chart.data.datasets;
  17129. var metasets = me._getMatchingVisibleMetas();
  17130. var hasStacks = opts.stacked;
  17131. var stacks = {};
  17132. var ilen = metasets.length;
  17133. var i, meta, data, values;
  17134. me.min = Number.POSITIVE_INFINITY;
  17135. me.max = Number.NEGATIVE_INFINITY;
  17136. if (hasStacks === undefined) {
  17137. for (i = 0; !hasStacks && i < ilen; ++i) {
  17138. meta = metasets[i];
  17139. hasStacks = meta.stack !== undefined;
  17140. }
  17141. }
  17142. for (i = 0; i < ilen; ++i) {
  17143. meta = metasets[i];
  17144. data = datasets[meta.index].data;
  17145. if (hasStacks) {
  17146. stackData(me, stacks, meta, data);
  17147. } else {
  17148. updateMinMax(me, meta, data);
  17149. }
  17150. }
  17151. helpers$1.each(stacks, function(stackValues) {
  17152. values = stackValues.pos.concat(stackValues.neg);
  17153. me.min = Math.min(me.min, helpers$1.min(values));
  17154. me.max = Math.max(me.max, helpers$1.max(values));
  17155. });
  17156. me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  17157. me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  17158. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  17159. me.handleTickRangeOptions();
  17160. },
  17161. // Returns the maximum number of ticks based on the scale dimension
  17162. _computeTickLimit: function() {
  17163. var me = this;
  17164. var tickFont;
  17165. if (me.isHorizontal()) {
  17166. return Math.ceil(me.width / 40);
  17167. }
  17168. tickFont = helpers$1.options._parseFont(me.options.ticks);
  17169. return Math.ceil(me.height / tickFont.lineHeight);
  17170. },
  17171. // Called after the ticks are built. We need
  17172. handleDirectionalChanges: function() {
  17173. if (!this.isHorizontal()) {
  17174. // We are in a vertical orientation. The top value is the highest. So reverse the array
  17175. this.ticks.reverse();
  17176. }
  17177. },
  17178. getLabelForIndex: function(index, datasetIndex) {
  17179. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  17180. },
  17181. // Utils
  17182. getPixelForValue: function(value) {
  17183. var me = this;
  17184. return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);
  17185. },
  17186. getValueForPixel: function(pixel) {
  17187. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  17188. },
  17189. getPixelForTick: function(index) {
  17190. var ticks = this.ticksAsNumbers;
  17191. if (index < 0 || index > ticks.length - 1) {
  17192. return null;
  17193. }
  17194. return this.getPixelForValue(ticks[index]);
  17195. }
  17196. });
  17197. // INTERNAL: static default options, registered in src/index.js
  17198. var _defaults$1 = defaultConfig$1;
  17199. scale_linear._defaults = _defaults$1;
  17200. var valueOrDefault$b = helpers$1.valueOrDefault;
  17201. var log10 = helpers$1.math.log10;
  17202. /**
  17203. * Generate a set of logarithmic ticks
  17204. * @param generationOptions the options used to generate the ticks
  17205. * @param dataRange the range of the data
  17206. * @returns {number[]} array of tick values
  17207. */
  17208. function generateTicks$1(generationOptions, dataRange) {
  17209. var ticks = [];
  17210. var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  17211. var endExp = Math.floor(log10(dataRange.max));
  17212. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  17213. var exp, significand;
  17214. if (tickVal === 0) {
  17215. exp = Math.floor(log10(dataRange.minNotZero));
  17216. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  17217. ticks.push(tickVal);
  17218. tickVal = significand * Math.pow(10, exp);
  17219. } else {
  17220. exp = Math.floor(log10(tickVal));
  17221. significand = Math.floor(tickVal / Math.pow(10, exp));
  17222. }
  17223. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  17224. do {
  17225. ticks.push(tickVal);
  17226. ++significand;
  17227. if (significand === 10) {
  17228. significand = 1;
  17229. ++exp;
  17230. precision = exp >= 0 ? 1 : precision;
  17231. }
  17232. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  17233. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  17234. var lastTick = valueOrDefault$b(generationOptions.max, tickVal);
  17235. ticks.push(lastTick);
  17236. return ticks;
  17237. }
  17238. var defaultConfig$2 = {
  17239. position: 'left',
  17240. // label settings
  17241. ticks: {
  17242. callback: core_ticks.formatters.logarithmic
  17243. }
  17244. };
  17245. // TODO(v3): change this to positiveOrDefault
  17246. function nonNegativeOrDefault(value, defaultValue) {
  17247. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  17248. }
  17249. var scale_logarithmic = core_scale.extend({
  17250. determineDataLimits: function() {
  17251. var me = this;
  17252. var opts = me.options;
  17253. var chart = me.chart;
  17254. var datasets = chart.data.datasets;
  17255. var isHorizontal = me.isHorizontal();
  17256. function IDMatches(meta) {
  17257. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  17258. }
  17259. var datasetIndex, meta, value, data, i, ilen;
  17260. // Calculate Range
  17261. me.min = Number.POSITIVE_INFINITY;
  17262. me.max = Number.NEGATIVE_INFINITY;
  17263. me.minNotZero = Number.POSITIVE_INFINITY;
  17264. var hasStacks = opts.stacked;
  17265. if (hasStacks === undefined) {
  17266. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  17267. meta = chart.getDatasetMeta(datasetIndex);
  17268. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  17269. meta.stack !== undefined) {
  17270. hasStacks = true;
  17271. break;
  17272. }
  17273. }
  17274. }
  17275. if (opts.stacked || hasStacks) {
  17276. var valuesPerStack = {};
  17277. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  17278. meta = chart.getDatasetMeta(datasetIndex);
  17279. var key = [
  17280. meta.type,
  17281. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  17282. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  17283. meta.stack
  17284. ].join('.');
  17285. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  17286. if (valuesPerStack[key] === undefined) {
  17287. valuesPerStack[key] = [];
  17288. }
  17289. data = datasets[datasetIndex].data;
  17290. for (i = 0, ilen = data.length; i < ilen; i++) {
  17291. var values = valuesPerStack[key];
  17292. value = me._parseValue(data[i]);
  17293. // invalid, hidden and negative values are ignored
  17294. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  17295. continue;
  17296. }
  17297. values[i] = values[i] || 0;
  17298. values[i] += value.max;
  17299. }
  17300. }
  17301. }
  17302. helpers$1.each(valuesPerStack, function(valuesForType) {
  17303. if (valuesForType.length > 0) {
  17304. var minVal = helpers$1.min(valuesForType);
  17305. var maxVal = helpers$1.max(valuesForType);
  17306. me.min = Math.min(me.min, minVal);
  17307. me.max = Math.max(me.max, maxVal);
  17308. }
  17309. });
  17310. } else {
  17311. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  17312. meta = chart.getDatasetMeta(datasetIndex);
  17313. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  17314. data = datasets[datasetIndex].data;
  17315. for (i = 0, ilen = data.length; i < ilen; i++) {
  17316. value = me._parseValue(data[i]);
  17317. // invalid, hidden and negative values are ignored
  17318. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  17319. continue;
  17320. }
  17321. me.min = Math.min(value.min, me.min);
  17322. me.max = Math.max(value.max, me.max);
  17323. if (value.min !== 0) {
  17324. me.minNotZero = Math.min(value.min, me.minNotZero);
  17325. }
  17326. }
  17327. }
  17328. }
  17329. }
  17330. me.min = helpers$1.isFinite(me.min) ? me.min : null;
  17331. me.max = helpers$1.isFinite(me.max) ? me.max : null;
  17332. me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;
  17333. // Common base implementation to handle ticks.min, ticks.max
  17334. this.handleTickRangeOptions();
  17335. },
  17336. handleTickRangeOptions: function() {
  17337. var me = this;
  17338. var tickOpts = me.options.ticks;
  17339. var DEFAULT_MIN = 1;
  17340. var DEFAULT_MAX = 10;
  17341. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  17342. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  17343. if (me.min === me.max) {
  17344. if (me.min !== 0 && me.min !== null) {
  17345. me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);
  17346. me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);
  17347. } else {
  17348. me.min = DEFAULT_MIN;
  17349. me.max = DEFAULT_MAX;
  17350. }
  17351. }
  17352. if (me.min === null) {
  17353. me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);
  17354. }
  17355. if (me.max === null) {
  17356. me.max = me.min !== 0
  17357. ? Math.pow(10, Math.floor(log10(me.min)) + 1)
  17358. : DEFAULT_MAX;
  17359. }
  17360. if (me.minNotZero === null) {
  17361. if (me.min > 0) {
  17362. me.minNotZero = me.min;
  17363. } else if (me.max < 1) {
  17364. me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));
  17365. } else {
  17366. me.minNotZero = DEFAULT_MIN;
  17367. }
  17368. }
  17369. },
  17370. buildTicks: function() {
  17371. var me = this;
  17372. var tickOpts = me.options.ticks;
  17373. var reverse = !me.isHorizontal();
  17374. var generationOptions = {
  17375. min: nonNegativeOrDefault(tickOpts.min),
  17376. max: nonNegativeOrDefault(tickOpts.max)
  17377. };
  17378. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  17379. // At this point, we need to update our max and min given the tick values since we have expanded the
  17380. // range of the scale
  17381. me.max = helpers$1.max(ticks);
  17382. me.min = helpers$1.min(ticks);
  17383. if (tickOpts.reverse) {
  17384. reverse = !reverse;
  17385. me.start = me.max;
  17386. me.end = me.min;
  17387. } else {
  17388. me.start = me.min;
  17389. me.end = me.max;
  17390. }
  17391. if (reverse) {
  17392. ticks.reverse();
  17393. }
  17394. },
  17395. convertTicksToLabels: function() {
  17396. this.tickValues = this.ticks.slice();
  17397. core_scale.prototype.convertTicksToLabels.call(this);
  17398. },
  17399. // Get the correct tooltip label
  17400. getLabelForIndex: function(index, datasetIndex) {
  17401. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  17402. },
  17403. getPixelForTick: function(index) {
  17404. var ticks = this.tickValues;
  17405. if (index < 0 || index > ticks.length - 1) {
  17406. return null;
  17407. }
  17408. return this.getPixelForValue(ticks[index]);
  17409. },
  17410. /**
  17411. * Returns the value of the first tick.
  17412. * @param {number} value - The minimum not zero value.
  17413. * @return {number} The first tick value.
  17414. * @private
  17415. */
  17416. _getFirstTickValue: function(value) {
  17417. var exp = Math.floor(log10(value));
  17418. var significand = Math.floor(value / Math.pow(10, exp));
  17419. return significand * Math.pow(10, exp);
  17420. },
  17421. _configure: function() {
  17422. var me = this;
  17423. var start = me.min;
  17424. var offset = 0;
  17425. core_scale.prototype._configure.call(me);
  17426. if (start === 0) {
  17427. start = me._getFirstTickValue(me.minNotZero);
  17428. offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;
  17429. }
  17430. me._startValue = log10(start);
  17431. me._valueOffset = offset;
  17432. me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);
  17433. },
  17434. getPixelForValue: function(value) {
  17435. var me = this;
  17436. var decimal = 0;
  17437. value = +me.getRightValue(value);
  17438. if (value > me.min && value > 0) {
  17439. decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;
  17440. }
  17441. return me.getPixelForDecimal(decimal);
  17442. },
  17443. getValueForPixel: function(pixel) {
  17444. var me = this;
  17445. var decimal = me.getDecimalForPixel(pixel);
  17446. return decimal === 0 && me.min === 0
  17447. ? 0
  17448. : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);
  17449. }
  17450. });
  17451. // INTERNAL: static default options, registered in src/index.js
  17452. var _defaults$2 = defaultConfig$2;
  17453. scale_logarithmic._defaults = _defaults$2;
  17454. var valueOrDefault$c = helpers$1.valueOrDefault;
  17455. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  17456. var resolve$4 = helpers$1.options.resolve;
  17457. var defaultConfig$3 = {
  17458. display: true,
  17459. // Boolean - Whether to animate scaling the chart from the centre
  17460. animate: true,
  17461. position: 'chartArea',
  17462. angleLines: {
  17463. display: true,
  17464. color: 'rgba(0,0,0,0.1)',
  17465. lineWidth: 1,
  17466. borderDash: [],
  17467. borderDashOffset: 0.0
  17468. },
  17469. gridLines: {
  17470. circular: false
  17471. },
  17472. // label settings
  17473. ticks: {
  17474. // Boolean - Show a backdrop to the scale label
  17475. showLabelBackdrop: true,
  17476. // String - The colour of the label backdrop
  17477. backdropColor: 'rgba(255,255,255,0.75)',
  17478. // Number - The backdrop padding above & below the label in pixels
  17479. backdropPaddingY: 2,
  17480. // Number - The backdrop padding to the side of the label in pixels
  17481. backdropPaddingX: 2,
  17482. callback: core_ticks.formatters.linear
  17483. },
  17484. pointLabels: {
  17485. // Boolean - if true, show point labels
  17486. display: true,
  17487. // Number - Point label font size in pixels
  17488. fontSize: 10,
  17489. // Function - Used to convert point labels
  17490. callback: function(label) {
  17491. return label;
  17492. }
  17493. }
  17494. };
  17495. function getTickBackdropHeight(opts) {
  17496. var tickOpts = opts.ticks;
  17497. if (tickOpts.display && opts.display) {
  17498. return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  17499. }
  17500. return 0;
  17501. }
  17502. function measureLabelSize(ctx, lineHeight, label) {
  17503. if (helpers$1.isArray(label)) {
  17504. return {
  17505. w: helpers$1.longestText(ctx, ctx.font, label),
  17506. h: label.length * lineHeight
  17507. };
  17508. }
  17509. return {
  17510. w: ctx.measureText(label).width,
  17511. h: lineHeight
  17512. };
  17513. }
  17514. function determineLimits(angle, pos, size, min, max) {
  17515. if (angle === min || angle === max) {
  17516. return {
  17517. start: pos - (size / 2),
  17518. end: pos + (size / 2)
  17519. };
  17520. } else if (angle < min || angle > max) {
  17521. return {
  17522. start: pos - size,
  17523. end: pos
  17524. };
  17525. }
  17526. return {
  17527. start: pos,
  17528. end: pos + size
  17529. };
  17530. }
  17531. /**
  17532. * Helper function to fit a radial linear scale with point labels
  17533. */
  17534. function fitWithPointLabels(scale) {
  17535. // Right, this is really confusing and there is a lot of maths going on here
  17536. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  17537. //
  17538. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  17539. //
  17540. // Solution:
  17541. //
  17542. // We assume the radius of the polygon is half the size of the canvas at first
  17543. // at each index we check if the text overlaps.
  17544. //
  17545. // Where it does, we store that angle and that index.
  17546. //
  17547. // After finding the largest index and angle we calculate how much we need to remove
  17548. // from the shape radius to move the point inwards by that x.
  17549. //
  17550. // We average the left and right distances to get the maximum shape radius that can fit in the box
  17551. // along with labels.
  17552. //
  17553. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  17554. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  17555. //
  17556. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  17557. // and position it in the most space efficient manner
  17558. //
  17559. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  17560. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  17561. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  17562. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  17563. var furthestLimits = {
  17564. l: 0,
  17565. r: scale.width,
  17566. t: 0,
  17567. b: scale.height - scale.paddingTop
  17568. };
  17569. var furthestAngles = {};
  17570. var i, textSize, pointPosition;
  17571. scale.ctx.font = plFont.string;
  17572. scale._pointLabelSizes = [];
  17573. var valueCount = scale.chart.data.labels.length;
  17574. for (i = 0; i < valueCount; i++) {
  17575. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  17576. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
  17577. scale._pointLabelSizes[i] = textSize;
  17578. // Add quarter circle to make degree 0 mean top of circle
  17579. var angleRadians = scale.getIndexAngle(i);
  17580. var angle = helpers$1.toDegrees(angleRadians) % 360;
  17581. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  17582. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  17583. if (hLimits.start < furthestLimits.l) {
  17584. furthestLimits.l = hLimits.start;
  17585. furthestAngles.l = angleRadians;
  17586. }
  17587. if (hLimits.end > furthestLimits.r) {
  17588. furthestLimits.r = hLimits.end;
  17589. furthestAngles.r = angleRadians;
  17590. }
  17591. if (vLimits.start < furthestLimits.t) {
  17592. furthestLimits.t = vLimits.start;
  17593. furthestAngles.t = angleRadians;
  17594. }
  17595. if (vLimits.end > furthestLimits.b) {
  17596. furthestLimits.b = vLimits.end;
  17597. furthestAngles.b = angleRadians;
  17598. }
  17599. }
  17600. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  17601. }
  17602. function getTextAlignForAngle(angle) {
  17603. if (angle === 0 || angle === 180) {
  17604. return 'center';
  17605. } else if (angle < 180) {
  17606. return 'left';
  17607. }
  17608. return 'right';
  17609. }
  17610. function fillText(ctx, text, position, lineHeight) {
  17611. var y = position.y + lineHeight / 2;
  17612. var i, ilen;
  17613. if (helpers$1.isArray(text)) {
  17614. for (i = 0, ilen = text.length; i < ilen; ++i) {
  17615. ctx.fillText(text[i], position.x, y);
  17616. y += lineHeight;
  17617. }
  17618. } else {
  17619. ctx.fillText(text, position.x, y);
  17620. }
  17621. }
  17622. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  17623. if (angle === 90 || angle === 270) {
  17624. position.y -= (textSize.h / 2);
  17625. } else if (angle > 270 || angle < 90) {
  17626. position.y -= textSize.h;
  17627. }
  17628. }
  17629. function drawPointLabels(scale) {
  17630. var ctx = scale.ctx;
  17631. var opts = scale.options;
  17632. var pointLabelOpts = opts.pointLabels;
  17633. var tickBackdropHeight = getTickBackdropHeight(opts);
  17634. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  17635. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  17636. ctx.save();
  17637. ctx.font = plFont.string;
  17638. ctx.textBaseline = 'middle';
  17639. for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
  17640. // Extra pixels out for some label spacing
  17641. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  17642. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  17643. // Keep this in loop since we may support array properties here
  17644. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  17645. ctx.fillStyle = pointLabelFontColor;
  17646. var angleRadians = scale.getIndexAngle(i);
  17647. var angle = helpers$1.toDegrees(angleRadians);
  17648. ctx.textAlign = getTextAlignForAngle(angle);
  17649. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  17650. fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
  17651. }
  17652. ctx.restore();
  17653. }
  17654. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  17655. var ctx = scale.ctx;
  17656. var circular = gridLineOpts.circular;
  17657. var valueCount = scale.chart.data.labels.length;
  17658. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  17659. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  17660. var pointPosition;
  17661. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  17662. return;
  17663. }
  17664. ctx.save();
  17665. ctx.strokeStyle = lineColor;
  17666. ctx.lineWidth = lineWidth;
  17667. if (ctx.setLineDash) {
  17668. ctx.setLineDash(gridLineOpts.borderDash || []);
  17669. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  17670. }
  17671. ctx.beginPath();
  17672. if (circular) {
  17673. // Draw circular arcs between the points
  17674. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  17675. } else {
  17676. // Draw straight lines connecting each index
  17677. pointPosition = scale.getPointPosition(0, radius);
  17678. ctx.moveTo(pointPosition.x, pointPosition.y);
  17679. for (var i = 1; i < valueCount; i++) {
  17680. pointPosition = scale.getPointPosition(i, radius);
  17681. ctx.lineTo(pointPosition.x, pointPosition.y);
  17682. }
  17683. }
  17684. ctx.closePath();
  17685. ctx.stroke();
  17686. ctx.restore();
  17687. }
  17688. function numberOrZero(param) {
  17689. return helpers$1.isNumber(param) ? param : 0;
  17690. }
  17691. var scale_radialLinear = scale_linearbase.extend({
  17692. setDimensions: function() {
  17693. var me = this;
  17694. // Set the unconstrained dimension before label rotation
  17695. me.width = me.maxWidth;
  17696. me.height = me.maxHeight;
  17697. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  17698. me.xCenter = Math.floor(me.width / 2);
  17699. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  17700. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  17701. },
  17702. determineDataLimits: function() {
  17703. var me = this;
  17704. var chart = me.chart;
  17705. var min = Number.POSITIVE_INFINITY;
  17706. var max = Number.NEGATIVE_INFINITY;
  17707. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  17708. if (chart.isDatasetVisible(datasetIndex)) {
  17709. var meta = chart.getDatasetMeta(datasetIndex);
  17710. helpers$1.each(dataset.data, function(rawValue, index) {
  17711. var value = +me.getRightValue(rawValue);
  17712. if (isNaN(value) || meta.data[index].hidden) {
  17713. return;
  17714. }
  17715. min = Math.min(value, min);
  17716. max = Math.max(value, max);
  17717. });
  17718. }
  17719. });
  17720. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  17721. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  17722. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  17723. me.handleTickRangeOptions();
  17724. },
  17725. // Returns the maximum number of ticks based on the scale dimension
  17726. _computeTickLimit: function() {
  17727. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  17728. },
  17729. convertTicksToLabels: function() {
  17730. var me = this;
  17731. scale_linearbase.prototype.convertTicksToLabels.call(me);
  17732. // Point labels
  17733. me.pointLabels = me.chart.data.labels.map(function() {
  17734. var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);
  17735. return label || label === 0 ? label : '';
  17736. });
  17737. },
  17738. getLabelForIndex: function(index, datasetIndex) {
  17739. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  17740. },
  17741. fit: function() {
  17742. var me = this;
  17743. var opts = me.options;
  17744. if (opts.display && opts.pointLabels.display) {
  17745. fitWithPointLabels(me);
  17746. } else {
  17747. me.setCenterPoint(0, 0, 0, 0);
  17748. }
  17749. },
  17750. /**
  17751. * Set radius reductions and determine new radius and center point
  17752. * @private
  17753. */
  17754. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  17755. var me = this;
  17756. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  17757. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  17758. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  17759. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  17760. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  17761. radiusReductionRight = numberOrZero(radiusReductionRight);
  17762. radiusReductionTop = numberOrZero(radiusReductionTop);
  17763. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  17764. me.drawingArea = Math.min(
  17765. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  17766. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  17767. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  17768. },
  17769. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  17770. var me = this;
  17771. var maxRight = me.width - rightMovement - me.drawingArea;
  17772. var maxLeft = leftMovement + me.drawingArea;
  17773. var maxTop = topMovement + me.drawingArea;
  17774. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  17775. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  17776. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  17777. },
  17778. getIndexAngle: function(index) {
  17779. var chart = this.chart;
  17780. var angleMultiplier = 360 / chart.data.labels.length;
  17781. var options = chart.options || {};
  17782. var startAngle = options.startAngle || 0;
  17783. // Start from the top instead of right, so remove a quarter of the circle
  17784. var angle = (index * angleMultiplier + startAngle) % 360;
  17785. return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;
  17786. },
  17787. getDistanceFromCenterForValue: function(value) {
  17788. var me = this;
  17789. if (helpers$1.isNullOrUndef(value)) {
  17790. return NaN;
  17791. }
  17792. // Take into account half font size + the yPadding of the top value
  17793. var scalingFactor = me.drawingArea / (me.max - me.min);
  17794. if (me.options.ticks.reverse) {
  17795. return (me.max - value) * scalingFactor;
  17796. }
  17797. return (value - me.min) * scalingFactor;
  17798. },
  17799. getPointPosition: function(index, distanceFromCenter) {
  17800. var me = this;
  17801. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  17802. return {
  17803. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  17804. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  17805. };
  17806. },
  17807. getPointPositionForValue: function(index, value) {
  17808. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  17809. },
  17810. getBasePosition: function(index) {
  17811. var me = this;
  17812. var min = me.min;
  17813. var max = me.max;
  17814. return me.getPointPositionForValue(index || 0,
  17815. me.beginAtZero ? 0 :
  17816. min < 0 && max < 0 ? max :
  17817. min > 0 && max > 0 ? min :
  17818. 0);
  17819. },
  17820. /**
  17821. * @private
  17822. */
  17823. _drawGrid: function() {
  17824. var me = this;
  17825. var ctx = me.ctx;
  17826. var opts = me.options;
  17827. var gridLineOpts = opts.gridLines;
  17828. var angleLineOpts = opts.angleLines;
  17829. var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  17830. var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);
  17831. var i, offset, position;
  17832. if (opts.pointLabels.display) {
  17833. drawPointLabels(me);
  17834. }
  17835. if (gridLineOpts.display) {
  17836. helpers$1.each(me.ticks, function(label, index) {
  17837. if (index !== 0) {
  17838. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  17839. drawRadiusLine(me, gridLineOpts, offset, index);
  17840. }
  17841. });
  17842. }
  17843. if (angleLineOpts.display && lineWidth && lineColor) {
  17844. ctx.save();
  17845. ctx.lineWidth = lineWidth;
  17846. ctx.strokeStyle = lineColor;
  17847. if (ctx.setLineDash) {
  17848. ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  17849. ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  17850. }
  17851. for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
  17852. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  17853. position = me.getPointPosition(i, offset);
  17854. ctx.beginPath();
  17855. ctx.moveTo(me.xCenter, me.yCenter);
  17856. ctx.lineTo(position.x, position.y);
  17857. ctx.stroke();
  17858. }
  17859. ctx.restore();
  17860. }
  17861. },
  17862. /**
  17863. * @private
  17864. */
  17865. _drawLabels: function() {
  17866. var me = this;
  17867. var ctx = me.ctx;
  17868. var opts = me.options;
  17869. var tickOpts = opts.ticks;
  17870. if (!tickOpts.display) {
  17871. return;
  17872. }
  17873. var startAngle = me.getIndexAngle(0);
  17874. var tickFont = helpers$1.options._parseFont(tickOpts);
  17875. var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  17876. var offset, width;
  17877. ctx.save();
  17878. ctx.font = tickFont.string;
  17879. ctx.translate(me.xCenter, me.yCenter);
  17880. ctx.rotate(startAngle);
  17881. ctx.textAlign = 'center';
  17882. ctx.textBaseline = 'middle';
  17883. helpers$1.each(me.ticks, function(label, index) {
  17884. if (index === 0 && !tickOpts.reverse) {
  17885. return;
  17886. }
  17887. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  17888. if (tickOpts.showLabelBackdrop) {
  17889. width = ctx.measureText(label).width;
  17890. ctx.fillStyle = tickOpts.backdropColor;
  17891. ctx.fillRect(
  17892. -width / 2 - tickOpts.backdropPaddingX,
  17893. -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  17894. width + tickOpts.backdropPaddingX * 2,
  17895. tickFont.size + tickOpts.backdropPaddingY * 2
  17896. );
  17897. }
  17898. ctx.fillStyle = tickFontColor;
  17899. ctx.fillText(label, 0, -offset);
  17900. });
  17901. ctx.restore();
  17902. },
  17903. /**
  17904. * @private
  17905. */
  17906. _drawTitle: helpers$1.noop
  17907. });
  17908. // INTERNAL: static default options, registered in src/index.js
  17909. var _defaults$3 = defaultConfig$3;
  17910. scale_radialLinear._defaults = _defaults$3;
  17911. var deprecated$1 = helpers$1._deprecated;
  17912. var resolve$5 = helpers$1.options.resolve;
  17913. var valueOrDefault$d = helpers$1.valueOrDefault;
  17914. // Integer constants are from the ES6 spec.
  17915. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  17916. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  17917. var INTERVALS = {
  17918. millisecond: {
  17919. common: true,
  17920. size: 1,
  17921. steps: 1000
  17922. },
  17923. second: {
  17924. common: true,
  17925. size: 1000,
  17926. steps: 60
  17927. },
  17928. minute: {
  17929. common: true,
  17930. size: 60000,
  17931. steps: 60
  17932. },
  17933. hour: {
  17934. common: true,
  17935. size: 3600000,
  17936. steps: 24
  17937. },
  17938. day: {
  17939. common: true,
  17940. size: 86400000,
  17941. steps: 30
  17942. },
  17943. week: {
  17944. common: false,
  17945. size: 604800000,
  17946. steps: 4
  17947. },
  17948. month: {
  17949. common: true,
  17950. size: 2.628e9,
  17951. steps: 12
  17952. },
  17953. quarter: {
  17954. common: false,
  17955. size: 7.884e9,
  17956. steps: 4
  17957. },
  17958. year: {
  17959. common: true,
  17960. size: 3.154e10
  17961. }
  17962. };
  17963. var UNITS = Object.keys(INTERVALS);
  17964. function sorter(a, b) {
  17965. return a - b;
  17966. }
  17967. function arrayUnique(items) {
  17968. var hash = {};
  17969. var out = [];
  17970. var i, ilen, item;
  17971. for (i = 0, ilen = items.length; i < ilen; ++i) {
  17972. item = items[i];
  17973. if (!hash[item]) {
  17974. hash[item] = true;
  17975. out.push(item);
  17976. }
  17977. }
  17978. return out;
  17979. }
  17980. function getMin(options) {
  17981. return helpers$1.valueOrDefault(options.time.min, options.ticks.min);
  17982. }
  17983. function getMax(options) {
  17984. return helpers$1.valueOrDefault(options.time.max, options.ticks.max);
  17985. }
  17986. /**
  17987. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  17988. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  17989. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  17990. * extremity (left + width or top + height). Note that it would be more optimized to directly
  17991. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  17992. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  17993. *
  17994. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  17995. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  17996. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  17997. * If 'series', timestamps will be positioned at the same distance from each other. In this
  17998. * case, only timestamps that break the time linearity are registered, meaning that in the
  17999. * best case, all timestamps are linear, the table contains only min and max.
  18000. */
  18001. function buildLookupTable(timestamps, min, max, distribution) {
  18002. if (distribution === 'linear' || !timestamps.length) {
  18003. return [
  18004. {time: min, pos: 0},
  18005. {time: max, pos: 1}
  18006. ];
  18007. }
  18008. var table = [];
  18009. var items = [min];
  18010. var i, ilen, prev, curr, next;
  18011. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  18012. curr = timestamps[i];
  18013. if (curr > min && curr < max) {
  18014. items.push(curr);
  18015. }
  18016. }
  18017. items.push(max);
  18018. for (i = 0, ilen = items.length; i < ilen; ++i) {
  18019. next = items[i + 1];
  18020. prev = items[i - 1];
  18021. curr = items[i];
  18022. // only add points that breaks the scale linearity
  18023. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  18024. table.push({time: curr, pos: i / (ilen - 1)});
  18025. }
  18026. }
  18027. return table;
  18028. }
  18029. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  18030. function lookup(table, key, value) {
  18031. var lo = 0;
  18032. var hi = table.length - 1;
  18033. var mid, i0, i1;
  18034. while (lo >= 0 && lo <= hi) {
  18035. mid = (lo + hi) >> 1;
  18036. i0 = table[mid - 1] || null;
  18037. i1 = table[mid];
  18038. if (!i0) {
  18039. // given value is outside table (before first item)
  18040. return {lo: null, hi: i1};
  18041. } else if (i1[key] < value) {
  18042. lo = mid + 1;
  18043. } else if (i0[key] > value) {
  18044. hi = mid - 1;
  18045. } else {
  18046. return {lo: i0, hi: i1};
  18047. }
  18048. }
  18049. // given value is outside table (after last item)
  18050. return {lo: i1, hi: null};
  18051. }
  18052. /**
  18053. * Linearly interpolates the given source `value` using the table items `skey` values and
  18054. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  18055. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  18056. * index [0, 1] or [n - 1, n] are used for the interpolation.
  18057. */
  18058. function interpolate$1(table, skey, sval, tkey) {
  18059. var range = lookup(table, skey, sval);
  18060. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  18061. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  18062. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  18063. var span = next[skey] - prev[skey];
  18064. var ratio = span ? (sval - prev[skey]) / span : 0;
  18065. var offset = (next[tkey] - prev[tkey]) * ratio;
  18066. return prev[tkey] + offset;
  18067. }
  18068. function toTimestamp(scale, input) {
  18069. var adapter = scale._adapter;
  18070. var options = scale.options.time;
  18071. var parser = options.parser;
  18072. var format = parser || options.format;
  18073. var value = input;
  18074. if (typeof parser === 'function') {
  18075. value = parser(value);
  18076. }
  18077. // Only parse if its not a timestamp already
  18078. if (!helpers$1.isFinite(value)) {
  18079. value = typeof format === 'string'
  18080. ? adapter.parse(value, format)
  18081. : adapter.parse(value);
  18082. }
  18083. if (value !== null) {
  18084. return +value;
  18085. }
  18086. // Labels are in an incompatible format and no `parser` has been provided.
  18087. // The user might still use the deprecated `format` option for parsing.
  18088. if (!parser && typeof format === 'function') {
  18089. value = format(input);
  18090. // `format` could return something else than a timestamp, if so, parse it
  18091. if (!helpers$1.isFinite(value)) {
  18092. value = adapter.parse(value);
  18093. }
  18094. }
  18095. return value;
  18096. }
  18097. function parse(scale, input) {
  18098. if (helpers$1.isNullOrUndef(input)) {
  18099. return null;
  18100. }
  18101. var options = scale.options.time;
  18102. var value = toTimestamp(scale, scale.getRightValue(input));
  18103. if (value === null) {
  18104. return value;
  18105. }
  18106. if (options.round) {
  18107. value = +scale._adapter.startOf(value, options.round);
  18108. }
  18109. return value;
  18110. }
  18111. /**
  18112. * Figures out what unit results in an appropriate number of auto-generated ticks
  18113. */
  18114. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  18115. var ilen = UNITS.length;
  18116. var i, interval, factor;
  18117. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  18118. interval = INTERVALS[UNITS[i]];
  18119. factor = interval.steps ? interval.steps : MAX_INTEGER;
  18120. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  18121. return UNITS[i];
  18122. }
  18123. }
  18124. return UNITS[ilen - 1];
  18125. }
  18126. /**
  18127. * Figures out what unit to format a set of ticks with
  18128. */
  18129. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  18130. var i, unit;
  18131. for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  18132. unit = UNITS[i];
  18133. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  18134. return unit;
  18135. }
  18136. }
  18137. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  18138. }
  18139. function determineMajorUnit(unit) {
  18140. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  18141. if (INTERVALS[UNITS[i]].common) {
  18142. return UNITS[i];
  18143. }
  18144. }
  18145. }
  18146. /**
  18147. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  18148. * `minor` unit using the given scale time `options`.
  18149. * Important: this method can return ticks outside the min and max range, it's the
  18150. * responsibility of the calling code to clamp values if needed.
  18151. */
  18152. function generate(scale, min, max, capacity) {
  18153. var adapter = scale._adapter;
  18154. var options = scale.options;
  18155. var timeOpts = options.time;
  18156. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  18157. var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
  18158. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  18159. var first = min;
  18160. var ticks = [];
  18161. var time;
  18162. // For 'week' unit, handle the first day of week option
  18163. if (weekday) {
  18164. first = +adapter.startOf(first, 'isoWeek', weekday);
  18165. }
  18166. // Align first ticks on unit
  18167. first = +adapter.startOf(first, weekday ? 'day' : minor);
  18168. // Prevent browser from freezing in case user options request millions of milliseconds
  18169. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  18170. throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
  18171. }
  18172. for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {
  18173. ticks.push(time);
  18174. }
  18175. if (time === max || options.bounds === 'ticks') {
  18176. ticks.push(time);
  18177. }
  18178. return ticks;
  18179. }
  18180. /**
  18181. * Returns the start and end offsets from edges in the form of {start, end}
  18182. * where each value is a relative width to the scale and ranges between 0 and 1.
  18183. * They add extra margins on the both sides by scaling down the original scale.
  18184. * Offsets are added when the `offset` option is true.
  18185. */
  18186. function computeOffsets(table, ticks, min, max, options) {
  18187. var start = 0;
  18188. var end = 0;
  18189. var first, last;
  18190. if (options.offset && ticks.length) {
  18191. first = interpolate$1(table, 'time', ticks[0], 'pos');
  18192. if (ticks.length === 1) {
  18193. start = 1 - first;
  18194. } else {
  18195. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  18196. }
  18197. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  18198. if (ticks.length === 1) {
  18199. end = last;
  18200. } else {
  18201. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  18202. }
  18203. }
  18204. return {start: start, end: end, factor: 1 / (start + 1 + end)};
  18205. }
  18206. function setMajorTicks(scale, ticks, map, majorUnit) {
  18207. var adapter = scale._adapter;
  18208. var first = +adapter.startOf(ticks[0].value, majorUnit);
  18209. var last = ticks[ticks.length - 1].value;
  18210. var major, index;
  18211. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  18212. index = map[major];
  18213. if (index >= 0) {
  18214. ticks[index].major = true;
  18215. }
  18216. }
  18217. return ticks;
  18218. }
  18219. function ticksFromTimestamps(scale, values, majorUnit) {
  18220. var ticks = [];
  18221. var map = {};
  18222. var ilen = values.length;
  18223. var i, value;
  18224. for (i = 0; i < ilen; ++i) {
  18225. value = values[i];
  18226. map[value] = i;
  18227. ticks.push({
  18228. value: value,
  18229. major: false
  18230. });
  18231. }
  18232. // We set the major ticks separately from the above loop because calling startOf for every tick
  18233. // is expensive when there is a large number of ticks
  18234. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  18235. }
  18236. var defaultConfig$4 = {
  18237. position: 'bottom',
  18238. /**
  18239. * Data distribution along the scale:
  18240. * - 'linear': data are spread according to their time (distances can vary),
  18241. * - 'series': data are spread at the same distance from each other.
  18242. * @see https://github.com/chartjs/Chart.js/pull/4507
  18243. * @since 2.7.0
  18244. */
  18245. distribution: 'linear',
  18246. /**
  18247. * Scale boundary strategy (bypassed by min/max time options)
  18248. * - `data`: make sure data are fully visible, ticks outside are removed
  18249. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  18250. * @see https://github.com/chartjs/Chart.js/pull/4556
  18251. * @since 2.7.0
  18252. */
  18253. bounds: 'data',
  18254. adapters: {},
  18255. time: {
  18256. 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
  18257. unit: false, // false == automatic or override with week, month, year, etc.
  18258. round: false, // none, or override with week, month, year, etc.
  18259. displayFormat: false, // DEPRECATED
  18260. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  18261. minUnit: 'millisecond',
  18262. displayFormats: {}
  18263. },
  18264. ticks: {
  18265. autoSkip: false,
  18266. /**
  18267. * Ticks generation input values:
  18268. * - 'auto': generates "optimal" ticks based on scale size and time options.
  18269. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  18270. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  18271. * @see https://github.com/chartjs/Chart.js/pull/4507
  18272. * @since 2.7.0
  18273. */
  18274. source: 'auto',
  18275. major: {
  18276. enabled: false
  18277. }
  18278. }
  18279. };
  18280. var scale_time = core_scale.extend({
  18281. initialize: function() {
  18282. this.mergeTicksOptions();
  18283. core_scale.prototype.initialize.call(this);
  18284. },
  18285. update: function() {
  18286. var me = this;
  18287. var options = me.options;
  18288. var time = options.time || (options.time = {});
  18289. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  18290. // DEPRECATIONS: output a message only one time per update
  18291. deprecated$1('time scale', time.format, 'time.format', 'time.parser');
  18292. deprecated$1('time scale', time.min, 'time.min', 'ticks.min');
  18293. deprecated$1('time scale', time.max, 'time.max', 'ticks.max');
  18294. // Backward compatibility: before introducing adapter, `displayFormats` was
  18295. // supposed to contain *all* unit/string pairs but this can't be resolved
  18296. // when loading the scale (adapters are loaded afterward), so let's populate
  18297. // missing formats on update
  18298. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  18299. return core_scale.prototype.update.apply(me, arguments);
  18300. },
  18301. /**
  18302. * Allows data to be referenced via 't' attribute
  18303. */
  18304. getRightValue: function(rawValue) {
  18305. if (rawValue && rawValue.t !== undefined) {
  18306. rawValue = rawValue.t;
  18307. }
  18308. return core_scale.prototype.getRightValue.call(this, rawValue);
  18309. },
  18310. determineDataLimits: function() {
  18311. var me = this;
  18312. var chart = me.chart;
  18313. var adapter = me._adapter;
  18314. var options = me.options;
  18315. var unit = options.time.unit || 'day';
  18316. var min = MAX_INTEGER;
  18317. var max = MIN_INTEGER;
  18318. var timestamps = [];
  18319. var datasets = [];
  18320. var labels = [];
  18321. var i, j, ilen, jlen, data, timestamp, labelsAdded;
  18322. var dataLabels = me._getLabels();
  18323. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  18324. labels.push(parse(me, dataLabels[i]));
  18325. }
  18326. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  18327. if (chart.isDatasetVisible(i)) {
  18328. data = chart.data.datasets[i].data;
  18329. // Let's consider that all data have the same format.
  18330. if (helpers$1.isObject(data[0])) {
  18331. datasets[i] = [];
  18332. for (j = 0, jlen = data.length; j < jlen; ++j) {
  18333. timestamp = parse(me, data[j]);
  18334. timestamps.push(timestamp);
  18335. datasets[i][j] = timestamp;
  18336. }
  18337. } else {
  18338. datasets[i] = labels.slice(0);
  18339. if (!labelsAdded) {
  18340. timestamps = timestamps.concat(labels);
  18341. labelsAdded = true;
  18342. }
  18343. }
  18344. } else {
  18345. datasets[i] = [];
  18346. }
  18347. }
  18348. if (labels.length) {
  18349. min = Math.min(min, labels[0]);
  18350. max = Math.max(max, labels[labels.length - 1]);
  18351. }
  18352. if (timestamps.length) {
  18353. timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);
  18354. min = Math.min(min, timestamps[0]);
  18355. max = Math.max(max, timestamps[timestamps.length - 1]);
  18356. }
  18357. min = parse(me, getMin(options)) || min;
  18358. max = parse(me, getMax(options)) || max;
  18359. // In case there is no valid min/max, set limits based on unit time option
  18360. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  18361. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  18362. // Make sure that max is strictly higher than min (required by the lookup table)
  18363. me.min = Math.min(min, max);
  18364. me.max = Math.max(min + 1, max);
  18365. // PRIVATE
  18366. me._table = [];
  18367. me._timestamps = {
  18368. data: timestamps,
  18369. datasets: datasets,
  18370. labels: labels
  18371. };
  18372. },
  18373. buildTicks: function() {
  18374. var me = this;
  18375. var min = me.min;
  18376. var max = me.max;
  18377. var options = me.options;
  18378. var tickOpts = options.ticks;
  18379. var timeOpts = options.time;
  18380. var timestamps = me._timestamps;
  18381. var ticks = [];
  18382. var capacity = me.getLabelCapacity(min);
  18383. var source = tickOpts.source;
  18384. var distribution = options.distribution;
  18385. var i, ilen, timestamp;
  18386. if (source === 'data' || (source === 'auto' && distribution === 'series')) {
  18387. timestamps = timestamps.data;
  18388. } else if (source === 'labels') {
  18389. timestamps = timestamps.labels;
  18390. } else {
  18391. timestamps = generate(me, min, max, capacity);
  18392. }
  18393. if (options.bounds === 'ticks' && timestamps.length) {
  18394. min = timestamps[0];
  18395. max = timestamps[timestamps.length - 1];
  18396. }
  18397. // Enforce limits with user min/max options
  18398. min = parse(me, getMin(options)) || min;
  18399. max = parse(me, getMax(options)) || max;
  18400. // Remove ticks outside the min/max range
  18401. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  18402. timestamp = timestamps[i];
  18403. if (timestamp >= min && timestamp <= max) {
  18404. ticks.push(timestamp);
  18405. }
  18406. }
  18407. me.min = min;
  18408. me.max = max;
  18409. // PRIVATE
  18410. // determineUnitForFormatting relies on the number of ticks so we don't use it when
  18411. // autoSkip is enabled because we don't yet know what the final number of ticks will be
  18412. me._unit = timeOpts.unit || (tickOpts.autoSkip
  18413. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
  18414. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  18415. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  18416. : determineMajorUnit(me._unit);
  18417. me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
  18418. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  18419. if (tickOpts.reverse) {
  18420. ticks.reverse();
  18421. }
  18422. return ticksFromTimestamps(me, ticks, me._majorUnit);
  18423. },
  18424. getLabelForIndex: function(index, datasetIndex) {
  18425. var me = this;
  18426. var adapter = me._adapter;
  18427. var data = me.chart.data;
  18428. var timeOpts = me.options.time;
  18429. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  18430. var value = data.datasets[datasetIndex].data[index];
  18431. if (helpers$1.isObject(value)) {
  18432. label = me.getRightValue(value);
  18433. }
  18434. if (timeOpts.tooltipFormat) {
  18435. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  18436. }
  18437. if (typeof label === 'string') {
  18438. return label;
  18439. }
  18440. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  18441. },
  18442. /**
  18443. * Function to format an individual tick mark
  18444. * @private
  18445. */
  18446. tickFormatFunction: function(time, index, ticks, format) {
  18447. var me = this;
  18448. var adapter = me._adapter;
  18449. var options = me.options;
  18450. var formats = options.time.displayFormats;
  18451. var minorFormat = formats[me._unit];
  18452. var majorUnit = me._majorUnit;
  18453. var majorFormat = formats[majorUnit];
  18454. var tick = ticks[index];
  18455. var tickOpts = options.ticks;
  18456. var major = majorUnit && majorFormat && tick && tick.major;
  18457. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  18458. var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;
  18459. var formatter = resolve$5([
  18460. nestedTickOpts.callback,
  18461. nestedTickOpts.userCallback,
  18462. tickOpts.callback,
  18463. tickOpts.userCallback
  18464. ]);
  18465. return formatter ? formatter(label, index, ticks) : label;
  18466. },
  18467. convertTicksToLabels: function(ticks) {
  18468. var labels = [];
  18469. var i, ilen;
  18470. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  18471. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  18472. }
  18473. return labels;
  18474. },
  18475. /**
  18476. * @private
  18477. */
  18478. getPixelForOffset: function(time) {
  18479. var me = this;
  18480. var offsets = me._offsets;
  18481. var pos = interpolate$1(me._table, 'time', time, 'pos');
  18482. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  18483. },
  18484. getPixelForValue: function(value, index, datasetIndex) {
  18485. var me = this;
  18486. var time = null;
  18487. if (index !== undefined && datasetIndex !== undefined) {
  18488. time = me._timestamps.datasets[datasetIndex][index];
  18489. }
  18490. if (time === null) {
  18491. time = parse(me, value);
  18492. }
  18493. if (time !== null) {
  18494. return me.getPixelForOffset(time);
  18495. }
  18496. },
  18497. getPixelForTick: function(index) {
  18498. var ticks = this.getTicks();
  18499. return index >= 0 && index < ticks.length ?
  18500. this.getPixelForOffset(ticks[index].value) :
  18501. null;
  18502. },
  18503. getValueForPixel: function(pixel) {
  18504. var me = this;
  18505. var offsets = me._offsets;
  18506. var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  18507. var time = interpolate$1(me._table, 'pos', pos, 'time');
  18508. // DEPRECATION, we should return time directly
  18509. return me._adapter._create(time);
  18510. },
  18511. /**
  18512. * @private
  18513. */
  18514. _getLabelSize: function(label) {
  18515. var me = this;
  18516. var ticksOpts = me.options.ticks;
  18517. var tickLabelWidth = me.ctx.measureText(label).width;
  18518. var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  18519. var cosRotation = Math.cos(angle);
  18520. var sinRotation = Math.sin(angle);
  18521. var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  18522. return {
  18523. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  18524. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  18525. };
  18526. },
  18527. /**
  18528. * Crude approximation of what the label width might be
  18529. * @private
  18530. */
  18531. getLabelWidth: function(label) {
  18532. return this._getLabelSize(label).w;
  18533. },
  18534. /**
  18535. * @private
  18536. */
  18537. getLabelCapacity: function(exampleTime) {
  18538. var me = this;
  18539. var timeOpts = me.options.time;
  18540. var displayFormats = timeOpts.displayFormats;
  18541. // pick the longest format (milliseconds) for guestimation
  18542. var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  18543. var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  18544. var size = me._getLabelSize(exampleLabel);
  18545. var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);
  18546. if (me.options.offset) {
  18547. capacity--;
  18548. }
  18549. return capacity > 0 ? capacity : 1;
  18550. }
  18551. });
  18552. // INTERNAL: static default options, registered in src/index.js
  18553. var _defaults$4 = defaultConfig$4;
  18554. scale_time._defaults = _defaults$4;
  18555. var scales = {
  18556. category: scale_category,
  18557. linear: scale_linear,
  18558. logarithmic: scale_logarithmic,
  18559. radialLinear: scale_radialLinear,
  18560. time: scale_time
  18561. };
  18562. var FORMATS = {
  18563. datetime: 'MMM D, YYYY, h:mm:ss a',
  18564. millisecond: 'h:mm:ss.SSS a',
  18565. second: 'h:mm:ss a',
  18566. minute: 'h:mm a',
  18567. hour: 'hA',
  18568. day: 'MMM D',
  18569. week: 'll',
  18570. month: 'MMM YYYY',
  18571. quarter: '[Q]Q - YYYY',
  18572. year: 'YYYY'
  18573. };
  18574. core_adapters._date.override(typeof moment === 'function' ? {
  18575. _id: 'moment', // DEBUG ONLY
  18576. formats: function() {
  18577. return FORMATS;
  18578. },
  18579. parse: function(value, format) {
  18580. if (typeof value === 'string' && typeof format === 'string') {
  18581. value = moment(value, format);
  18582. } else if (!(value instanceof moment)) {
  18583. value = moment(value);
  18584. }
  18585. return value.isValid() ? value.valueOf() : null;
  18586. },
  18587. format: function(time, format) {
  18588. return moment(time).format(format);
  18589. },
  18590. add: function(time, amount, unit) {
  18591. return moment(time).add(amount, unit).valueOf();
  18592. },
  18593. diff: function(max, min, unit) {
  18594. return moment(max).diff(moment(min), unit);
  18595. },
  18596. startOf: function(time, unit, weekday) {
  18597. time = moment(time);
  18598. if (unit === 'isoWeek') {
  18599. return time.isoWeekday(weekday).valueOf();
  18600. }
  18601. return time.startOf(unit).valueOf();
  18602. },
  18603. endOf: function(time, unit) {
  18604. return moment(time).endOf(unit).valueOf();
  18605. },
  18606. // DEPRECATIONS
  18607. /**
  18608. * Provided for backward compatibility with scale.getValueForPixel().
  18609. * @deprecated since version 2.8.0
  18610. * @todo remove at version 3
  18611. * @private
  18612. */
  18613. _create: function(time) {
  18614. return moment(time);
  18615. },
  18616. } : {});
  18617. core_defaults._set('global', {
  18618. plugins: {
  18619. filler: {
  18620. propagate: true
  18621. }
  18622. }
  18623. });
  18624. var mappers = {
  18625. dataset: function(source) {
  18626. var index = source.fill;
  18627. var chart = source.chart;
  18628. var meta = chart.getDatasetMeta(index);
  18629. var visible = meta && chart.isDatasetVisible(index);
  18630. var points = (visible && meta.dataset._children) || [];
  18631. var length = points.length || 0;
  18632. return !length ? null : function(point, i) {
  18633. return (i < length && points[i]._view) || null;
  18634. };
  18635. },
  18636. boundary: function(source) {
  18637. var boundary = source.boundary;
  18638. var x = boundary ? boundary.x : null;
  18639. var y = boundary ? boundary.y : null;
  18640. if (helpers$1.isArray(boundary)) {
  18641. return function(point, i) {
  18642. return boundary[i];
  18643. };
  18644. }
  18645. return function(point) {
  18646. return {
  18647. x: x === null ? point.x : x,
  18648. y: y === null ? point.y : y,
  18649. };
  18650. };
  18651. }
  18652. };
  18653. // @todo if (fill[0] === '#')
  18654. function decodeFill(el, index, count) {
  18655. var model = el._model || {};
  18656. var fill = model.fill;
  18657. var target;
  18658. if (fill === undefined) {
  18659. fill = !!model.backgroundColor;
  18660. }
  18661. if (fill === false || fill === null) {
  18662. return false;
  18663. }
  18664. if (fill === true) {
  18665. return 'origin';
  18666. }
  18667. target = parseFloat(fill, 10);
  18668. if (isFinite(target) && Math.floor(target) === target) {
  18669. if (fill[0] === '-' || fill[0] === '+') {
  18670. target = index + target;
  18671. }
  18672. if (target === index || target < 0 || target >= count) {
  18673. return false;
  18674. }
  18675. return target;
  18676. }
  18677. switch (fill) {
  18678. // compatibility
  18679. case 'bottom':
  18680. return 'start';
  18681. case 'top':
  18682. return 'end';
  18683. case 'zero':
  18684. return 'origin';
  18685. // supported boundaries
  18686. case 'origin':
  18687. case 'start':
  18688. case 'end':
  18689. return fill;
  18690. // invalid fill values
  18691. default:
  18692. return false;
  18693. }
  18694. }
  18695. function computeLinearBoundary(source) {
  18696. var model = source.el._model || {};
  18697. var scale = source.el._scale || {};
  18698. var fill = source.fill;
  18699. var target = null;
  18700. var horizontal;
  18701. if (isFinite(fill)) {
  18702. return null;
  18703. }
  18704. // Backward compatibility: until v3, we still need to support boundary values set on
  18705. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  18706. // controllers might still use it (e.g. the Smith chart).
  18707. if (fill === 'start') {
  18708. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  18709. } else if (fill === 'end') {
  18710. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  18711. } else if (model.scaleZero !== undefined) {
  18712. target = model.scaleZero;
  18713. } else if (scale.getBasePixel) {
  18714. target = scale.getBasePixel();
  18715. }
  18716. if (target !== undefined && target !== null) {
  18717. if (target.x !== undefined && target.y !== undefined) {
  18718. return target;
  18719. }
  18720. if (helpers$1.isFinite(target)) {
  18721. horizontal = scale.isHorizontal();
  18722. return {
  18723. x: horizontal ? target : null,
  18724. y: horizontal ? null : target
  18725. };
  18726. }
  18727. }
  18728. return null;
  18729. }
  18730. function computeCircularBoundary(source) {
  18731. var scale = source.el._scale;
  18732. var options = scale.options;
  18733. var length = scale.chart.data.labels.length;
  18734. var fill = source.fill;
  18735. var target = [];
  18736. var start, end, center, i, point;
  18737. if (!length) {
  18738. return null;
  18739. }
  18740. start = options.ticks.reverse ? scale.max : scale.min;
  18741. end = options.ticks.reverse ? scale.min : scale.max;
  18742. center = scale.getPointPositionForValue(0, start);
  18743. for (i = 0; i < length; ++i) {
  18744. point = fill === 'start' || fill === 'end'
  18745. ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)
  18746. : scale.getBasePosition(i);
  18747. if (options.gridLines.circular) {
  18748. point.cx = center.x;
  18749. point.cy = center.y;
  18750. point.angle = scale.getIndexAngle(i) - Math.PI / 2;
  18751. }
  18752. target.push(point);
  18753. }
  18754. return target;
  18755. }
  18756. function computeBoundary(source) {
  18757. var scale = source.el._scale || {};
  18758. if (scale.getPointPositionForValue) {
  18759. return computeCircularBoundary(source);
  18760. }
  18761. return computeLinearBoundary(source);
  18762. }
  18763. function resolveTarget(sources, index, propagate) {
  18764. var source = sources[index];
  18765. var fill = source.fill;
  18766. var visited = [index];
  18767. var target;
  18768. if (!propagate) {
  18769. return fill;
  18770. }
  18771. while (fill !== false && visited.indexOf(fill) === -1) {
  18772. if (!isFinite(fill)) {
  18773. return fill;
  18774. }
  18775. target = sources[fill];
  18776. if (!target) {
  18777. return false;
  18778. }
  18779. if (target.visible) {
  18780. return fill;
  18781. }
  18782. visited.push(fill);
  18783. fill = target.fill;
  18784. }
  18785. return false;
  18786. }
  18787. function createMapper(source) {
  18788. var fill = source.fill;
  18789. var type = 'dataset';
  18790. if (fill === false) {
  18791. return null;
  18792. }
  18793. if (!isFinite(fill)) {
  18794. type = 'boundary';
  18795. }
  18796. return mappers[type](source);
  18797. }
  18798. function isDrawable(point) {
  18799. return point && !point.skip;
  18800. }
  18801. function drawArea(ctx, curve0, curve1, len0, len1) {
  18802. var i, cx, cy, r;
  18803. if (!len0 || !len1) {
  18804. return;
  18805. }
  18806. // building first area curve (normal)
  18807. ctx.moveTo(curve0[0].x, curve0[0].y);
  18808. for (i = 1; i < len0; ++i) {
  18809. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  18810. }
  18811. if (curve1[0].angle !== undefined) {
  18812. cx = curve1[0].cx;
  18813. cy = curve1[0].cy;
  18814. r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));
  18815. for (i = len1 - 1; i > 0; --i) {
  18816. ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);
  18817. }
  18818. return;
  18819. }
  18820. // joining the two area curves
  18821. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  18822. // building opposite area curve (reverse)
  18823. for (i = len1 - 1; i > 0; --i) {
  18824. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  18825. }
  18826. }
  18827. function doFill(ctx, points, mapper, view, color, loop) {
  18828. var count = points.length;
  18829. var span = view.spanGaps;
  18830. var curve0 = [];
  18831. var curve1 = [];
  18832. var len0 = 0;
  18833. var len1 = 0;
  18834. var i, ilen, index, p0, p1, d0, d1, loopOffset;
  18835. ctx.beginPath();
  18836. for (i = 0, ilen = count; i < ilen; ++i) {
  18837. index = i % count;
  18838. p0 = points[index]._view;
  18839. p1 = mapper(p0, index, view);
  18840. d0 = isDrawable(p0);
  18841. d1 = isDrawable(p1);
  18842. if (loop && loopOffset === undefined && d0) {
  18843. loopOffset = i + 1;
  18844. ilen = count + loopOffset;
  18845. }
  18846. if (d0 && d1) {
  18847. len0 = curve0.push(p0);
  18848. len1 = curve1.push(p1);
  18849. } else if (len0 && len1) {
  18850. if (!span) {
  18851. drawArea(ctx, curve0, curve1, len0, len1);
  18852. len0 = len1 = 0;
  18853. curve0 = [];
  18854. curve1 = [];
  18855. } else {
  18856. if (d0) {
  18857. curve0.push(p0);
  18858. }
  18859. if (d1) {
  18860. curve1.push(p1);
  18861. }
  18862. }
  18863. }
  18864. }
  18865. drawArea(ctx, curve0, curve1, len0, len1);
  18866. ctx.closePath();
  18867. ctx.fillStyle = color;
  18868. ctx.fill();
  18869. }
  18870. var plugin_filler = {
  18871. id: 'filler',
  18872. afterDatasetsUpdate: function(chart, options) {
  18873. var count = (chart.data.datasets || []).length;
  18874. var propagate = options.propagate;
  18875. var sources = [];
  18876. var meta, i, el, source;
  18877. for (i = 0; i < count; ++i) {
  18878. meta = chart.getDatasetMeta(i);
  18879. el = meta.dataset;
  18880. source = null;
  18881. if (el && el._model && el instanceof elements.Line) {
  18882. source = {
  18883. visible: chart.isDatasetVisible(i),
  18884. fill: decodeFill(el, i, count),
  18885. chart: chart,
  18886. el: el
  18887. };
  18888. }
  18889. meta.$filler = source;
  18890. sources.push(source);
  18891. }
  18892. for (i = 0; i < count; ++i) {
  18893. source = sources[i];
  18894. if (!source) {
  18895. continue;
  18896. }
  18897. source.fill = resolveTarget(sources, i, propagate);
  18898. source.boundary = computeBoundary(source);
  18899. source.mapper = createMapper(source);
  18900. }
  18901. },
  18902. beforeDatasetsDraw: function(chart) {
  18903. var metasets = chart._getSortedVisibleDatasetMetas();
  18904. var ctx = chart.ctx;
  18905. var meta, i, el, view, points, mapper, color;
  18906. for (i = metasets.length - 1; i >= 0; --i) {
  18907. meta = metasets[i].$filler;
  18908. if (!meta || !meta.visible) {
  18909. continue;
  18910. }
  18911. el = meta.el;
  18912. view = el._view;
  18913. points = el._children || [];
  18914. mapper = meta.mapper;
  18915. color = view.backgroundColor || core_defaults.global.defaultColor;
  18916. if (mapper && color && points.length) {
  18917. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  18918. doFill(ctx, points, mapper, view, color, el._loop);
  18919. helpers$1.canvas.unclipArea(ctx);
  18920. }
  18921. }
  18922. }
  18923. };
  18924. var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;
  18925. var noop$1 = helpers$1.noop;
  18926. var valueOrDefault$e = helpers$1.valueOrDefault;
  18927. core_defaults._set('global', {
  18928. legend: {
  18929. display: true,
  18930. position: 'top',
  18931. align: 'center',
  18932. fullWidth: true,
  18933. reverse: false,
  18934. weight: 1000,
  18935. // a callback that will handle
  18936. onClick: function(e, legendItem) {
  18937. var index = legendItem.datasetIndex;
  18938. var ci = this.chart;
  18939. var meta = ci.getDatasetMeta(index);
  18940. // See controller.isDatasetVisible comment
  18941. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  18942. // We hid a dataset ... rerender the chart
  18943. ci.update();
  18944. },
  18945. onHover: null,
  18946. onLeave: null,
  18947. labels: {
  18948. boxWidth: 40,
  18949. padding: 10,
  18950. // Generates labels shown in the legend
  18951. // Valid properties to return:
  18952. // text : text to display
  18953. // fillStyle : fill of coloured box
  18954. // strokeStyle: stroke of coloured box
  18955. // hidden : if this legend item refers to a hidden item
  18956. // lineCap : cap style for line
  18957. // lineDash
  18958. // lineDashOffset :
  18959. // lineJoin :
  18960. // lineWidth :
  18961. generateLabels: function(chart) {
  18962. var datasets = chart.data.datasets;
  18963. var options = chart.options.legend || {};
  18964. var usePointStyle = options.labels && options.labels.usePointStyle;
  18965. return chart._getSortedDatasetMetas().map(function(meta) {
  18966. var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  18967. return {
  18968. text: datasets[meta.index].label,
  18969. fillStyle: style.backgroundColor,
  18970. hidden: !chart.isDatasetVisible(meta.index),
  18971. lineCap: style.borderCapStyle,
  18972. lineDash: style.borderDash,
  18973. lineDashOffset: style.borderDashOffset,
  18974. lineJoin: style.borderJoinStyle,
  18975. lineWidth: style.borderWidth,
  18976. strokeStyle: style.borderColor,
  18977. pointStyle: style.pointStyle,
  18978. rotation: style.rotation,
  18979. // Below is extra data used for toggling the datasets
  18980. datasetIndex: meta.index
  18981. };
  18982. }, this);
  18983. }
  18984. }
  18985. },
  18986. legendCallback: function(chart) {
  18987. var list = document.createElement('ul');
  18988. var datasets = chart.data.datasets;
  18989. var i, ilen, listItem, listItemSpan;
  18990. list.setAttribute('class', chart.id + '-legend');
  18991. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  18992. listItem = list.appendChild(document.createElement('li'));
  18993. listItemSpan = listItem.appendChild(document.createElement('span'));
  18994. listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
  18995. if (datasets[i].label) {
  18996. listItem.appendChild(document.createTextNode(datasets[i].label));
  18997. }
  18998. }
  18999. return list.outerHTML;
  19000. }
  19001. });
  19002. /**
  19003. * Helper function to get the box width based on the usePointStyle option
  19004. * @param {object} labelopts - the label options on the legend
  19005. * @param {number} fontSize - the label font size
  19006. * @return {number} width of the color box area
  19007. */
  19008. function getBoxWidth(labelOpts, fontSize) {
  19009. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  19010. fontSize :
  19011. labelOpts.boxWidth;
  19012. }
  19013. /**
  19014. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  19015. */
  19016. var Legend = core_element.extend({
  19017. initialize: function(config) {
  19018. var me = this;
  19019. helpers$1.extend(me, config);
  19020. // Contains hit boxes for each dataset (in dataset order)
  19021. me.legendHitBoxes = [];
  19022. /**
  19023. * @private
  19024. */
  19025. me._hoveredItem = null;
  19026. // Are we in doughnut mode which has a different data type
  19027. me.doughnutMode = false;
  19028. },
  19029. // These methods are ordered by lifecycle. Utilities then follow.
  19030. // Any function defined here is inherited by all legend types.
  19031. // Any function can be extended by the legend type
  19032. beforeUpdate: noop$1,
  19033. update: function(maxWidth, maxHeight, margins) {
  19034. var me = this;
  19035. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  19036. me.beforeUpdate();
  19037. // Absorb the master measurements
  19038. me.maxWidth = maxWidth;
  19039. me.maxHeight = maxHeight;
  19040. me.margins = margins;
  19041. // Dimensions
  19042. me.beforeSetDimensions();
  19043. me.setDimensions();
  19044. me.afterSetDimensions();
  19045. // Labels
  19046. me.beforeBuildLabels();
  19047. me.buildLabels();
  19048. me.afterBuildLabels();
  19049. // Fit
  19050. me.beforeFit();
  19051. me.fit();
  19052. me.afterFit();
  19053. //
  19054. me.afterUpdate();
  19055. return me.minSize;
  19056. },
  19057. afterUpdate: noop$1,
  19058. //
  19059. beforeSetDimensions: noop$1,
  19060. setDimensions: function() {
  19061. var me = this;
  19062. // Set the unconstrained dimension before label rotation
  19063. if (me.isHorizontal()) {
  19064. // Reset position before calculating rotation
  19065. me.width = me.maxWidth;
  19066. me.left = 0;
  19067. me.right = me.width;
  19068. } else {
  19069. me.height = me.maxHeight;
  19070. // Reset position before calculating rotation
  19071. me.top = 0;
  19072. me.bottom = me.height;
  19073. }
  19074. // Reset padding
  19075. me.paddingLeft = 0;
  19076. me.paddingTop = 0;
  19077. me.paddingRight = 0;
  19078. me.paddingBottom = 0;
  19079. // Reset minSize
  19080. me.minSize = {
  19081. width: 0,
  19082. height: 0
  19083. };
  19084. },
  19085. afterSetDimensions: noop$1,
  19086. //
  19087. beforeBuildLabels: noop$1,
  19088. buildLabels: function() {
  19089. var me = this;
  19090. var labelOpts = me.options.labels || {};
  19091. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  19092. if (labelOpts.filter) {
  19093. legendItems = legendItems.filter(function(item) {
  19094. return labelOpts.filter(item, me.chart.data);
  19095. });
  19096. }
  19097. if (me.options.reverse) {
  19098. legendItems.reverse();
  19099. }
  19100. me.legendItems = legendItems;
  19101. },
  19102. afterBuildLabels: noop$1,
  19103. //
  19104. beforeFit: noop$1,
  19105. fit: function() {
  19106. var me = this;
  19107. var opts = me.options;
  19108. var labelOpts = opts.labels;
  19109. var display = opts.display;
  19110. var ctx = me.ctx;
  19111. var labelFont = helpers$1.options._parseFont(labelOpts);
  19112. var fontSize = labelFont.size;
  19113. // Reset hit boxes
  19114. var hitboxes = me.legendHitBoxes = [];
  19115. var minSize = me.minSize;
  19116. var isHorizontal = me.isHorizontal();
  19117. if (isHorizontal) {
  19118. minSize.width = me.maxWidth; // fill all the width
  19119. minSize.height = display ? 10 : 0;
  19120. } else {
  19121. minSize.width = display ? 10 : 0;
  19122. minSize.height = me.maxHeight; // fill all the height
  19123. }
  19124. // Increase sizes here
  19125. if (!display) {
  19126. me.width = minSize.width = me.height = minSize.height = 0;
  19127. return;
  19128. }
  19129. ctx.font = labelFont.string;
  19130. if (isHorizontal) {
  19131. // Labels
  19132. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  19133. var lineWidths = me.lineWidths = [0];
  19134. var totalHeight = 0;
  19135. ctx.textAlign = 'left';
  19136. ctx.textBaseline = 'middle';
  19137. helpers$1.each(me.legendItems, function(legendItem, i) {
  19138. var boxWidth = getBoxWidth(labelOpts, fontSize);
  19139. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  19140. if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {
  19141. totalHeight += fontSize + labelOpts.padding;
  19142. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  19143. }
  19144. // Store the hitbox width and height here. Final position will be updated in `draw`
  19145. hitboxes[i] = {
  19146. left: 0,
  19147. top: 0,
  19148. width: width,
  19149. height: fontSize
  19150. };
  19151. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  19152. });
  19153. minSize.height += totalHeight;
  19154. } else {
  19155. var vPadding = labelOpts.padding;
  19156. var columnWidths = me.columnWidths = [];
  19157. var columnHeights = me.columnHeights = [];
  19158. var totalWidth = labelOpts.padding;
  19159. var currentColWidth = 0;
  19160. var currentColHeight = 0;
  19161. helpers$1.each(me.legendItems, function(legendItem, i) {
  19162. var boxWidth = getBoxWidth(labelOpts, fontSize);
  19163. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  19164. // If too tall, go to new column
  19165. if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) {
  19166. totalWidth += currentColWidth + labelOpts.padding;
  19167. columnWidths.push(currentColWidth); // previous column width
  19168. columnHeights.push(currentColHeight);
  19169. currentColWidth = 0;
  19170. currentColHeight = 0;
  19171. }
  19172. // Get max width
  19173. currentColWidth = Math.max(currentColWidth, itemWidth);
  19174. currentColHeight += fontSize + vPadding;
  19175. // Store the hitbox width and height here. Final position will be updated in `draw`
  19176. hitboxes[i] = {
  19177. left: 0,
  19178. top: 0,
  19179. width: itemWidth,
  19180. height: fontSize
  19181. };
  19182. });
  19183. totalWidth += currentColWidth;
  19184. columnWidths.push(currentColWidth);
  19185. columnHeights.push(currentColHeight);
  19186. minSize.width += totalWidth;
  19187. }
  19188. me.width = minSize.width;
  19189. me.height = minSize.height;
  19190. },
  19191. afterFit: noop$1,
  19192. // Shared Methods
  19193. isHorizontal: function() {
  19194. return this.options.position === 'top' || this.options.position === 'bottom';
  19195. },
  19196. // Actually draw the legend on the canvas
  19197. draw: function() {
  19198. var me = this;
  19199. var opts = me.options;
  19200. var labelOpts = opts.labels;
  19201. var globalDefaults = core_defaults.global;
  19202. var defaultColor = globalDefaults.defaultColor;
  19203. var lineDefault = globalDefaults.elements.line;
  19204. var legendHeight = me.height;
  19205. var columnHeights = me.columnHeights;
  19206. var legendWidth = me.width;
  19207. var lineWidths = me.lineWidths;
  19208. if (!opts.display) {
  19209. return;
  19210. }
  19211. var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);
  19212. var ctx = me.ctx;
  19213. var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);
  19214. var labelFont = helpers$1.options._parseFont(labelOpts);
  19215. var fontSize = labelFont.size;
  19216. var cursor;
  19217. // Canvas setup
  19218. ctx.textAlign = rtlHelper.textAlign('left');
  19219. ctx.textBaseline = 'middle';
  19220. ctx.lineWidth = 0.5;
  19221. ctx.strokeStyle = fontColor; // for strikethrough effect
  19222. ctx.fillStyle = fontColor; // render in correct colour
  19223. ctx.font = labelFont.string;
  19224. var boxWidth = getBoxWidth(labelOpts, fontSize);
  19225. var hitboxes = me.legendHitBoxes;
  19226. // current position
  19227. var drawLegendBox = function(x, y, legendItem) {
  19228. if (isNaN(boxWidth) || boxWidth <= 0) {
  19229. return;
  19230. }
  19231. // Set the ctx for the box
  19232. ctx.save();
  19233. var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);
  19234. ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);
  19235. ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);
  19236. ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  19237. ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);
  19238. ctx.lineWidth = lineWidth;
  19239. ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);
  19240. if (ctx.setLineDash) {
  19241. // IE 9 and 10 do not support line dash
  19242. ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));
  19243. }
  19244. if (labelOpts && labelOpts.usePointStyle) {
  19245. // Recalculate x and y for drawPoint() because its expecting
  19246. // x and y to be center of figure (instead of top left)
  19247. var radius = boxWidth * Math.SQRT2 / 2;
  19248. var centerX = rtlHelper.xPlus(x, boxWidth / 2);
  19249. var centerY = y + fontSize / 2;
  19250. // Draw pointStyle as legend symbol
  19251. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
  19252. } else {
  19253. // Draw box as legend symbol
  19254. ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  19255. if (lineWidth !== 0) {
  19256. ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  19257. }
  19258. }
  19259. ctx.restore();
  19260. };
  19261. var fillText = function(x, y, legendItem, textWidth) {
  19262. var halfFontSize = fontSize / 2;
  19263. var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
  19264. var yMiddle = y + halfFontSize;
  19265. ctx.fillText(legendItem.text, xLeft, yMiddle);
  19266. if (legendItem.hidden) {
  19267. // Strikethrough the text if hidden
  19268. ctx.beginPath();
  19269. ctx.lineWidth = 2;
  19270. ctx.moveTo(xLeft, yMiddle);
  19271. ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);
  19272. ctx.stroke();
  19273. }
  19274. };
  19275. var alignmentOffset = function(dimension, blockSize) {
  19276. switch (opts.align) {
  19277. case 'start':
  19278. return labelOpts.padding;
  19279. case 'end':
  19280. return dimension - blockSize;
  19281. default: // center
  19282. return (dimension - blockSize + labelOpts.padding) / 2;
  19283. }
  19284. };
  19285. // Horizontal
  19286. var isHorizontal = me.isHorizontal();
  19287. if (isHorizontal) {
  19288. cursor = {
  19289. x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
  19290. y: me.top + labelOpts.padding,
  19291. line: 0
  19292. };
  19293. } else {
  19294. cursor = {
  19295. x: me.left + labelOpts.padding,
  19296. y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
  19297. line: 0
  19298. };
  19299. }
  19300. helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);
  19301. var itemHeight = fontSize + labelOpts.padding;
  19302. helpers$1.each(me.legendItems, function(legendItem, i) {
  19303. var textWidth = ctx.measureText(legendItem.text).width;
  19304. var width = boxWidth + (fontSize / 2) + textWidth;
  19305. var x = cursor.x;
  19306. var y = cursor.y;
  19307. rtlHelper.setWidth(me.minSize.width);
  19308. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  19309. // instead of me.right and me.bottom because me.width and me.height
  19310. // may have been changed since me.minSize was calculated
  19311. if (isHorizontal) {
  19312. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  19313. y = cursor.y += itemHeight;
  19314. cursor.line++;
  19315. x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
  19316. }
  19317. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  19318. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  19319. cursor.line++;
  19320. y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
  19321. }
  19322. var realX = rtlHelper.x(x);
  19323. drawLegendBox(realX, y, legendItem);
  19324. hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);
  19325. hitboxes[i].top = y;
  19326. // Fill the actual label
  19327. fillText(realX, y, legendItem, textWidth);
  19328. if (isHorizontal) {
  19329. cursor.x += width + labelOpts.padding;
  19330. } else {
  19331. cursor.y += itemHeight;
  19332. }
  19333. });
  19334. helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);
  19335. },
  19336. /**
  19337. * @private
  19338. */
  19339. _getLegendItemAt: function(x, y) {
  19340. var me = this;
  19341. var i, hitBox, lh;
  19342. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  19343. // See if we are touching one of the dataset boxes
  19344. lh = me.legendHitBoxes;
  19345. for (i = 0; i < lh.length; ++i) {
  19346. hitBox = lh[i];
  19347. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  19348. // Touching an element
  19349. return me.legendItems[i];
  19350. }
  19351. }
  19352. }
  19353. return null;
  19354. },
  19355. /**
  19356. * Handle an event
  19357. * @private
  19358. * @param {IEvent} event - The event to handle
  19359. */
  19360. handleEvent: function(e) {
  19361. var me = this;
  19362. var opts = me.options;
  19363. var type = e.type === 'mouseup' ? 'click' : e.type;
  19364. var hoveredItem;
  19365. if (type === 'mousemove') {
  19366. if (!opts.onHover && !opts.onLeave) {
  19367. return;
  19368. }
  19369. } else if (type === 'click') {
  19370. if (!opts.onClick) {
  19371. return;
  19372. }
  19373. } else {
  19374. return;
  19375. }
  19376. // Chart event already has relative position in it
  19377. hoveredItem = me._getLegendItemAt(e.x, e.y);
  19378. if (type === 'click') {
  19379. if (hoveredItem && opts.onClick) {
  19380. // use e.native for backwards compatibility
  19381. opts.onClick.call(me, e.native, hoveredItem);
  19382. }
  19383. } else {
  19384. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  19385. if (me._hoveredItem) {
  19386. opts.onLeave.call(me, e.native, me._hoveredItem);
  19387. }
  19388. me._hoveredItem = hoveredItem;
  19389. }
  19390. if (opts.onHover && hoveredItem) {
  19391. // use e.native for backwards compatibility
  19392. opts.onHover.call(me, e.native, hoveredItem);
  19393. }
  19394. }
  19395. }
  19396. });
  19397. function createNewLegendAndAttach(chart, legendOpts) {
  19398. var legend = new Legend({
  19399. ctx: chart.ctx,
  19400. options: legendOpts,
  19401. chart: chart
  19402. });
  19403. core_layouts.configure(chart, legend, legendOpts);
  19404. core_layouts.addBox(chart, legend);
  19405. chart.legend = legend;
  19406. }
  19407. var plugin_legend = {
  19408. id: 'legend',
  19409. /**
  19410. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  19411. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  19412. * the plugin, which one will be re-exposed in the chart.js file.
  19413. * https://github.com/chartjs/Chart.js/pull/2640
  19414. * @private
  19415. */
  19416. _element: Legend,
  19417. beforeInit: function(chart) {
  19418. var legendOpts = chart.options.legend;
  19419. if (legendOpts) {
  19420. createNewLegendAndAttach(chart, legendOpts);
  19421. }
  19422. },
  19423. beforeUpdate: function(chart) {
  19424. var legendOpts = chart.options.legend;
  19425. var legend = chart.legend;
  19426. if (legendOpts) {
  19427. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  19428. if (legend) {
  19429. core_layouts.configure(chart, legend, legendOpts);
  19430. legend.options = legendOpts;
  19431. } else {
  19432. createNewLegendAndAttach(chart, legendOpts);
  19433. }
  19434. } else if (legend) {
  19435. core_layouts.removeBox(chart, legend);
  19436. delete chart.legend;
  19437. }
  19438. },
  19439. afterEvent: function(chart, e) {
  19440. var legend = chart.legend;
  19441. if (legend) {
  19442. legend.handleEvent(e);
  19443. }
  19444. }
  19445. };
  19446. var noop$2 = helpers$1.noop;
  19447. core_defaults._set('global', {
  19448. title: {
  19449. display: false,
  19450. fontStyle: 'bold',
  19451. fullWidth: true,
  19452. padding: 10,
  19453. position: 'top',
  19454. text: '',
  19455. weight: 2000 // by default greater than legend (1000) to be above
  19456. }
  19457. });
  19458. /**
  19459. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  19460. */
  19461. var Title = core_element.extend({
  19462. initialize: function(config) {
  19463. var me = this;
  19464. helpers$1.extend(me, config);
  19465. // Contains hit boxes for each dataset (in dataset order)
  19466. me.legendHitBoxes = [];
  19467. },
  19468. // These methods are ordered by lifecycle. Utilities then follow.
  19469. beforeUpdate: noop$2,
  19470. update: function(maxWidth, maxHeight, margins) {
  19471. var me = this;
  19472. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  19473. me.beforeUpdate();
  19474. // Absorb the master measurements
  19475. me.maxWidth = maxWidth;
  19476. me.maxHeight = maxHeight;
  19477. me.margins = margins;
  19478. // Dimensions
  19479. me.beforeSetDimensions();
  19480. me.setDimensions();
  19481. me.afterSetDimensions();
  19482. // Labels
  19483. me.beforeBuildLabels();
  19484. me.buildLabels();
  19485. me.afterBuildLabels();
  19486. // Fit
  19487. me.beforeFit();
  19488. me.fit();
  19489. me.afterFit();
  19490. //
  19491. me.afterUpdate();
  19492. return me.minSize;
  19493. },
  19494. afterUpdate: noop$2,
  19495. //
  19496. beforeSetDimensions: noop$2,
  19497. setDimensions: function() {
  19498. var me = this;
  19499. // Set the unconstrained dimension before label rotation
  19500. if (me.isHorizontal()) {
  19501. // Reset position before calculating rotation
  19502. me.width = me.maxWidth;
  19503. me.left = 0;
  19504. me.right = me.width;
  19505. } else {
  19506. me.height = me.maxHeight;
  19507. // Reset position before calculating rotation
  19508. me.top = 0;
  19509. me.bottom = me.height;
  19510. }
  19511. // Reset padding
  19512. me.paddingLeft = 0;
  19513. me.paddingTop = 0;
  19514. me.paddingRight = 0;
  19515. me.paddingBottom = 0;
  19516. // Reset minSize
  19517. me.minSize = {
  19518. width: 0,
  19519. height: 0
  19520. };
  19521. },
  19522. afterSetDimensions: noop$2,
  19523. //
  19524. beforeBuildLabels: noop$2,
  19525. buildLabels: noop$2,
  19526. afterBuildLabels: noop$2,
  19527. //
  19528. beforeFit: noop$2,
  19529. fit: function() {
  19530. var me = this;
  19531. var opts = me.options;
  19532. var minSize = me.minSize = {};
  19533. var isHorizontal = me.isHorizontal();
  19534. var lineCount, textSize;
  19535. if (!opts.display) {
  19536. me.width = minSize.width = me.height = minSize.height = 0;
  19537. return;
  19538. }
  19539. lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  19540. textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;
  19541. me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
  19542. me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
  19543. },
  19544. afterFit: noop$2,
  19545. // Shared Methods
  19546. isHorizontal: function() {
  19547. var pos = this.options.position;
  19548. return pos === 'top' || pos === 'bottom';
  19549. },
  19550. // Actually draw the title block on the canvas
  19551. draw: function() {
  19552. var me = this;
  19553. var ctx = me.ctx;
  19554. var opts = me.options;
  19555. if (!opts.display) {
  19556. return;
  19557. }
  19558. var fontOpts = helpers$1.options._parseFont(opts);
  19559. var lineHeight = fontOpts.lineHeight;
  19560. var offset = lineHeight / 2 + opts.padding;
  19561. var rotation = 0;
  19562. var top = me.top;
  19563. var left = me.left;
  19564. var bottom = me.bottom;
  19565. var right = me.right;
  19566. var maxWidth, titleX, titleY;
  19567. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  19568. ctx.font = fontOpts.string;
  19569. // Horizontal
  19570. if (me.isHorizontal()) {
  19571. titleX = left + ((right - left) / 2); // midpoint of the width
  19572. titleY = top + offset;
  19573. maxWidth = right - left;
  19574. } else {
  19575. titleX = opts.position === 'left' ? left + offset : right - offset;
  19576. titleY = top + ((bottom - top) / 2);
  19577. maxWidth = bottom - top;
  19578. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  19579. }
  19580. ctx.save();
  19581. ctx.translate(titleX, titleY);
  19582. ctx.rotate(rotation);
  19583. ctx.textAlign = 'center';
  19584. ctx.textBaseline = 'middle';
  19585. var text = opts.text;
  19586. if (helpers$1.isArray(text)) {
  19587. var y = 0;
  19588. for (var i = 0; i < text.length; ++i) {
  19589. ctx.fillText(text[i], 0, y, maxWidth);
  19590. y += lineHeight;
  19591. }
  19592. } else {
  19593. ctx.fillText(text, 0, 0, maxWidth);
  19594. }
  19595. ctx.restore();
  19596. }
  19597. });
  19598. function createNewTitleBlockAndAttach(chart, titleOpts) {
  19599. var title = new Title({
  19600. ctx: chart.ctx,
  19601. options: titleOpts,
  19602. chart: chart
  19603. });
  19604. core_layouts.configure(chart, title, titleOpts);
  19605. core_layouts.addBox(chart, title);
  19606. chart.titleBlock = title;
  19607. }
  19608. var plugin_title = {
  19609. id: 'title',
  19610. /**
  19611. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  19612. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  19613. * the plugin, which one will be re-exposed in the chart.js file.
  19614. * https://github.com/chartjs/Chart.js/pull/2640
  19615. * @private
  19616. */
  19617. _element: Title,
  19618. beforeInit: function(chart) {
  19619. var titleOpts = chart.options.title;
  19620. if (titleOpts) {
  19621. createNewTitleBlockAndAttach(chart, titleOpts);
  19622. }
  19623. },
  19624. beforeUpdate: function(chart) {
  19625. var titleOpts = chart.options.title;
  19626. var titleBlock = chart.titleBlock;
  19627. if (titleOpts) {
  19628. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  19629. if (titleBlock) {
  19630. core_layouts.configure(chart, titleBlock, titleOpts);
  19631. titleBlock.options = titleOpts;
  19632. } else {
  19633. createNewTitleBlockAndAttach(chart, titleOpts);
  19634. }
  19635. } else if (titleBlock) {
  19636. core_layouts.removeBox(chart, titleBlock);
  19637. delete chart.titleBlock;
  19638. }
  19639. }
  19640. };
  19641. var plugins = {};
  19642. var filler = plugin_filler;
  19643. var legend = plugin_legend;
  19644. var title = plugin_title;
  19645. plugins.filler = filler;
  19646. plugins.legend = legend;
  19647. plugins.title = title;
  19648. /**
  19649. * @namespace Chart
  19650. */
  19651. core_controller.helpers = helpers$1;
  19652. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  19653. core_helpers();
  19654. core_controller._adapters = core_adapters;
  19655. core_controller.Animation = core_animation;
  19656. core_controller.animationService = core_animations;
  19657. core_controller.controllers = controllers;
  19658. core_controller.DatasetController = core_datasetController;
  19659. core_controller.defaults = core_defaults;
  19660. core_controller.Element = core_element;
  19661. core_controller.elements = elements;
  19662. core_controller.Interaction = core_interaction;
  19663. core_controller.layouts = core_layouts;
  19664. core_controller.platform = platform;
  19665. core_controller.plugins = core_plugins;
  19666. core_controller.Scale = core_scale;
  19667. core_controller.scaleService = core_scaleService;
  19668. core_controller.Ticks = core_ticks;
  19669. core_controller.Tooltip = core_tooltip;
  19670. // Register built-in scales
  19671. core_controller.helpers.each(scales, function(scale, type) {
  19672. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  19673. });
  19674. // Load to register built-in adapters (as side effects)
  19675. // Loading built-in plugins
  19676. for (var k in plugins) {
  19677. if (plugins.hasOwnProperty(k)) {
  19678. core_controller.plugins.register(plugins[k]);
  19679. }
  19680. }
  19681. core_controller.platform.initialize();
  19682. var src = core_controller;
  19683. if (typeof window !== 'undefined') {
  19684. window.Chart = core_controller;
  19685. }
  19686. // DEPRECATIONS
  19687. /**
  19688. * Provided for backward compatibility, not available anymore
  19689. * @namespace Chart.Chart
  19690. * @deprecated since version 2.8.0
  19691. * @todo remove at version 3
  19692. * @private
  19693. */
  19694. core_controller.Chart = core_controller;
  19695. /**
  19696. * Provided for backward compatibility, not available anymore
  19697. * @namespace Chart.Legend
  19698. * @deprecated since version 2.1.5
  19699. * @todo remove at version 3
  19700. * @private
  19701. */
  19702. core_controller.Legend = plugins.legend._element;
  19703. /**
  19704. * Provided for backward compatibility, not available anymore
  19705. * @namespace Chart.Title
  19706. * @deprecated since version 2.1.5
  19707. * @todo remove at version 3
  19708. * @private
  19709. */
  19710. core_controller.Title = plugins.title._element;
  19711. /**
  19712. * Provided for backward compatibility, use Chart.plugins instead
  19713. * @namespace Chart.pluginService
  19714. * @deprecated since version 2.1.5
  19715. * @todo remove at version 3
  19716. * @private
  19717. */
  19718. core_controller.pluginService = core_controller.plugins;
  19719. /**
  19720. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  19721. * effect, instead simply create/register plugins via plain JavaScript objects.
  19722. * @interface Chart.PluginBase
  19723. * @deprecated since version 2.5.0
  19724. * @todo remove at version 3
  19725. * @private
  19726. */
  19727. core_controller.PluginBase = core_controller.Element.extend({});
  19728. /**
  19729. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  19730. * @namespace Chart.canvasHelpers
  19731. * @deprecated since version 2.6.0
  19732. * @todo remove at version 3
  19733. * @private
  19734. */
  19735. core_controller.canvasHelpers = core_controller.helpers.canvas;
  19736. /**
  19737. * Provided for backward compatibility, use Chart.layouts instead.
  19738. * @namespace Chart.layoutService
  19739. * @deprecated since version 2.7.3
  19740. * @todo remove at version 3
  19741. * @private
  19742. */
  19743. core_controller.layoutService = core_controller.layouts;
  19744. /**
  19745. * Provided for backward compatibility, not available anymore.
  19746. * @namespace Chart.LinearScaleBase
  19747. * @deprecated since version 2.8
  19748. * @todo remove at version 3
  19749. * @private
  19750. */
  19751. core_controller.LinearScaleBase = scale_linearbase;
  19752. /**
  19753. * Provided for backward compatibility, instead we should create a new Chart
  19754. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  19755. * @deprecated since version 2.8.0
  19756. * @todo remove at version 3
  19757. */
  19758. core_controller.helpers.each(
  19759. [
  19760. 'Bar',
  19761. 'Bubble',
  19762. 'Doughnut',
  19763. 'Line',
  19764. 'PolarArea',
  19765. 'Radar',
  19766. 'Scatter'
  19767. ],
  19768. function(klass) {
  19769. core_controller[klass] = function(ctx, cfg) {
  19770. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  19771. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  19772. }));
  19773. };
  19774. }
  19775. );
  19776. return src;
  19777. })));
  19778. } (Chart$1));
  19779. var ChartExports = Chart$1.exports;
  19780. var Chart = /*@__PURE__*/getDefaultExportFromCjs(ChartExports);
  19781. // Modify horizontalBar so that each dataset (fragments, timeRanges) draws on the same row (level, track or buffer)
  19782. Chart.controllers.horizontalBar.prototype.calculateBarValuePixels = function (datasetIndex, index, options) {
  19783. var chart = this.chart;
  19784. var scale = this._getValueScale();
  19785. var datasets = chart.data.datasets;
  19786. if (!datasets) {
  19787. throw new Error("Chart datasets are " + datasets);
  19788. }
  19789. scale._parseValue = scaleParseValue;
  19790. var obj = datasets[datasetIndex].data[index];
  19791. var value = scale._parseValue(obj);
  19792. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  19793. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  19794. var base = scale.getPixelForValue(start);
  19795. var head = scale.getPixelForValue(start + length);
  19796. var size = head - base;
  19797. return {
  19798. size: size,
  19799. base: base,
  19800. head: head,
  19801. center: head + size / 2
  19802. };
  19803. };
  19804. Chart.controllers.horizontalBar.prototype.calculateBarIndexPixels = function (datasetIndex, index, ruler, options) {
  19805. var rowHeight = options.barThickness;
  19806. var size = rowHeight * options.categoryPercentage;
  19807. var center = ruler.start + (datasetIndex * rowHeight + rowHeight / 2);
  19808. return {
  19809. base: center - size / 2,
  19810. head: center + size / 2,
  19811. center: center,
  19812. size: size
  19813. };
  19814. };
  19815. Chart.controllers.horizontalBar.prototype.draw = function () {
  19816. var rects = this.getMeta().data;
  19817. var len = rects.length;
  19818. var dataset = this.getDataset();
  19819. if (len !== dataset.data.length) {
  19820. // View does not match dataset (wait for redraw)
  19821. return;
  19822. }
  19823. var chart = this.chart;
  19824. var scale = this._getValueScale();
  19825. scale._parseValue = scaleParseValue;
  19826. var ctx = chart.ctx;
  19827. var chartArea = chart.chartArea;
  19828. Chart.helpers.canvas.clipArea(ctx, chartArea);
  19829. if (!this.lineHeight) {
  19830. this.lineHeight = Math.ceil(ctx.measureText('0').actualBoundingBoxAscent) + 2;
  19831. }
  19832. var lineHeight = this.lineHeight;
  19833. var range = 0;
  19834. for (var i = 0; i < len; ++i) {
  19835. var rect = rects[i];
  19836. var view = rect._view;
  19837. if (!intersects(view.base, view.x, chartArea.left, chartArea.right)) {
  19838. // Do not draw elements outside of the chart's viewport
  19839. continue;
  19840. }
  19841. var obj = dataset.data[i];
  19842. var val = scale._parseValue(obj);
  19843. if (!isNaN(val.min) && !isNaN(val.max)) {
  19844. var dataType = obj.dataType;
  19845. var stats = obj.stats;
  19846. var isPart = dataType === 'part';
  19847. var isFragmentHint = dataType === 'fragmentHint';
  19848. var isFragment = dataType === 'fragment' || isPart || isFragmentHint;
  19849. var isCue = dataType === 'cue';
  19850. if (isCue) {
  19851. view.y += view.height * 0.5 * (i % 2) - view.height * 0.25;
  19852. } else if (isPart) {
  19853. view.height -= 22;
  19854. }
  19855. var bounds = boundingRects(view);
  19856. var drawText = bounds.w > lineHeight * 1.5 && !isFragmentHint;
  19857. if (isFragment || isCue) {
  19858. if (drawText) {
  19859. view.borderWidth = 1;
  19860. if (i === 0) {
  19861. view.borderSkipped = false;
  19862. }
  19863. } else {
  19864. range = range || scale.getValueForPixel(chartArea.right) - scale.getValueForPixel(chartArea.left);
  19865. if (range > 300 || isCue) {
  19866. view.borderWidth = 0;
  19867. }
  19868. }
  19869. if (isFragmentHint) {
  19870. view.borderWidth = 0;
  19871. view.backgroundColor = 'rgba(0, 0, 0, 0.1)';
  19872. } else {
  19873. view.backgroundColor = "rgba(0, 0, 0, " + (0.05 + i % 2 / 12) + ")";
  19874. }
  19875. }
  19876. rect.draw();
  19877. if (isFragment) {
  19878. if (!stats) {
  19879. stats = {};
  19880. }
  19881. if (isPart) {
  19882. ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
  19883. ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
  19884. }
  19885. if (stats.aborted) {
  19886. ctx.fillStyle = 'rgba(100, 0, 0, 0.3)';
  19887. ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
  19888. }
  19889. if (stats.loaded && stats.total) {
  19890. ctx.fillStyle = 'rgba(50, 20, 100, 0.3)';
  19891. ctx.fillRect(bounds.x, bounds.y, bounds.w * stats.loaded / stats.total, bounds.h);
  19892. }
  19893. } else if (isCue) {
  19894. if (obj.active) {
  19895. ctx.fillStyle = 'rgba(100, 100, 10, 0.4)';
  19896. ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
  19897. }
  19898. }
  19899. if (drawText) {
  19900. var start = val.start; // obj.start;
  19901. ctx.fillStyle = 'rgb(0, 0, 0)';
  19902. if (stats) {
  19903. var snBounds = _extends({}, bounds);
  19904. if (obj.cc) {
  19905. var ccLabel = "cc:" + obj.cc;
  19906. var ccWidth = Math.min(ctx.measureText(ccLabel).width + 2, snBounds.w / 2 - 2);
  19907. if (ccWidth) {
  19908. ctx.fillText(ccLabel, snBounds.x + 2, snBounds.y + lineHeight, snBounds.w / 2 - 4);
  19909. snBounds.x += ccWidth;
  19910. snBounds.w -= ccWidth;
  19911. }
  19912. }
  19913. var snLabel = isPart ? "part: " + obj.index : "sn: " + obj.sn;
  19914. var textWidth = Math.min(ctx.measureText(snLabel).width + 2, snBounds.w - 2);
  19915. ctx.fillText(snLabel, snBounds.x + snBounds.w - textWidth, snBounds.y + lineHeight, snBounds.w - 4);
  19916. }
  19917. if (isCue) {
  19918. var strLength = Math.min(30, Math.ceil(bounds.w / (lineHeight / 3)));
  19919. ctx.fillText(('' + obj.content).slice(0, strLength), bounds.x + 2, bounds.y + bounds.h - 3, bounds.w - 5);
  19920. } else if (!isPart) {
  19921. var _float = start !== (start | 0);
  19922. var fixedDigits = _float ? Math.min(5, Math.max(1, Math.floor(bounds.w / 10 - 1))) : 0;
  19923. var startString = hhmmss(start, fixedDigits);
  19924. ctx.fillText(startString, bounds.x + 2, bounds.y + bounds.h - 3, bounds.w - 5);
  19925. }
  19926. }
  19927. }
  19928. }
  19929. Chart.helpers.canvas.unclipArea(chart.ctx);
  19930. };
  19931. function applyChartInstanceOverrides(chart) {
  19932. Object.keys(chart.scales).forEach(function (axis) {
  19933. var scale = chart.scales[axis];
  19934. scale._parseValue = scaleParseValue;
  19935. });
  19936. }
  19937. function scaleParseValue(value) {
  19938. if (value === undefined) {
  19939. console.warn('Chart values undefined (update chart)');
  19940. return {};
  19941. }
  19942. var start;
  19943. var end;
  19944. var min;
  19945. var max;
  19946. if (Array.isArray(value)) {
  19947. start = +this.getRightValue(value[0]);
  19948. end = +this.getRightValue(value[1]);
  19949. min = Math.min(start, end);
  19950. max = Math.max(start, end);
  19951. } else {
  19952. start = +this.getRightValue(value.start);
  19953. if ('end' in value) {
  19954. end = +this.getRightValue(value.end);
  19955. } else {
  19956. end = +this.getRightValue(value.start + value.duration);
  19957. }
  19958. min = Math.min(start, end);
  19959. max = Math.max(start, end);
  19960. }
  19961. return {
  19962. min: min,
  19963. max: max,
  19964. start: start,
  19965. end: end
  19966. };
  19967. }
  19968. function intersects(x1, x2, x3, x4) {
  19969. return x2 > x3 && x1 < x4;
  19970. }
  19971. function boundingRects(vm) {
  19972. var half = vm.height / 2;
  19973. var left = Math.min(vm.x, vm.base);
  19974. var right = Math.max(vm.x, vm.base);
  19975. var top = vm.y - half;
  19976. var bottom = vm.y + half;
  19977. return {
  19978. x: left,
  19979. y: top,
  19980. w: right - left,
  19981. h: bottom - top
  19982. };
  19983. }
  19984. function hhmmss(value, fixedDigits) {
  19985. var h = value / 3600 | 0;
  19986. var m = (value / 60 | 0) % 60;
  19987. var s = value % 60;
  19988. return (h + ":" + pad(m, 2) + ":" + pad(s.toFixed(fixedDigits), fixedDigits ? fixedDigits + 3 : 2)).replace(/^(?:0+:?)*(\d.*?)(?:\.0*)?$/, '$1');
  19989. }
  19990. function pad(str, length) {
  19991. str = '' + str;
  19992. while (str.length < length) {
  19993. str = '0' + str;
  19994. }
  19995. return str;
  19996. }
  19997. var X_AXIS_SECONDS = 'x-axis-seconds';
  19998. var TimelineChart = /*#__PURE__*/function () {
  19999. function TimelineChart(canvas, chartJsOptions) {
  20000. var _this = this;
  20001. this.chart = void 0;
  20002. this.rafDebounceRequestId = -1;
  20003. this.imageDataBuffer = null;
  20004. this.media = null;
  20005. this.tracksChangeHandler = void 0;
  20006. this.cuesChangeHandler = void 0;
  20007. this.hidden = true;
  20008. this.zoom100 = 60;
  20009. var ctx = canvas.getContext('2d');
  20010. if (!ctx) {
  20011. throw new Error("Could not get CanvasRenderingContext2D from canvas: " + canvas);
  20012. }
  20013. var chart = this.chart = self.chart = new Chart(ctx, {
  20014. type: 'horizontalBar',
  20015. data: {
  20016. labels: [],
  20017. datasets: []
  20018. },
  20019. options: _extends(getChartOptions(), chartJsOptions),
  20020. plugins: [{
  20021. afterRender: function afterRender(chart) {
  20022. _this.imageDataBuffer = null;
  20023. _this.drawCurrentTime();
  20024. }
  20025. }]
  20026. });
  20027. applyChartInstanceOverrides(chart);
  20028. canvas.ondblclick = function (event) {
  20029. var chart = _this.chart;
  20030. var chartArea = chart.chartArea;
  20031. var element = chart.getElementAtEvent(event);
  20032. var pos = Chart.helpers.getRelativePosition(event, chart);
  20033. var scale = _this.chartScales[X_AXIS_SECONDS];
  20034. // zoom in when double clicking near elements in chart area
  20035. if (element.length || pos.x > chartArea.left) {
  20036. var amount = event.getModifierState('Shift') ? -1.0 : 0.5;
  20037. _this.zoom(scale, pos, amount);
  20038. } else {
  20039. scale.options.ticks.min = 0;
  20040. scale.options.ticks.max = _this.zoom100;
  20041. }
  20042. _this.update();
  20043. };
  20044. canvas.onwheel = function (event) {
  20045. if (event.deltaMode) {
  20046. // exit if wheel is in page or line scrolling mode
  20047. return;
  20048. }
  20049. var chart = _this.chart;
  20050. var chartArea = chart.chartArea;
  20051. var pos = Chart.helpers.getRelativePosition(event, chart);
  20052. // zoom when scrolling over chart elements
  20053. if (pos.x > chartArea.left - 11) {
  20054. var scale = _this.chartScales[X_AXIS_SECONDS];
  20055. if (event.deltaY) {
  20056. var direction = -event.deltaY / Math.abs(event.deltaY);
  20057. var normal = Math.min(333, Math.abs(event.deltaY)) / 1000;
  20058. var ease = 1 - (1 - normal) * (1 - normal);
  20059. _this.zoom(scale, pos, ease * direction);
  20060. } else if (event.deltaX) {
  20061. _this.pan(scale, event.deltaX / 10, scale.min, scale.max);
  20062. }
  20063. event.preventDefault();
  20064. }
  20065. };
  20066. var moved = false;
  20067. var gestureScale = 1;
  20068. canvas.onpointerdown = function (downEvent) {
  20069. if (!downEvent.isPrimary || gestureScale !== 1) {
  20070. return;
  20071. }
  20072. var chart = _this.chart;
  20073. var chartArea = chart.chartArea;
  20074. var pos = Chart.helpers.getRelativePosition(downEvent, chart);
  20075. // pan when dragging over chart elements
  20076. if (pos.x > chartArea.left) {
  20077. var scale = _this.chartScales[X_AXIS_SECONDS];
  20078. var startX = downEvent.clientX;
  20079. var min = scale.min,
  20080. max = scale.max;
  20081. var xToVal = (max - min) / scale.width;
  20082. moved = false;
  20083. canvas.setPointerCapture(downEvent.pointerId);
  20084. canvas.onpointermove = function (moveEvent) {
  20085. if (!downEvent.isPrimary || gestureScale !== 1) {
  20086. return;
  20087. }
  20088. var movedX = startX - moveEvent.clientX;
  20089. var movedValue = movedX * xToVal;
  20090. moved = moved || Math.abs(movedX) > 8;
  20091. _this.pan(scale, movedValue, min, max);
  20092. };
  20093. }
  20094. };
  20095. canvas.onpointerup = canvas.onpointercancel = function (upEvent) {
  20096. if (canvas.onpointermove) {
  20097. canvas.onpointermove = null;
  20098. canvas.releasePointerCapture(upEvent.pointerId);
  20099. }
  20100. if (!moved && upEvent.isPrimary) {
  20101. _this.click(upEvent);
  20102. }
  20103. };
  20104. // Gesture events are for iOS and easier to implement than pinch-zoom with multiple pointers for all browsers
  20105. // @ts-ignore
  20106. canvas.ongesturestart = function (event) {
  20107. gestureScale = 1;
  20108. event.preventDefault();
  20109. };
  20110. // @ts-ignore
  20111. canvas.ongestureend = function (event) {
  20112. gestureScale = 1;
  20113. };
  20114. // @ts-ignore
  20115. canvas.ongesturechange = function (event) {
  20116. var chart = _this.chart;
  20117. var chartArea = chart.chartArea;
  20118. var pos = Chart.helpers.getRelativePosition(event, chart);
  20119. // zoom when scrolling over chart elements
  20120. if (pos.x > chartArea.left) {
  20121. var scale = _this.chartScales[X_AXIS_SECONDS];
  20122. var amount = event.scale - gestureScale;
  20123. _this.zoom(scale, pos, amount);
  20124. gestureScale = event.scale;
  20125. }
  20126. };
  20127. }
  20128. var _proto = TimelineChart.prototype;
  20129. _proto.click = function click(event) {
  20130. // Log object on click and seek to position
  20131. var chart = this.chart;
  20132. var element = chart.getElementAtEvent(event);
  20133. if (element.length && chart.data.datasets) {
  20134. var _self$hls;
  20135. var dataset = chart.data.datasets[element[0]._datasetIndex];
  20136. var obj = dataset.data[element[0]._index];
  20137. // eslint-disable-next-line no-console
  20138. console.log(obj);
  20139. if ((_self$hls = self.hls) != null && _self$hls.media) {
  20140. var scale = this.chartScales[X_AXIS_SECONDS];
  20141. var pos = Chart.helpers.getRelativePosition(event, chart);
  20142. self.hls.media.currentTime = scale.getValueForPixel(pos.x);
  20143. }
  20144. }
  20145. };
  20146. _proto.pan = function pan(scale, amount, min, max) {
  20147. if (amount === 0) {
  20148. return;
  20149. }
  20150. var pan = amount;
  20151. if (amount > 0) {
  20152. pan = Math.min(this.zoom100 + 10 - max, amount);
  20153. } else {
  20154. pan = Math.max(-10 - min, amount);
  20155. }
  20156. scale.options.ticks.min = min + pan;
  20157. scale.options.ticks.max = max + pan;
  20158. this.updateOnRepaint();
  20159. };
  20160. _proto.zoom = function zoom(scale, pos, amount) {
  20161. var range = scale.max - scale.min;
  20162. var diff = range * amount;
  20163. var minPercent = (scale.getValueForPixel(pos.x) - scale.min) / range;
  20164. var maxPercent = 1 - minPercent;
  20165. var minDelta = diff * minPercent;
  20166. var maxDelta = diff * maxPercent;
  20167. scale.options.ticks.min = Math.max(-10, scale.min + minDelta);
  20168. scale.options.ticks.max = Math.min(this.zoom100 + 10, scale.max - maxDelta);
  20169. this.updateOnRepaint();
  20170. };
  20171. _proto.reset = function reset() {
  20172. var scale = this.chartScales[X_AXIS_SECONDS];
  20173. scale.options.ticks.min = 0;
  20174. scale.options.ticks.max = 60;
  20175. var _this$chart$data = this.chart.data,
  20176. labels = _this$chart$data.labels,
  20177. datasets = _this$chart$data.datasets;
  20178. if (labels && datasets) {
  20179. labels.length = 0;
  20180. datasets.length = 0;
  20181. this.resize(datasets);
  20182. }
  20183. };
  20184. _proto.update = function update() {
  20185. var _this$chart$ctx;
  20186. if (this.hidden || !((_this$chart$ctx = this.chart.ctx) != null && _this$chart$ctx.canvas.width)) {
  20187. return;
  20188. }
  20189. self.cancelAnimationFrame(this.rafDebounceRequestId);
  20190. this.chart.update({
  20191. duration: 0,
  20192. lazy: true
  20193. });
  20194. };
  20195. _proto.updateOnRepaint = function updateOnRepaint() {
  20196. var _this2 = this;
  20197. if (this.hidden) {
  20198. return;
  20199. }
  20200. self.cancelAnimationFrame(this.rafDebounceRequestId);
  20201. this.rafDebounceRequestId = self.requestAnimationFrame(function () {
  20202. return _this2.update();
  20203. });
  20204. };
  20205. _proto.resize = function resize(datasets) {
  20206. var _this3 = this;
  20207. if (this.hidden) {
  20208. return;
  20209. }
  20210. if (datasets != null && datasets.length) {
  20211. var _this$chart$canvas;
  20212. var scale = this.chartScales[X_AXIS_SECONDS];
  20213. var top = this.chart.chartArea.top;
  20214. var height = top + datasets.reduce(function (val, dataset) {
  20215. return val + dataset.barThickness;
  20216. }, 0) + scale.height + 5;
  20217. var container = (_this$chart$canvas = this.chart.canvas) == null ? void 0 : _this$chart$canvas.parentElement;
  20218. if (container) {
  20219. container.style.height = height + "px";
  20220. }
  20221. }
  20222. self.cancelAnimationFrame(this.rafDebounceRequestId);
  20223. this.rafDebounceRequestId = self.requestAnimationFrame(function () {
  20224. _this3.chart.resize();
  20225. });
  20226. };
  20227. _proto.show = function show() {
  20228. this.hidden = false;
  20229. };
  20230. _proto.hide = function hide() {
  20231. this.hidden = true;
  20232. };
  20233. _proto.updateLevels = function updateLevels(levels, levelSwitched) {
  20234. var _this4 = this;
  20235. var _this$chart$data2 = this.chart.data,
  20236. labels = _this$chart$data2.labels,
  20237. datasets = _this$chart$data2.datasets;
  20238. if (!labels || !datasets) {
  20239. return;
  20240. }
  20241. var _self$hls2 = self.hls,
  20242. loadLevel = _self$hls2.loadLevel,
  20243. nextLoadLevel = _self$hls2.nextLoadLevel,
  20244. nextAutoLevel = _self$hls2.nextAutoLevel;
  20245. // eslint-disable-next-line no-undefined
  20246. var currentLevel = levelSwitched !== undefined ? levelSwitched : self.hls.currentLevel;
  20247. levels.forEach(function (level, i) {
  20248. var index = level.id || i;
  20249. labels.push(getLevelName(level, index));
  20250. var borderColor = null;
  20251. if (currentLevel === i) {
  20252. borderColor = 'rgba(32, 32, 240, 1.0)';
  20253. } else if (loadLevel === i) {
  20254. borderColor = 'rgba(255, 128, 0, 1.0)';
  20255. } else if (nextLoadLevel === i) {
  20256. borderColor = 'rgba(200, 200, 64, 1.0)';
  20257. } else if (nextAutoLevel === i) {
  20258. borderColor = 'rgba(160, 0, 160, 1.0)';
  20259. }
  20260. datasets.push(datasetWithDefaults({
  20261. url: Array.isArray(level.url) ? level.url[level.urlId || 0] : level.url,
  20262. trackType: 'level',
  20263. borderColor: borderColor,
  20264. level: index
  20265. }));
  20266. if (level.details) {
  20267. _this4.updateLevelOrTrack(level.details);
  20268. }
  20269. });
  20270. this.resize(datasets);
  20271. };
  20272. _proto.updateAudioTracks = function updateAudioTracks(audioTracks) {
  20273. var _this5 = this;
  20274. var _this$chart$data3 = this.chart.data,
  20275. labels = _this$chart$data3.labels,
  20276. datasets = _this$chart$data3.datasets;
  20277. if (!labels || !datasets) {
  20278. return;
  20279. }
  20280. var audioTrack = self.hls.audioTrack;
  20281. audioTracks.forEach(function (track, i) {
  20282. labels.push(getAudioTrackName(track, i));
  20283. datasets.push(datasetWithDefaults({
  20284. url: track.url,
  20285. trackType: 'audioTrack',
  20286. borderColor: audioTrack === i ? 'rgba(32, 32, 240, 1.0)' : null,
  20287. audioTrack: i
  20288. }));
  20289. if (track.details) {
  20290. _this5.updateLevelOrTrack(track.details);
  20291. }
  20292. });
  20293. this.resize(datasets);
  20294. };
  20295. _proto.updateSubtitleTracks = function updateSubtitleTracks(subtitles) {
  20296. var _this6 = this;
  20297. var _this$chart$data4 = this.chart.data,
  20298. labels = _this$chart$data4.labels,
  20299. datasets = _this$chart$data4.datasets;
  20300. if (!labels || !datasets) {
  20301. return;
  20302. }
  20303. var subtitleTrack = self.hls.subtitleTrack;
  20304. subtitles.forEach(function (track, i) {
  20305. labels.push(getSubtitlesName(track, i));
  20306. datasets.push(datasetWithDefaults({
  20307. url: track.url,
  20308. trackType: 'subtitleTrack',
  20309. borderColor: subtitleTrack === i ? 'rgba(32, 32, 240, 1.0)' : null,
  20310. subtitleTrack: i
  20311. }));
  20312. if (track.details) {
  20313. _this6.updateLevelOrTrack(track.details);
  20314. }
  20315. });
  20316. this.resize(datasets);
  20317. };
  20318. _proto.removeType = function removeType(trackType) {
  20319. var _this$chart$data5 = this.chart.data,
  20320. labels = _this$chart$data5.labels,
  20321. datasets = _this$chart$data5.datasets;
  20322. if (!labels || !datasets) {
  20323. return;
  20324. }
  20325. var i = datasets.length;
  20326. while (i--) {
  20327. if (datasets[i].trackType === trackType) {
  20328. datasets.splice(i, 1);
  20329. labels.splice(i, 1);
  20330. }
  20331. }
  20332. };
  20333. _proto.updateLevelOrTrack = function updateLevelOrTrack(details) {
  20334. var targetduration = details.targetduration,
  20335. totalduration = details.totalduration,
  20336. url = details.url;
  20337. var datasets = this.chart.data.datasets;
  20338. var levelDataSet = arrayFind(datasets, function (dataset) {
  20339. return stripDeliveryDirectives(url) === stripDeliveryDirectives(dataset.url || '');
  20340. });
  20341. if (!levelDataSet) {
  20342. levelDataSet = arrayFind(datasets, function (dataset) {
  20343. var _details$fragments$;
  20344. return ((_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.level) === dataset.level;
  20345. });
  20346. }
  20347. if (!levelDataSet) {
  20348. return;
  20349. }
  20350. var data = levelDataSet.data;
  20351. data.length = 0;
  20352. if (details.fragments) {
  20353. details.fragments.forEach(function (fragment) {
  20354. // TODO: keep track of initial playlist start and duration so that we can show drift and pts offset
  20355. // (Make that a feature of hls.js v1.0.0 fragments)
  20356. var chartFragment = _extends({
  20357. dataType: 'fragment'
  20358. }, fragment,
  20359. // Remove loader references for GC
  20360. {
  20361. loader: null
  20362. });
  20363. data.push(chartFragment);
  20364. });
  20365. }
  20366. if (details.partList) {
  20367. details.partList.forEach(function (part) {
  20368. var chartPart = _extends({
  20369. dataType: 'part',
  20370. start: part.fragment.start + part.fragOffset
  20371. }, part, {
  20372. fragment: _extends({}, part.fragment, {
  20373. loader: null
  20374. })
  20375. });
  20376. data.push(chartPart);
  20377. });
  20378. if (details.fragmentHint) {
  20379. var chartFragment = _extends({
  20380. dataType: 'fragmentHint'
  20381. }, details.fragmentHint,
  20382. // Remove loader references for GC
  20383. {
  20384. loader: null
  20385. });
  20386. data.push(chartFragment);
  20387. }
  20388. }
  20389. var start = getPlaylistStart(details);
  20390. this.maxZoom = this.zoom100 = Math.max(start + totalduration + targetduration * 3, this.zoom100);
  20391. this.updateOnRepaint();
  20392. }
  20393. // @ts-ignore
  20394. ;
  20395. _proto.updateFragment = function updateFragment(data) {
  20396. var datasets = this.chart.data.datasets;
  20397. var frag = data.frag;
  20398. var levelDataSet = arrayFind(datasets, function (dataset) {
  20399. return frag.baseurl === dataset.url;
  20400. });
  20401. if (!levelDataSet) {
  20402. levelDataSet = arrayFind(datasets, function (dataset) {
  20403. return frag.level === dataset.level;
  20404. });
  20405. }
  20406. if (!levelDataSet) {
  20407. return;
  20408. }
  20409. // eslint-disable-next-line no-restricted-properties
  20410. var fragData = arrayFind(levelDataSet.data, function (fragData) {
  20411. return fragData.relurl === frag.relurl && fragData.sn === frag.sn;
  20412. });
  20413. if (fragData && fragData !== frag) {
  20414. _extends(fragData, frag);
  20415. }
  20416. this.updateOnRepaint();
  20417. };
  20418. _proto.updateSourceBuffers = function updateSourceBuffers(tracks, media) {
  20419. var _this7 = this;
  20420. var _this$chart$data6 = this.chart.data,
  20421. labels = _this$chart$data6.labels,
  20422. datasets = _this$chart$data6.datasets;
  20423. if (!labels || !datasets) {
  20424. return;
  20425. }
  20426. var trackTypes = Object.keys(tracks).sort(function (type) {
  20427. return type === 'video' ? 1 : -1;
  20428. });
  20429. var mediaBufferData = [];
  20430. this.removeSourceBuffers();
  20431. this.media = media;
  20432. trackTypes.forEach(function (type) {
  20433. var track = tracks[type];
  20434. var data = [];
  20435. var sourceBuffer = track.buffer;
  20436. var backgroundColor = {
  20437. video: 'rgba(0, 0, 255, 0.2)',
  20438. audio: 'rgba(128, 128, 0, 0.2)',
  20439. audiovideo: 'rgba(128, 128, 255, 0.2)'
  20440. }[type];
  20441. labels.unshift(type + " buffer (" + track.id + ")");
  20442. datasets.unshift(datasetWithDefaults({
  20443. data: data,
  20444. categoryPercentage: 0.5,
  20445. backgroundColor: backgroundColor,
  20446. sourceBuffer: sourceBuffer
  20447. }));
  20448. sourceBuffer.addEventListener('update', function () {
  20449. try {
  20450. replaceTimeRangeTuples(sourceBuffer.buffered, data);
  20451. } catch (error) {
  20452. // eslint-disable-next-line no-console
  20453. console.warn(error);
  20454. return;
  20455. }
  20456. replaceTimeRangeTuples(media.buffered, mediaBufferData);
  20457. _this7.update();
  20458. });
  20459. });
  20460. if (trackTypes.length === 0) {
  20461. media.onprogress = function () {
  20462. replaceTimeRangeTuples(media.buffered, mediaBufferData);
  20463. _this7.update();
  20464. };
  20465. }
  20466. labels.unshift('media buffer');
  20467. datasets.unshift(datasetWithDefaults({
  20468. data: mediaBufferData,
  20469. categoryPercentage: 0.5,
  20470. backgroundColor: 'rgba(0, 255, 0, 0.2)',
  20471. media: media
  20472. }));
  20473. media.ontimeupdate = function () {
  20474. return _this7.drawCurrentTime();
  20475. };
  20476. // TextTrackList
  20477. var textTracks = media.textTracks;
  20478. this.tracksChangeHandler = this.tracksChangeHandler || function (e) {
  20479. return _this7.setTextTracks(e.currentTarget);
  20480. };
  20481. textTracks.removeEventListener('addtrack', this.tracksChangeHandler);
  20482. textTracks.removeEventListener('removetrack', this.tracksChangeHandler);
  20483. textTracks.removeEventListener('change', this.tracksChangeHandler);
  20484. textTracks.addEventListener('addtrack', this.tracksChangeHandler);
  20485. textTracks.addEventListener('removetrack', this.tracksChangeHandler);
  20486. textTracks.addEventListener('change', this.tracksChangeHandler);
  20487. this.setTextTracks(textTracks);
  20488. this.resize(datasets);
  20489. };
  20490. _proto.removeSourceBuffers = function removeSourceBuffers() {
  20491. var _this$chart$data7 = this.chart.data,
  20492. labels = _this$chart$data7.labels,
  20493. datasets = _this$chart$data7.datasets;
  20494. if (!labels || !datasets) {
  20495. return;
  20496. }
  20497. var i = datasets.length;
  20498. while (i--) {
  20499. if ((labels[0] || '').toString().indexOf('buffer') > -1) {
  20500. datasets.splice(i, 1);
  20501. labels.splice(i, 1);
  20502. }
  20503. }
  20504. };
  20505. _proto.setTextTracks = function setTextTracks(textTracks) {
  20506. var _this8 = this;
  20507. var _this$chart$data8 = this.chart.data,
  20508. labels = _this$chart$data8.labels,
  20509. datasets = _this$chart$data8.datasets;
  20510. if (!labels || !datasets) {
  20511. return;
  20512. }
  20513. this.removeType('textTrack');
  20514. [].forEach.call(textTracks, function (textTrack, i) {
  20515. // Uncomment to disable rending of subtitle/caption cues in the timeline
  20516. // if (textTrack.kind === 'subtitles' || textTrack.kind === 'captions') {
  20517. // return;
  20518. // }
  20519. var data = [];
  20520. labels.push((textTrack.name || textTrack.label) + " " + textTrack.kind + " (" + textTrack.mode + ")");
  20521. datasets.push(datasetWithDefaults({
  20522. data: data,
  20523. categoryPercentage: 0.5,
  20524. url: '',
  20525. trackType: 'textTrack',
  20526. borderColor: textTrack.mode !== 'hidden' === i ? 'rgba(32, 32, 240, 1.0)' : null,
  20527. textTrack: i
  20528. }));
  20529. _this8.cuesChangeHandler = _this8.cuesChangeHandler || function (e) {
  20530. return _this8.updateTextTrackCues(e.currentTarget);
  20531. };
  20532. textTrack._data = data;
  20533. textTrack.removeEventListener('cuechange', _this8.cuesChangeHandler);
  20534. textTrack.addEventListener('cuechange', _this8.cuesChangeHandler);
  20535. _this8.updateTextTrackCues(textTrack);
  20536. });
  20537. this.resize(datasets);
  20538. };
  20539. _proto.updateTextTrackCues = function updateTextTrackCues(textTrack) {
  20540. var data = textTrack._data;
  20541. if (!data) {
  20542. return;
  20543. }
  20544. var activeCues = textTrack.activeCues,
  20545. cues = textTrack.cues;
  20546. data.length = 0;
  20547. if (!cues) {
  20548. return;
  20549. }
  20550. var length = cues.length;
  20551. var activeLength = 0;
  20552. var activeMin = Infinity;
  20553. var activeMax = 0;
  20554. if (activeCues) {
  20555. activeLength = activeCues.length;
  20556. for (var i = 0; i < activeLength; i++) {
  20557. var cue = activeCues[i];
  20558. if (!cue && activeCues.item) {
  20559. cue = activeCues.item(i);
  20560. }
  20561. if (cue) {
  20562. activeMin = Math.min(activeMin, cue.startTime);
  20563. activeMax = cue.endTime ? Math.max(activeMax, cue.endTime) : activeMax;
  20564. } else {
  20565. activeLength--;
  20566. }
  20567. }
  20568. }
  20569. var _loop = function _loop() {
  20570. var cue = cues[_i];
  20571. if (!cue && cues.item) {
  20572. cue = cues.item(_i);
  20573. }
  20574. if (!cue) {
  20575. return 1; // continue
  20576. }
  20577. var start = cue.startTime;
  20578. var end = cue.endTime;
  20579. var content = getCueLabel(cue);
  20580. var active = false;
  20581. if (activeLength && end >= activeMin && start <= activeMax) {
  20582. active = [].some.call(activeCues, function (activeCue) {
  20583. return cuesMatch(activeCue, cue);
  20584. });
  20585. }
  20586. data.push({
  20587. start: start,
  20588. end: end,
  20589. content: content,
  20590. active: active,
  20591. dataType: 'cue'
  20592. });
  20593. };
  20594. for (var _i = 0; _i < length; _i++) {
  20595. if (_loop()) continue;
  20596. }
  20597. this.updateOnRepaint();
  20598. };
  20599. _proto.drawCurrentTime = function drawCurrentTime() {
  20600. var _self$hls3;
  20601. var chart = this.chart;
  20602. if ((_self$hls3 = self.hls) != null && _self$hls3.media && chart.data.datasets.length) {
  20603. var currentTime = self.hls.media.currentTime;
  20604. var scale = this.chartScales[X_AXIS_SECONDS];
  20605. var ctx = chart.ctx;
  20606. if (this.hidden || !ctx || !ctx.canvas.width) {
  20607. return;
  20608. }
  20609. var chartArea = chart.chartArea;
  20610. var x = scale.getPixelForValue(currentTime);
  20611. ctx.restore();
  20612. ctx.save();
  20613. this.drawLineX(ctx, x, chartArea);
  20614. if (x > chartArea.left && x < chartArea.right) {
  20615. ctx.fillStyle = this.getCurrentTimeColor(self.hls.media);
  20616. var y = chartArea.top + chart.data.datasets[0].barThickness + 1;
  20617. ctx.fillText(hhmmss(currentTime, 5), x + 2, y, 100);
  20618. }
  20619. ctx.restore();
  20620. }
  20621. };
  20622. _proto.getCurrentTimeColor = function getCurrentTimeColor(video) {
  20623. if (!video.readyState || video.ended) {
  20624. return 'rgba(0, 0, 0, 0.9)';
  20625. }
  20626. if (video.seeking || video.readyState < 3) {
  20627. return 'rgba(255, 128, 0, 0.9)';
  20628. }
  20629. if (video.paused) {
  20630. return 'rgba(128, 0, 255, 0.9)';
  20631. }
  20632. return 'rgba(0, 0, 255, 0.9)';
  20633. };
  20634. _proto.drawLineX = function drawLineX(ctx, x, chartArea) {
  20635. if (!this.imageDataBuffer) {
  20636. var devicePixelRatio = self.devicePixelRatio || 1;
  20637. this.imageDataBuffer = ctx.getImageData(0, 0, chartArea.right * devicePixelRatio, chartArea.bottom * devicePixelRatio);
  20638. } else {
  20639. ctx.fillStyle = '#ffffff';
  20640. ctx.fillRect(0, 0, chartArea.right, chartArea.bottom);
  20641. ctx.putImageData(this.imageDataBuffer, 0, 0);
  20642. }
  20643. if (x > chartArea.left && x < chartArea.right) {
  20644. ctx.lineWidth = 1;
  20645. ctx.strokeStyle = this.getCurrentTimeColor(self.hls.media); // alpha '0.5'
  20646. ctx.beginPath();
  20647. ctx.moveTo(x, chartArea.top);
  20648. ctx.lineTo(x, chartArea.bottom);
  20649. ctx.stroke();
  20650. }
  20651. };
  20652. _createClass(TimelineChart, [{
  20653. key: "chartScales",
  20654. get: function get() {
  20655. return this.chart.scales;
  20656. }
  20657. }, {
  20658. key: "minZoom",
  20659. get: function get() {
  20660. var scale = this.chartScales[X_AXIS_SECONDS];
  20661. if (scale) {
  20662. return scale.options.ticks.min;
  20663. }
  20664. return 1;
  20665. }
  20666. // @ts-ignore
  20667. }, {
  20668. key: "maxZoom",
  20669. get: function get() {
  20670. var scale = this.chartScales[X_AXIS_SECONDS];
  20671. if (scale) {
  20672. return scale.options.ticks.max;
  20673. }
  20674. return this.zoom100;
  20675. }
  20676. // @ts-ignore
  20677. ,
  20678. set: function set(x) {
  20679. var currentZoom = this.maxZoom;
  20680. var newZoom = Math.max(x, currentZoom);
  20681. if (currentZoom === 60 && newZoom !== currentZoom) {
  20682. var scale = this.chartScales[X_AXIS_SECONDS];
  20683. scale.options.ticks.max = newZoom;
  20684. }
  20685. }
  20686. }]);
  20687. return TimelineChart;
  20688. }();
  20689. function stripDeliveryDirectives(url) {
  20690. if (url === '') {
  20691. return url;
  20692. }
  20693. try {
  20694. var webUrl = new self.URL(url);
  20695. webUrl.searchParams.delete('_HLS_msn');
  20696. webUrl.searchParams.delete('_HLS_part');
  20697. webUrl.searchParams.delete('_HLS_skip');
  20698. webUrl.searchParams.sort();
  20699. return webUrl.href;
  20700. } catch (e) {
  20701. return url.replace(/[?&]_HLS_(?:msn|part|skip)=[^?&]+/g, '');
  20702. }
  20703. }
  20704. function datasetWithDefaults(options) {
  20705. return _extends({
  20706. data: [],
  20707. xAxisID: X_AXIS_SECONDS,
  20708. barThickness: 35,
  20709. categoryPercentage: 1
  20710. }, options);
  20711. }
  20712. function getPlaylistStart(details) {
  20713. var _details$fragments;
  20714. return (_details$fragments = details.fragments) != null && _details$fragments.length ? details.fragments[0].start : 0;
  20715. }
  20716. function getLevelName(level, index) {
  20717. var _level$attrs;
  20718. var label = '(main playlist)';
  20719. if ((_level$attrs = level.attrs) != null && _level$attrs.BANDWIDTH) {
  20720. label = getMainLevelAttribute(level) + "@" + level.attrs.BANDWIDTH;
  20721. if (level.name) {
  20722. label = label + " (" + level.name + ")";
  20723. }
  20724. } else if (level.name) {
  20725. label = level.name;
  20726. }
  20727. return label + " L-" + index;
  20728. }
  20729. function getMainLevelAttribute(level) {
  20730. return level.attrs.RESOLUTION || level.attrs.CODECS || level.attrs.AUDIO;
  20731. }
  20732. function getAudioTrackName(track, index) {
  20733. var label = track.lang ? track.name + "/" + track.lang : track.name;
  20734. return label + " (" + (track.groupId || track.attrs['GROUP-ID']) + ") A-" + index;
  20735. }
  20736. function getSubtitlesName(track, index) {
  20737. var label = track.lang ? track.name + "/" + track.lang : track.name;
  20738. return label + " (" + (track.groupId || track.attrs['GROUP-ID']) + ") S-" + index;
  20739. }
  20740. function replaceTimeRangeTuples(timeRanges, data) {
  20741. data.length = 0;
  20742. var length = timeRanges.length;
  20743. for (var i = 0; i < length; i++) {
  20744. data.push([timeRanges.start(i), timeRanges.end(i)]);
  20745. }
  20746. }
  20747. function cuesMatch(cue1, cue2) {
  20748. return cue1.startTime === cue2.startTime && cue1.endTime === cue2.endTime && cue1.text === cue2.text && cue1.data === cue2.data && JSON.stringify(cue1.value) === JSON.stringify(cue2.value);
  20749. }
  20750. function getCueLabel(cue) {
  20751. if (cue.text) {
  20752. return cue.text;
  20753. }
  20754. var result = parseDataCue(cue);
  20755. return JSON.stringify(result);
  20756. }
  20757. function parseDataCue(cue) {
  20758. var data = {};
  20759. var value = cue.value;
  20760. if (value) {
  20761. if (value.info) {
  20762. var collection = data[value.key];
  20763. if (collection !== Object(collection)) {
  20764. collection = {};
  20765. data[value.key] = collection;
  20766. }
  20767. collection[value.info] = value.data;
  20768. } else {
  20769. data[value.key] = value.data;
  20770. }
  20771. }
  20772. return data;
  20773. }
  20774. function getChartOptions() {
  20775. return {
  20776. animation: {
  20777. duration: 0
  20778. },
  20779. elements: {
  20780. rectangle: {
  20781. borderWidth: 1,
  20782. borderColor: 'rgba(20, 20, 20, 1)'
  20783. }
  20784. },
  20785. events: ['click', 'touchstart'],
  20786. hover: {
  20787. mode: null,
  20788. animationDuration: 0
  20789. },
  20790. legend: {
  20791. display: false
  20792. },
  20793. maintainAspectRatio: false,
  20794. responsiveAnimationDuration: 0,
  20795. scales: {
  20796. // TODO: additional xAxes for PTS and PDT
  20797. xAxes: [{
  20798. id: X_AXIS_SECONDS,
  20799. ticks: {
  20800. beginAtZero: true,
  20801. sampleSize: 0,
  20802. maxRotation: 0,
  20803. callback: function callback(tickValue, i, ticks) {
  20804. if (i === 0 || i === ticks.length - 1) {
  20805. return tickValue ? '' : '0';
  20806. } else {
  20807. return hhmmss(tickValue, 2);
  20808. }
  20809. }
  20810. }
  20811. }],
  20812. yAxes: [{
  20813. gridLines: {
  20814. display: false
  20815. }
  20816. }]
  20817. },
  20818. tooltips: {
  20819. enabled: false
  20820. }
  20821. };
  20822. }
  20823. function arrayFind(array, predicate) {
  20824. var len = array.length >>> 0;
  20825. if (typeof predicate !== 'function') {
  20826. throw TypeError('predicate must be a function');
  20827. }
  20828. var thisArg = arguments[2];
  20829. var k = 0;
  20830. while (k < len) {
  20831. var kValue = array[k];
  20832. if (predicate.call(thisArg, kValue, k, array)) {
  20833. return kValue;
  20834. }
  20835. k++;
  20836. }
  20837. // eslint-disable-next-line no-undefined
  20838. return undefined;
  20839. }
  20840. /* global $, Hls, null */
  20841. var STORAGE_KEYS = {
  20842. Editor_Persistence: 'hlsjs:config-editor-persist',
  20843. Hls_Config: 'hlsjs:config',
  20844. volume: 'hlsjs:volume',
  20845. demo_tabs: 'hlsjs:demo-tabs'
  20846. };
  20847. var testStreams = testStreams$1;
  20848. var defaultTestStreamUrl = testStreams[Object.keys(testStreams)[0]].url;
  20849. var sourceURL = decodeURIComponent(getURLParam('src', defaultTestStreamUrl));
  20850. var demoConfig = getURLParam('demoConfig', null);
  20851. if (demoConfig) {
  20852. demoConfig = JSON.parse(atob(demoConfig));
  20853. } else {
  20854. demoConfig = {};
  20855. }
  20856. var hlsjsDefaults = {
  20857. debug: true,
  20858. enableWorker: true,
  20859. lowLatencyMode: true,
  20860. backBufferLength: 60 * 1.5
  20861. };
  20862. var enableStreaming = getDemoConfigPropOrDefault('enableStreaming', true);
  20863. var autoRecoverError = getDemoConfigPropOrDefault('autoRecoverError', true);
  20864. var levelCapping = getDemoConfigPropOrDefault('levelCapping', -1);
  20865. var limitMetrics = getDemoConfigPropOrDefault('limitMetrics', -1);
  20866. var dumpfMP4 = getDemoConfigPropOrDefault('dumpfMP4', false);
  20867. var stopOnStall = getDemoConfigPropOrDefault('stopOnStall', false);
  20868. var bufferingIdx = -1;
  20869. var selectedTestStream = null;
  20870. var video = document.querySelector('#video');
  20871. var startTime = Date.now();
  20872. var lastSeekingIdx;
  20873. var lastStartPosition;
  20874. var lastDuration;
  20875. var lastAudioTrackSwitchingIdx;
  20876. var hls;
  20877. var url;
  20878. var events;
  20879. var stats;
  20880. var tracks;
  20881. var fmp4Data;
  20882. var configPersistenceEnabled = false;
  20883. var configEditor = null;
  20884. var chart;
  20885. var resizeAsyncCallbackId = -1;
  20886. var requestAnimationFrame = self.requestAnimationFrame || self.setTimeout;
  20887. var cancelAnimationFrame = self.cancelAnimationFrame || self.clearTimeout;
  20888. var resizeHandlers = [];
  20889. var resize = function resize() {
  20890. cancelAnimationFrame(resizeAsyncCallbackId);
  20891. resizeAsyncCallbackId = requestAnimationFrame(function () {
  20892. resizeHandlers.forEach(function (handler) {
  20893. handler();
  20894. });
  20895. });
  20896. };
  20897. self.onresize = resize;
  20898. if (self.screen && self.screen.orientation) {
  20899. self.screen.orientation.onchange = resize;
  20900. }
  20901. var playerResize = function playerResize() {
  20902. var bounds = video.getBoundingClientRect();
  20903. $('#currentSize').html(Math.round(bounds.width * 10) / 10 + " x " + Math.round(bounds.height * 10) / 10);
  20904. if (video.videoWidth && video.videoHeight) {
  20905. $('#currentResolution').html(video.videoWidth + " x " + video.videoHeight);
  20906. }
  20907. };
  20908. resizeHandlers.push(playerResize);
  20909. $(document).ready(function () {
  20910. setupConfigEditor();
  20911. chart = setupTimelineChart();
  20912. Object.keys(testStreams).forEach(function (key, index) {
  20913. var stream = testStreams[key];
  20914. var option = new Option(stream.description, key);
  20915. $('#streamSelect').append(option);
  20916. if (stream.url === sourceURL) {
  20917. document.querySelector('#streamSelect').selectedIndex = index + 1;
  20918. }
  20919. });
  20920. var videoWidth = video.style.width;
  20921. if (videoWidth) {
  20922. $('#videoSize option').each(function (i, option) {
  20923. if (option.value === videoWidth) {
  20924. document.querySelector('#videoSize').selectedIndex = i;
  20925. $('#bufferedCanvas').width(videoWidth);
  20926. resize();
  20927. return false;
  20928. }
  20929. });
  20930. }
  20931. $('#streamSelect').change(function () {
  20932. var key = $('#streamSelect').val() || Object.keys(testStreams)[0];
  20933. selectedTestStream = testStreams[key];
  20934. var streamUrl = selectedTestStream.url;
  20935. $('#streamURL').val(streamUrl);
  20936. loadSelectedStream();
  20937. });
  20938. $('#streamURL').change(function () {
  20939. selectedTestStream = null;
  20940. loadSelectedStream();
  20941. });
  20942. $('#videoSize').change(function () {
  20943. $('#video').width($('#videoSize').val());
  20944. $('#bufferedCanvas').width($('#videoSize').val());
  20945. checkBuffer();
  20946. resize();
  20947. });
  20948. $('#enableStreaming').click(function () {
  20949. enableStreaming = this.checked;
  20950. loadSelectedStream();
  20951. });
  20952. $('#autoRecoverError').click(function () {
  20953. autoRecoverError = this.checked;
  20954. onDemoConfigChanged();
  20955. });
  20956. $('#stopOnStall').click(function () {
  20957. stopOnStall = this.checked;
  20958. onDemoConfigChanged();
  20959. });
  20960. $('#dumpfMP4').click(function () {
  20961. dumpfMP4 = this.checked;
  20962. $('.btn-dump').toggle(dumpfMP4);
  20963. onDemoConfigChanged();
  20964. });
  20965. $('#limitMetrics').change(function () {
  20966. limitMetrics = this.value;
  20967. onDemoConfigChanged();
  20968. });
  20969. $('#levelCapping').change(function () {
  20970. levelCapping = this.value;
  20971. onDemoConfigChanged();
  20972. });
  20973. $('#limitMetrics').val(limitMetrics);
  20974. $('#enableStreaming').prop('checked', enableStreaming);
  20975. $('#autoRecoverError').prop('checked', autoRecoverError);
  20976. $('#stopOnStall').prop('checked', stopOnStall);
  20977. $('#dumpfMP4').prop('checked', dumpfMP4);
  20978. $('#levelCapping').val(levelCapping);
  20979. // If cloudflare pages build link to branch
  20980. // If not a stable tag link to npm
  20981. // otherwise link to github tag
  20982. function getVersionLink(version) {
  20983. var noneStable = version.includes('-');
  20984. if (noneStable) {
  20985. return "https://www.npmjs.com/package/hls.js/v/" + encodeURIComponent(version);
  20986. } else {
  20987. return "https://github.com/video-dev/hls.js/releases/tag/v" + encodeURIComponent(version);
  20988. }
  20989. }
  20990. var version = Hls.version;
  20991. if (version) {
  20992. var $a = $('<a />').attr('target', '_blank').attr('rel', 'noopener noreferrer').attr('href', getVersionLink(version)).text('v' + version);
  20993. $('.title').append(' ').append($a);
  20994. }
  20995. $('#streamURL').val(sourceURL);
  20996. var volumeSettings = JSON.parse(localStorage.getItem(STORAGE_KEYS.volume)) || {
  20997. volume: 0.05,
  20998. muted: false
  20999. };
  21000. video.volume = volumeSettings.volume;
  21001. video.muted = volumeSettings.muted;
  21002. $('.btn-dump').toggle(dumpfMP4);
  21003. $('#toggleButtons').show();
  21004. $('#metricsButtonWindow').toggle(self.windowSliding);
  21005. $('#metricsButtonFixed').toggle(!self.windowSliding);
  21006. loadSelectedStream();
  21007. var tabIndexesCSV = localStorage.getItem(STORAGE_KEYS.demo_tabs);
  21008. if (tabIndexesCSV === null) {
  21009. tabIndexesCSV = '0,1,2';
  21010. }
  21011. if (tabIndexesCSV) {
  21012. tabIndexesCSV.split(',').forEach(function (indexString) {
  21013. toggleTab($('.demo-tab-btn')[parseInt(indexString) || 0], true);
  21014. });
  21015. }
  21016. $(self).on('popstate', function () {
  21017. self.location.reload();
  21018. });
  21019. });
  21020. function setupGlobals() {
  21021. self.events = events = {
  21022. url: url,
  21023. t0: self.performance.now(),
  21024. load: [],
  21025. buffer: [],
  21026. video: [],
  21027. level: [],
  21028. bitrate: []
  21029. };
  21030. lastAudioTrackSwitchingIdx = undefined;
  21031. lastSeekingIdx = undefined;
  21032. bufferingIdx = -1;
  21033. // actual values, only on window
  21034. self.recoverDecodingErrorDate = null;
  21035. self.recoverSwapAudioCodecDate = null;
  21036. self.fmp4Data = fmp4Data = {
  21037. audio: [],
  21038. video: []
  21039. };
  21040. self.onClickBufferedRange = onClickBufferedRange;
  21041. self.updateLevelInfo = updateLevelInfo;
  21042. self.onDemoConfigChanged = onDemoConfigChanged;
  21043. self.createfMP4 = createfMP4;
  21044. self.goToMetricsPermaLink = goToMetricsPermaLink;
  21045. self.toggleTab = toggleTab;
  21046. self.toggleTabClick = toggleTabClick;
  21047. self.applyConfigEditorValue = applyConfigEditorValue;
  21048. }
  21049. function trimArray(target, limit) {
  21050. if (limit < 0) {
  21051. return;
  21052. }
  21053. while (target.length > limit) {
  21054. target.shift();
  21055. }
  21056. }
  21057. function trimEventHistory() {
  21058. var x = limitMetrics;
  21059. if (x < 0) {
  21060. return;
  21061. }
  21062. trimArray(events.load, x);
  21063. trimArray(events.buffer, x);
  21064. trimArray(events.video, x);
  21065. trimArray(events.level, x);
  21066. trimArray(events.bitrate, x);
  21067. }
  21068. function loadSelectedStream() {
  21069. $('#statusOut,#errorOut').empty();
  21070. if (!Hls.isSupported()) {
  21071. handleUnsupported();
  21072. return;
  21073. }
  21074. url = $('#streamURL').val();
  21075. setupGlobals();
  21076. hideCanvas();
  21077. if (hls) {
  21078. hls.destroy();
  21079. clearInterval(hls.bufferTimer);
  21080. hls = null;
  21081. }
  21082. if (!enableStreaming) {
  21083. logStatus('Streaming disabled');
  21084. return;
  21085. }
  21086. logStatus('Loading ' + url);
  21087. // Extending both a demo-specific config and the user config which can override all
  21088. var hlsConfig = $.extend({}, hlsjsDefaults, getEditorValue({
  21089. parse: true
  21090. }));
  21091. if (selectedTestStream && selectedTestStream.config) {
  21092. console.info('[loadSelectedStream] extending hls config with stream-specific config: ', selectedTestStream.config);
  21093. $.extend(hlsConfig, selectedTestStream.config);
  21094. updateConfigEditorValue(hlsConfig);
  21095. }
  21096. onDemoConfigChanged(true);
  21097. console.log('Using Hls.js config:', hlsConfig);
  21098. self.hls = hls = new Hls(hlsConfig);
  21099. logStatus('Loading manifest and attaching video element...');
  21100. var expiredTracks = [].filter.call(video.textTracks, function (track) {
  21101. return track.kind !== 'metadata';
  21102. });
  21103. if (expiredTracks.length) {
  21104. var kinds = expiredTracks.map(function (track) {
  21105. return track.kind;
  21106. }).filter(function (kind, index, self) {
  21107. return self.indexOf(kind) === index;
  21108. });
  21109. logStatus("Replacing video element to remove " + kinds.join(' and ') + " text tracks");
  21110. var videoWithExpiredTextTracks = video;
  21111. video = videoWithExpiredTextTracks.cloneNode(false);
  21112. video.removeAttribute('src');
  21113. video.volume = videoWithExpiredTextTracks.volume;
  21114. video.muted = videoWithExpiredTextTracks.muted;
  21115. videoWithExpiredTextTracks.parentNode.insertBefore(video, videoWithExpiredTextTracks);
  21116. videoWithExpiredTextTracks.parentNode.removeChild(videoWithExpiredTextTracks);
  21117. }
  21118. addChartEventListeners(hls);
  21119. addVideoEventListeners(video);
  21120. hls.loadSource(url);
  21121. hls.autoLevelCapping = levelCapping;
  21122. hls.attachMedia(video);
  21123. hls.on(Hls.Events.MEDIA_ATTACHED, function () {
  21124. logStatus('Media element attached');
  21125. bufferingIdx = -1;
  21126. events.video.push({
  21127. time: self.performance.now() - events.t0,
  21128. type: 'Media attached'
  21129. });
  21130. trimEventHistory();
  21131. });
  21132. hls.on(Hls.Events.MEDIA_DETACHED, function () {
  21133. logStatus('Media element detached');
  21134. clearInterval(hls.bufferTimer);
  21135. bufferingIdx = -1;
  21136. tracks = [];
  21137. events.video.push({
  21138. time: self.performance.now() - events.t0,
  21139. type: 'Media detached'
  21140. });
  21141. trimEventHistory();
  21142. });
  21143. hls.on(Hls.Events.DESTROYING, function () {
  21144. clearInterval(hls.bufferTimer);
  21145. });
  21146. hls.on(Hls.Events.BUFFER_RESET, function () {
  21147. clearInterval(hls.bufferTimer);
  21148. });
  21149. hls.on(Hls.Events.FRAG_PARSING_INIT_SEGMENT, function (eventName, data) {
  21150. showCanvas();
  21151. events.video.push({
  21152. time: self.performance.now() - events.t0,
  21153. type: data.id + ' init segment'
  21154. });
  21155. trimEventHistory();
  21156. });
  21157. hls.on(Hls.Events.FRAG_PARSING_METADATA, function (eventName, data) {
  21158. // console.log("Id3 samples ", data.samples);
  21159. });
  21160. hls.on(Hls.Events.LEVEL_SWITCHING, function (eventName, data) {
  21161. events.level.push({
  21162. time: self.performance.now() - events.t0,
  21163. id: data.level,
  21164. bitrate: Math.round(hls.levels[data.level].bitrate / 1000)
  21165. });
  21166. trimEventHistory();
  21167. updateLevelInfo();
  21168. });
  21169. hls.on(Hls.Events.MANIFEST_PARSED, function (eventName, data) {
  21170. events.load.push({
  21171. type: 'manifest',
  21172. name: '',
  21173. start: 0,
  21174. end: data.levels.length,
  21175. time: data.stats.loading.start - events.t0,
  21176. latency: data.stats.loading.first - data.stats.loading.start,
  21177. load: data.stats.loading.end - data.stats.loading.first,
  21178. duration: data.stats.loading.end - data.stats.loading.first
  21179. });
  21180. trimEventHistory();
  21181. self.refreshCanvas();
  21182. });
  21183. hls.on(Hls.Events.MANIFEST_PARSED, function (eventName, data) {
  21184. logStatus(hls.levels.length + " quality levels found");
  21185. logStatus('Manifest successfully loaded');
  21186. stats = {
  21187. levelNb: data.levels.length,
  21188. levelParsed: 0
  21189. };
  21190. trimEventHistory();
  21191. updateLevelInfo();
  21192. });
  21193. hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, function (eventName, data) {
  21194. logStatus('No of audio tracks found: ' + data.audioTracks.length);
  21195. updateAudioTrackInfo();
  21196. });
  21197. hls.on(Hls.Events.AUDIO_TRACK_SWITCHING, function (eventName, data) {
  21198. logStatus('Audio track switching...');
  21199. updateAudioTrackInfo();
  21200. events.video.push({
  21201. time: self.performance.now() - events.t0,
  21202. type: 'audio switching',
  21203. name: '@' + data.id
  21204. });
  21205. trimEventHistory();
  21206. lastAudioTrackSwitchingIdx = events.video.length - 1;
  21207. });
  21208. hls.on(Hls.Events.AUDIO_TRACK_SWITCHED, function (eventName, data) {
  21209. logStatus('Audio track switched');
  21210. updateAudioTrackInfo();
  21211. var event = {
  21212. time: self.performance.now() - events.t0,
  21213. type: 'audio switched',
  21214. name: '@' + data.id
  21215. };
  21216. if (lastAudioTrackSwitchingIdx !== undefined) {
  21217. events.video[lastAudioTrackSwitchingIdx].duration = event.time - events.video[lastAudioTrackSwitchingIdx].time;
  21218. lastAudioTrackSwitchingIdx = undefined;
  21219. }
  21220. events.video.push(event);
  21221. trimEventHistory();
  21222. });
  21223. hls.on(Hls.Events.LEVEL_LOADED, function (eventName, data) {
  21224. events.isLive = data.details.live;
  21225. var event = {
  21226. type: 'level',
  21227. id: data.level,
  21228. start: data.details.startSN,
  21229. end: data.details.endSN,
  21230. time: data.stats.loading.start - events.t0,
  21231. latency: data.stats.loading.first - data.stats.loading.start,
  21232. load: data.stats.loading.end - data.stats.loading.first,
  21233. parsing: data.stats.parsing.end - data.stats.loading.end,
  21234. duration: data.stats.loading.end - data.stats.loading.first
  21235. };
  21236. var parsingDuration = data.stats.parsing.end - data.stats.loading.end;
  21237. if (stats.levelParsed) {
  21238. this.sumLevelParsingMs += parsingDuration;
  21239. } else {
  21240. this.sumLevelParsingMs = parsingDuration;
  21241. }
  21242. stats.levelParsed++;
  21243. stats.levelParsingUs = Math.round(1000 * this.sumLevelParsingMs / stats.levelParsed);
  21244. // console.log('parsing level duration :' + stats.levelParsingUs + 'us,count:' + stats.levelParsed);
  21245. events.load.push(event);
  21246. trimEventHistory();
  21247. self.refreshCanvas();
  21248. });
  21249. hls.on(Hls.Events.AUDIO_TRACK_LOADED, function (eventName, data) {
  21250. events.isLive = data.details.live;
  21251. var event = {
  21252. type: 'audio track',
  21253. id: data.id,
  21254. start: data.details.startSN,
  21255. end: data.details.endSN,
  21256. time: data.stats.loading.start - events.t0,
  21257. latency: data.stats.loading.first - data.stats.loading.start,
  21258. load: data.stats.loading.end - data.stats.loading.first,
  21259. parsing: data.stats.parsing.end - data.stats.loading.end,
  21260. duration: data.stats.loading.end - data.stats.loading.first
  21261. };
  21262. events.load.push(event);
  21263. trimEventHistory();
  21264. self.refreshCanvas();
  21265. });
  21266. hls.on(Hls.Events.FRAG_BUFFERED, function (eventName, data) {
  21267. var stats = data.part && data.part.stats && data.part.stats.loaded ? data.part.stats : data.frag.stats;
  21268. if (data.stats.aborted) {
  21269. console.assert('Aborted request being buffered.', data);
  21270. return;
  21271. }
  21272. var event = {
  21273. type: data.frag.type + (data.part ? ' part' : ' fragment'),
  21274. id: data.frag.level,
  21275. id2: data.frag.sn,
  21276. id3: data.part ? data.part.index : undefined,
  21277. time: data.stats.loading.start - events.t0,
  21278. latency: data.stats.loading.first - data.stats.loading.start,
  21279. load: data.stats.loading.end - data.stats.loading.first,
  21280. parsing: data.stats.parsing.end - data.stats.loading.end,
  21281. buffer: data.stats.buffering.end - data.stats.parsing.end,
  21282. duration: data.stats.buffering.end - data.stats.loading.first,
  21283. bw: Math.round(8 * data.stats.total / (data.stats.buffering.end - data.stats.loading.start)),
  21284. // bandwidth of this fragment
  21285. ewma: Math.round(hls.bandwidthEstimate / 1000),
  21286. // estimated bandwidth
  21287. size: data.stats.total
  21288. };
  21289. events.load.push(event);
  21290. events.bitrate.push({
  21291. time: self.performance.now() - events.t0,
  21292. bitrate: event.bw,
  21293. ewma: event.ewma,
  21294. duration: data.frag.duration,
  21295. level: event.id
  21296. });
  21297. if (events.buffer.length === 0) {
  21298. events.buffer.push({
  21299. time: 0,
  21300. buffer: 0,
  21301. pos: 0
  21302. });
  21303. }
  21304. clearInterval(hls.bufferTimer);
  21305. hls.bufferTimer = self.setInterval(checkBuffer, 100);
  21306. trimEventHistory();
  21307. self.refreshCanvas();
  21308. updateLevelInfo();
  21309. var latency = data.stats.loading.first - data.stats.loading.start;
  21310. var parsing = data.stats.parsing.end - data.stats.loading.end;
  21311. var process = data.stats.buffering.end - data.stats.loading.start;
  21312. var bitrate = Math.round(8 * data.stats.total / (data.stats.buffering.end - data.stats.loading.first));
  21313. if (stats.fragBuffered) {
  21314. stats.fragMinLatency = Math.min(stats.fragMinLatency, latency);
  21315. stats.fragMaxLatency = Math.max(stats.fragMaxLatency, latency);
  21316. stats.fragMinProcess = Math.min(stats.fragMinProcess, process);
  21317. stats.fragMaxProcess = Math.max(stats.fragMaxProcess, process);
  21318. stats.fragMinKbps = Math.min(stats.fragMinKbps, bitrate);
  21319. stats.fragMaxKbps = Math.max(stats.fragMaxKbps, bitrate);
  21320. stats.autoLevelCappingMin = Math.min(stats.autoLevelCappingMin, hls.autoLevelCapping);
  21321. stats.autoLevelCappingMax = Math.max(stats.autoLevelCappingMax, hls.autoLevelCapping);
  21322. stats.fragBuffered++;
  21323. } else {
  21324. stats.fragMinLatency = stats.fragMaxLatency = latency;
  21325. stats.fragMinProcess = stats.fragMaxProcess = process;
  21326. stats.fragMinKbps = stats.fragMaxKbps = bitrate;
  21327. stats.fragBuffered = 1;
  21328. stats.fragBufferedBytes = 0;
  21329. stats.autoLevelCappingMin = stats.autoLevelCappingMax = hls.autoLevelCapping;
  21330. this.sumLatency = 0;
  21331. this.sumKbps = 0;
  21332. this.sumProcess = 0;
  21333. this.sumParsing = 0;
  21334. }
  21335. stats.fraglastLatency = latency;
  21336. this.sumLatency += latency;
  21337. stats.fragAvgLatency = Math.round(this.sumLatency / stats.fragBuffered);
  21338. stats.fragLastProcess = process;
  21339. this.sumProcess += process;
  21340. this.sumParsing += parsing;
  21341. stats.fragAvgProcess = Math.round(this.sumProcess / stats.fragBuffered);
  21342. stats.fragLastKbps = bitrate;
  21343. this.sumKbps += bitrate;
  21344. stats.fragAvgKbps = Math.round(this.sumKbps / stats.fragBuffered);
  21345. stats.fragBufferedBytes += data.stats.total;
  21346. stats.fragparsingKbps = Math.round(8 * stats.fragBufferedBytes / this.sumParsing);
  21347. stats.fragparsingMs = Math.round(this.sumParsing);
  21348. stats.autoLevelCappingLast = hls.autoLevelCapping;
  21349. });
  21350. hls.on(Hls.Events.LEVEL_SWITCHED, function (eventName, data) {
  21351. var event = {
  21352. time: self.performance.now() - events.t0,
  21353. type: 'level switched',
  21354. name: data.level
  21355. };
  21356. events.video.push(event);
  21357. trimEventHistory();
  21358. self.refreshCanvas();
  21359. updateLevelInfo();
  21360. });
  21361. hls.on(Hls.Events.FRAG_CHANGED, function (eventName, data) {
  21362. var event = {
  21363. time: self.performance.now() - events.t0,
  21364. type: 'frag changed',
  21365. name: data.frag.sn + ' @ ' + data.frag.level
  21366. };
  21367. events.video.push(event);
  21368. trimEventHistory();
  21369. self.refreshCanvas();
  21370. updateLevelInfo();
  21371. stats.tagList = data.frag.tagList;
  21372. var level = data.frag.level;
  21373. var autoLevel = hls.autoLevelEnabled;
  21374. if (stats.levelStart === undefined) {
  21375. stats.levelStart = level;
  21376. }
  21377. stats.fragProgramDateTime = data.frag.programDateTime;
  21378. stats.fragStart = data.frag.start;
  21379. if (autoLevel) {
  21380. if (stats.fragChangedAuto) {
  21381. stats.autoLevelMin = Math.min(stats.autoLevelMin, level);
  21382. stats.autoLevelMax = Math.max(stats.autoLevelMax, level);
  21383. stats.fragChangedAuto++;
  21384. if (this.levelLastAuto && level !== stats.autoLevelLast) {
  21385. stats.autoLevelSwitch++;
  21386. }
  21387. } else {
  21388. stats.autoLevelMin = stats.autoLevelMax = level;
  21389. stats.autoLevelSwitch = 0;
  21390. stats.fragChangedAuto = 1;
  21391. this.sumAutoLevel = 0;
  21392. }
  21393. this.sumAutoLevel += level;
  21394. stats.autoLevelAvg = Math.round(1000 * this.sumAutoLevel / stats.fragChangedAuto) / 1000;
  21395. stats.autoLevelLast = level;
  21396. } else {
  21397. if (stats.fragChangedManual) {
  21398. stats.manualLevelMin = Math.min(stats.manualLevelMin, level);
  21399. stats.manualLevelMax = Math.max(stats.manualLevelMax, level);
  21400. stats.fragChangedManual++;
  21401. if (!this.levelLastAuto && level !== stats.manualLevelLast) {
  21402. stats.manualLevelSwitch++;
  21403. }
  21404. } else {
  21405. stats.manualLevelMin = stats.manualLevelMax = level;
  21406. stats.manualLevelSwitch = 0;
  21407. stats.fragChangedManual = 1;
  21408. }
  21409. stats.manualLevelLast = level;
  21410. }
  21411. this.levelLastAuto = autoLevel;
  21412. });
  21413. hls.on(Hls.Events.FRAG_LOAD_EMERGENCY_ABORTED, function (eventName, data) {
  21414. if (stats) {
  21415. if (stats.fragLoadEmergencyAborted === undefined) {
  21416. stats.fragLoadEmergencyAborted = 1;
  21417. } else {
  21418. stats.fragLoadEmergencyAborted++;
  21419. }
  21420. }
  21421. });
  21422. hls.on(Hls.Events.FRAG_DECRYPTED, function (eventName, data) {
  21423. if (!stats.fragDecrypted) {
  21424. stats.fragDecrypted = 0;
  21425. this.totalDecryptTime = 0;
  21426. stats.fragAvgDecryptTime = 0;
  21427. }
  21428. stats.fragDecrypted++;
  21429. this.totalDecryptTime += data.stats.tdecrypt - data.stats.tstart;
  21430. stats.fragAvgDecryptTime = this.totalDecryptTime / stats.fragDecrypted;
  21431. });
  21432. hls.on(Hls.Events.ERROR, function (eventName, data) {
  21433. console.warn('Error event:', data);
  21434. switch (data.details) {
  21435. case Hls.ErrorDetails.MANIFEST_LOAD_ERROR:
  21436. try {
  21437. $('#errorOut').html('Cannot load <a href="' + data.context.url + '">' + url + '</a><br>HTTP response code:' + data.response.code + ' <br>' + data.response.text);
  21438. if (data.response.code === 0) {
  21439. $('#errorOut').append('This might be a CORS issue, consider installing <a href="https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi">Allow-Control-Allow-Origin</a> Chrome Extension');
  21440. }
  21441. } catch (err) {
  21442. $('#errorOut').html('Cannot load <a href="' + data.context.url + '">' + url + '</a><br>Response body: ' + data.response.text);
  21443. }
  21444. break;
  21445. case Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  21446. logError('Timeout while loading manifest');
  21447. break;
  21448. case Hls.ErrorDetails.MANIFEST_PARSING_ERROR:
  21449. logError('Error while parsing manifest:' + data.reason);
  21450. break;
  21451. case Hls.ErrorDetails.LEVEL_EMPTY_ERROR:
  21452. logError('Loaded level contains no fragments ' + data.level + ' ' + data.url);
  21453. // handleLevelError demonstrates how to remove a level that errors followed by a downswitch
  21454. // handleLevelError(data);
  21455. break;
  21456. case Hls.ErrorDetails.LEVEL_LOAD_ERROR:
  21457. logError('Error while loading level playlist ' + data.context.level + ' ' + data.url);
  21458. // handleLevelError demonstrates how to remove a level that errors followed by a downswitch
  21459. // handleLevelError(data);
  21460. break;
  21461. case Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  21462. logError('Timeout while loading level playlist ' + data.context.level + ' ' + data.url);
  21463. // handleLevelError demonstrates how to remove a level that errors followed by a downswitch
  21464. // handleLevelError(data);
  21465. break;
  21466. case Hls.ErrorDetails.LEVEL_SWITCH_ERROR:
  21467. logError('Error while trying to switch to level ' + data.level);
  21468. break;
  21469. case Hls.ErrorDetails.FRAG_LOAD_ERROR:
  21470. logError('Error while loading fragment ' + data.frag.url);
  21471. break;
  21472. case Hls.ErrorDetails.FRAG_LOAD_TIMEOUT:
  21473. logError('Timeout while loading fragment ' + data.frag.url);
  21474. break;
  21475. case Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
  21476. logError('Fragment-loop loading error');
  21477. break;
  21478. case Hls.ErrorDetails.FRAG_DECRYPT_ERROR:
  21479. logError('Decrypting error:' + data.reason);
  21480. break;
  21481. case Hls.ErrorDetails.FRAG_PARSING_ERROR:
  21482. logError('Parsing error:' + data.reason);
  21483. break;
  21484. case Hls.ErrorDetails.KEY_LOAD_ERROR:
  21485. logError('Error while loading key ' + data.frag.decryptdata.uri);
  21486. break;
  21487. case Hls.ErrorDetails.KEY_LOAD_TIMEOUT:
  21488. logError('Timeout while loading key ' + data.frag.decryptdata.uri);
  21489. break;
  21490. case Hls.ErrorDetails.BUFFER_APPEND_ERROR:
  21491. logError('Buffer append error');
  21492. break;
  21493. case Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  21494. logError('Buffer add codec error for ' + data.mimeType + ':' + data.error.message);
  21495. break;
  21496. case Hls.ErrorDetails.BUFFER_APPENDING_ERROR:
  21497. logError('Buffer appending error');
  21498. break;
  21499. case Hls.ErrorDetails.BUFFER_STALLED_ERROR:
  21500. logError('Buffer stalled error');
  21501. if (stopOnStall) {
  21502. hls.stopLoad();
  21503. video.pause();
  21504. }
  21505. break;
  21506. }
  21507. if (data.fatal) {
  21508. console.error("Fatal error : " + data.details);
  21509. switch (data.type) {
  21510. case Hls.ErrorTypes.MEDIA_ERROR:
  21511. logError("A media error occurred: " + data.details);
  21512. handleMediaError();
  21513. break;
  21514. case Hls.ErrorTypes.NETWORK_ERROR:
  21515. logError("A network error occurred: " + data.details);
  21516. break;
  21517. default:
  21518. logError("An unrecoverable error occurred: " + data.details);
  21519. hls.destroy();
  21520. break;
  21521. }
  21522. }
  21523. if (!stats) {
  21524. stats = {};
  21525. }
  21526. // track all errors independently
  21527. if (stats[data.details] === undefined) {
  21528. stats[data.details] = 1;
  21529. } else {
  21530. stats[data.details] += 1;
  21531. }
  21532. // track fatal error
  21533. if (data.fatal) {
  21534. if (stats.fatalError === undefined) {
  21535. stats.fatalError = 1;
  21536. } else {
  21537. stats.fatalError += 1;
  21538. }
  21539. }
  21540. $('#statisticsOut').text(JSON.stringify(sortObject(stats), null, '\t'));
  21541. });
  21542. hls.on(Hls.Events.BUFFER_CREATED, function (eventName, data) {
  21543. tracks = data.tracks;
  21544. });
  21545. hls.on(Hls.Events.BUFFER_APPENDING, function (eventName, data) {
  21546. if (dumpfMP4) {
  21547. fmp4Data[data.type].push(data.data);
  21548. }
  21549. });
  21550. hls.on(Hls.Events.FPS_DROP, function (eventName, data) {
  21551. var event = {
  21552. time: self.performance.now() - events.t0,
  21553. type: 'frame drop',
  21554. name: data.currentDropped + '/' + data.currentDecoded
  21555. };
  21556. events.video.push(event);
  21557. trimEventHistory();
  21558. if (stats) {
  21559. if (stats.fpsDropEvent === undefined) {
  21560. stats.fpsDropEvent = 1;
  21561. } else {
  21562. stats.fpsDropEvent++;
  21563. }
  21564. stats.fpsTotalDroppedFrames = data.totalDroppedFrames;
  21565. }
  21566. });
  21567. }
  21568. function addVideoEventListeners(video) {
  21569. video.removeEventListener('resize', handleVideoEvent);
  21570. video.removeEventListener('seeking', handleVideoEvent);
  21571. video.removeEventListener('seeked', handleVideoEvent);
  21572. video.removeEventListener('pause', handleVideoEvent);
  21573. video.removeEventListener('play', handleVideoEvent);
  21574. video.removeEventListener('canplay', handleVideoEvent);
  21575. video.removeEventListener('canplaythrough', handleVideoEvent);
  21576. video.removeEventListener('ended', handleVideoEvent);
  21577. video.removeEventListener('playing', handleVideoEvent);
  21578. video.removeEventListener('error', handleVideoEvent);
  21579. video.removeEventListener('loadedmetadata', handleVideoEvent);
  21580. video.removeEventListener('loadeddata', handleVideoEvent);
  21581. video.removeEventListener('durationchange', handleVideoEvent);
  21582. video.removeEventListener('volumechange', handleVolumeEvent);
  21583. video.addEventListener('resize', handleVideoEvent);
  21584. video.addEventListener('seeking', handleVideoEvent);
  21585. video.addEventListener('seeked', handleVideoEvent);
  21586. video.addEventListener('pause', handleVideoEvent);
  21587. video.addEventListener('play', handleVideoEvent);
  21588. video.addEventListener('canplay', handleVideoEvent);
  21589. video.addEventListener('canplaythrough', handleVideoEvent);
  21590. video.addEventListener('ended', handleVideoEvent);
  21591. video.addEventListener('playing', handleVideoEvent);
  21592. video.addEventListener('error', handleVideoEvent);
  21593. video.addEventListener('loadedmetadata', handleVideoEvent);
  21594. video.addEventListener('loadeddata', handleVideoEvent);
  21595. video.addEventListener('durationchange', handleVideoEvent);
  21596. video.addEventListener('volumechange', handleVolumeEvent);
  21597. }
  21598. function handleUnsupported() {
  21599. if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1) {
  21600. logStatus('You are using Firefox, it looks like MediaSource is not enabled,<br>please ensure the following keys are set appropriately in <b>about:config</b><br>media.mediasource.enabled=true<br>media.mediasource.mp4.enabled=true<br><b>media.mediasource.whitelist=false</b>');
  21601. } else {
  21602. logStatus('Your Browser does not support MediaSourceExtension / MP4 mediasource');
  21603. }
  21604. }
  21605. function handleVideoEvent(evt) {
  21606. var data = '';
  21607. switch (evt.type) {
  21608. case 'durationchange':
  21609. if (evt.target.duration - lastDuration <= 0.5) {
  21610. // some browsers report several duration change events with almost the same value ... avoid spamming video events
  21611. return;
  21612. }
  21613. lastDuration = evt.target.duration;
  21614. data = Math.round(evt.target.duration * 1000);
  21615. break;
  21616. case 'resize':
  21617. data = evt.target.videoWidth + '/' + evt.target.videoHeight;
  21618. playerResize();
  21619. break;
  21620. case 'loadedmetadata':
  21621. case 'loadeddata':
  21622. case 'canplay':
  21623. case 'canplaythrough':
  21624. case 'ended':
  21625. case 'seeking':
  21626. case 'seeked':
  21627. case 'play':
  21628. case 'playing':
  21629. lastStartPosition = evt.target.currentTime;
  21630. case 'pause':
  21631. case 'waiting':
  21632. case 'stalled':
  21633. case 'error':
  21634. data = Math.round(evt.target.currentTime * 1000);
  21635. if (evt.type === 'error') {
  21636. var errorTxt;
  21637. var mediaError = evt.currentTarget.error;
  21638. switch (mediaError.code) {
  21639. case mediaError.MEDIA_ERR_ABORTED:
  21640. errorTxt = 'You aborted the video playback';
  21641. break;
  21642. case mediaError.MEDIA_ERR_DECODE:
  21643. errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support';
  21644. handleMediaError();
  21645. break;
  21646. case mediaError.MEDIA_ERR_NETWORK:
  21647. errorTxt = 'A network error caused the video download to fail part-way';
  21648. break;
  21649. case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
  21650. errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported';
  21651. break;
  21652. }
  21653. if (mediaError.message) {
  21654. errorTxt += ' - ' + mediaError.message;
  21655. }
  21656. logStatus(errorTxt);
  21657. console.error(errorTxt);
  21658. }
  21659. break;
  21660. }
  21661. var event = {
  21662. time: self.performance.now() - events.t0,
  21663. type: evt.type,
  21664. name: data
  21665. };
  21666. events.video.push(event);
  21667. if (evt.type === 'seeking') {
  21668. lastSeekingIdx = events.video.length - 1;
  21669. }
  21670. if (evt.type === 'seeked') {
  21671. events.video[lastSeekingIdx].duration = event.time - events.video[lastSeekingIdx].time;
  21672. }
  21673. trimEventHistory();
  21674. }
  21675. function handleVolumeEvent() {
  21676. localStorage.setItem(STORAGE_KEYS.volume, JSON.stringify({
  21677. muted: video.muted,
  21678. volume: video.volume
  21679. }));
  21680. }
  21681. function handleMediaError() {
  21682. if (autoRecoverError) {
  21683. var now = self.performance.now();
  21684. if (!self.recoverDecodingErrorDate || now - self.recoverDecodingErrorDate > 3000) {
  21685. self.recoverDecodingErrorDate = self.performance.now();
  21686. $('#statusOut').append(', trying to recover media error.');
  21687. hls.recoverMediaError();
  21688. } else {
  21689. if (!self.recoverSwapAudioCodecDate || now - self.recoverSwapAudioCodecDate > 3000) {
  21690. self.recoverSwapAudioCodecDate = self.performance.now();
  21691. $('#statusOut').append(', trying to swap audio codec and recover media error.');
  21692. hls.swapAudioCodec();
  21693. hls.recoverMediaError();
  21694. } else {
  21695. $('#statusOut').append(', cannot recover. Last media error recovery failed.');
  21696. }
  21697. }
  21698. }
  21699. }
  21700. function timeRangesToString(r) {
  21701. var log = '';
  21702. for (var i = 0; i < r.length; i++) {
  21703. log += '[' + r.start(i) + ', ' + r.end(i) + ']';
  21704. log += ' ';
  21705. }
  21706. return log;
  21707. }
  21708. function checkBuffer() {
  21709. var canvas = document.querySelector('#bufferedCanvas');
  21710. var ctx = canvas.getContext('2d');
  21711. var r = video.buffered;
  21712. var seekableEnd = getSeekableEnd();
  21713. var bufferingDuration;
  21714. if (r) {
  21715. ctx.fillStyle = 'black';
  21716. if (!canvas.width || canvas.width !== video.clientWidth) {
  21717. canvas.width = video.clientWidth;
  21718. }
  21719. ctx.fillRect(0, 0, canvas.width, canvas.height);
  21720. var pos = video.currentTime;
  21721. var bufferLen = 0;
  21722. ctx.fillStyle = 'gray';
  21723. for (var i = 0; i < r.length; i++) {
  21724. var start = r.start(i) / seekableEnd * canvas.width;
  21725. var end = r.end(i) / seekableEnd * canvas.width;
  21726. ctx.fillRect(start, 2, Math.max(2, end - start), 11);
  21727. if (pos >= r.start(i) && pos < r.end(i)) {
  21728. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  21729. bufferLen = r.end(i) - pos;
  21730. }
  21731. }
  21732. // check if we are in buffering / or playback ended state
  21733. if (bufferLen <= 0.1 && video.paused === false && pos - lastStartPosition > 0.5) {
  21734. if (lastDuration - pos <= 0.5 && events.isLive === false) ; else {
  21735. // we are not at the end of the playlist ... real buffering
  21736. if (bufferingIdx !== -1) {
  21737. bufferingDuration = self.performance.now() - events.t0 - events.video[bufferingIdx].time;
  21738. events.video[bufferingIdx].duration = bufferingDuration;
  21739. events.video[bufferingIdx].name = bufferingDuration;
  21740. } else {
  21741. events.video.push({
  21742. type: 'buffering',
  21743. time: self.performance.now() - events.t0
  21744. });
  21745. trimEventHistory();
  21746. // we are in buffering state
  21747. bufferingIdx = events.video.length - 1;
  21748. }
  21749. }
  21750. }
  21751. if (bufferLen > 0.1 && bufferingIdx !== -1) {
  21752. bufferingDuration = self.performance.now() - events.t0 - events.video[bufferingIdx].time;
  21753. events.video[bufferingIdx].duration = bufferingDuration;
  21754. events.video[bufferingIdx].name = bufferingDuration;
  21755. // we are out of buffering state
  21756. bufferingIdx = -1;
  21757. }
  21758. // update buffer/position for current Time
  21759. var event = {
  21760. time: self.performance.now() - events.t0,
  21761. buffer: Math.round(bufferLen * 1000),
  21762. pos: Math.round(pos * 1000)
  21763. };
  21764. var bufEvents = events.buffer;
  21765. var bufEventLen = bufEvents.length;
  21766. if (bufEventLen > 1) {
  21767. var event0 = bufEvents[bufEventLen - 2];
  21768. var event1 = bufEvents[bufEventLen - 1];
  21769. var slopeBuf0 = (event0.buffer - event1.buffer) / (event0.time - event1.time);
  21770. var slopeBuf1 = (event1.buffer - event.buffer) / (event1.time - event.time);
  21771. var slopePos0 = (event0.pos - event1.pos) / (event0.time - event1.time);
  21772. var slopePos1 = (event1.pos - event.pos) / (event1.time - event.time);
  21773. // compute slopes. if less than 30% difference, remove event1
  21774. if ((slopeBuf0 === slopeBuf1 || Math.abs(slopeBuf0 / slopeBuf1 - 1) <= 0.3) && (slopePos0 === slopePos1 || Math.abs(slopePos0 / slopePos1 - 1) <= 0.3)) {
  21775. bufEvents.pop();
  21776. }
  21777. }
  21778. events.buffer.push(event);
  21779. trimEventHistory();
  21780. self.refreshCanvas();
  21781. if ($('#statsDisplayTab').is(':visible')) {
  21782. var log = "Duration: " + video.duration + "\nBuffered: " + timeRangesToString(video.buffered) + "\nSeekable: " + timeRangesToString(video.seekable) + "\nPlayed: " + timeRangesToString(video.played) + "\n";
  21783. if (hls.media) {
  21784. for (var type in tracks) {
  21785. log += "Buffer for " + type + " contains:" + timeRangesToString(tracks[type].buffer.buffered) + "\n";
  21786. }
  21787. var videoPlaybackQuality = video.getVideoPlaybackQuality;
  21788. if (videoPlaybackQuality && typeof videoPlaybackQuality === typeof Function) {
  21789. log += "Dropped frames: " + video.getVideoPlaybackQuality().droppedVideoFrames + "\n";
  21790. log += "Corrupted frames: " + video.getVideoPlaybackQuality().corruptedVideoFrames + "\n";
  21791. } else if (video.webkitDroppedFrameCount) {
  21792. log += "Dropped frames: " + video.webkitDroppedFrameCount + "\n";
  21793. }
  21794. }
  21795. log += "TTFB Estimate: " + hls.ttfbEstimate.toFixed(3) + "\n";
  21796. log += "Bandwidth Estimate: " + hls.bandwidthEstimate.toFixed(3) + "\n";
  21797. if (events.isLive) {
  21798. log += 'Live Stats:\n' + (" Max Latency: " + hls.maxLatency + "\n") + (" Target Latency: " + hls.targetLatency.toFixed(3) + "\n") + (" Latency: " + hls.latency.toFixed(3) + "\n") + (" Drift: " + hls.drift.toFixed(3) + " (edge advance rate)\n") + (" Edge Stall: " + hls.latencyController.edgeStalled.toFixed(3) + " (playlist refresh over target duration/part)\n") + (" Playback rate: " + video.playbackRate.toFixed(2) + "\n");
  21799. if (stats.fragProgramDateTime) {
  21800. var currentPDT = stats.fragProgramDateTime + (video.currentTime - stats.fragStart) * 1000;
  21801. log += " Program Date Time: " + new Date(currentPDT).toISOString();
  21802. var pdtLatency = (Date.now() - currentPDT) / 1000;
  21803. if (pdtLatency > 0) {
  21804. log += " (" + pdtLatency.toFixed(3) + " seconds ago)";
  21805. }
  21806. }
  21807. }
  21808. $('#bufferedOut').text(log);
  21809. $('#statisticsOut').text(JSON.stringify(sortObject(stats), null, '\t'));
  21810. }
  21811. ctx.fillStyle = 'blue';
  21812. var x = video.currentTime / seekableEnd * canvas.width;
  21813. ctx.fillRect(x, 0, 2, 15);
  21814. } else if (ctx.fillStyle !== 'black') {
  21815. ctx.fillStyle = 'black';
  21816. ctx.fillRect(0, 0, canvas.width, canvas.height);
  21817. }
  21818. }
  21819. function showCanvas() {
  21820. self.showMetrics();
  21821. $('#bufferedOut').show();
  21822. $('#bufferedCanvas').show();
  21823. }
  21824. function hideCanvas() {
  21825. self.hideMetrics();
  21826. $('#bufferedOut').hide();
  21827. $('#bufferedCanvas').hide();
  21828. }
  21829. function getMetrics() {
  21830. var json = JSON.stringify(events);
  21831. var jsonpacked = main.pack(json);
  21832. // console.log('packing JSON from ' + json.length + ' to ' + jsonpacked.length + ' bytes');
  21833. return btoa(jsonpacked);
  21834. }
  21835. self.copyMetricsToClipBoard = function () {
  21836. copyTextToClipboard(getMetrics());
  21837. };
  21838. self.goToMetrics = function () {
  21839. var url = document.URL;
  21840. url = url.slice(0, url.lastIndexOf('/') + 1) + 'metrics.html';
  21841. self.open(url, '_blank');
  21842. };
  21843. function goToMetricsPermaLink() {
  21844. var url = document.URL;
  21845. var b64 = getMetrics();
  21846. url = url.slice(0, url.lastIndexOf('/') + 1) + 'metrics.html#data=' + b64;
  21847. self.open(url, '_blank');
  21848. }
  21849. function onClickBufferedRange(event) {
  21850. var canvas = document.querySelector('#bufferedCanvas');
  21851. var target = (event.clientX - canvas.offsetLeft) / canvas.width * getSeekableEnd();
  21852. video.currentTime = target;
  21853. }
  21854. function getSeekableEnd() {
  21855. if (isFinite(video.duration)) {
  21856. return video.duration;
  21857. }
  21858. if (video.seekable.length) {
  21859. return video.seekable.end(video.seekable.length - 1);
  21860. }
  21861. return 0;
  21862. }
  21863. function getLevelButtonHtml(key, levels, onclickReplace, autoEnabled) {
  21864. var onclickAuto = (key + "=-1").replace(/^(\w+)=([^=]+)$/, onclickReplace);
  21865. var codecs = levels.reduce(function (uniqueCodecs, level) {
  21866. var levelCodecs = codecs2label(level.attrs.CODECS);
  21867. if (levelCodecs && uniqueCodecs.indexOf(levelCodecs) === -1) {
  21868. uniqueCodecs.push(levelCodecs);
  21869. }
  21870. return uniqueCodecs;
  21871. }, []);
  21872. return "<button type=\"button\" class=\"btn btn-sm " + (autoEnabled ? 'btn-primary' : 'btn-success') + "\" onclick=\"" + onclickAuto + "\">auto</button>" + levels.map(function (level, i) {
  21873. var enabled = hls[key] === i;
  21874. var onclick = (key + "=" + i).replace(/^(\w+)=(\w+)$/, onclickReplace);
  21875. var label = level2label(levels[i], i, codecs);
  21876. return "<button type=\"button\" class=\"btn btn-sm " + (enabled ? 'btn-primary' : 'btn-success') + "\" onclick=\"" + onclick + "\">" + label + "</button>";
  21877. }).join('');
  21878. }
  21879. function updateLevelInfo() {
  21880. var levels = hls.levels;
  21881. if (!levels) {
  21882. return;
  21883. }
  21884. var htmlCurrentLevel = getLevelButtonHtml('currentLevel', levels, 'hls.$1=$2', hls.autoLevelEnabled);
  21885. var htmlNextLevel = getLevelButtonHtml('nextLevel', levels, 'hls.$1=$2', hls.autoLevelEnabled);
  21886. var htmlLoadLevel = getLevelButtonHtml('loadLevel', levels, 'hls.$1=$2', hls.autoLevelEnabled);
  21887. var htmlCapLevel = getLevelButtonHtml('autoLevelCapping', levels, 'levelCapping=hls.$1=$2;updateLevelInfo();onDemoConfigChanged();', hls.autoLevelCapping === -1);
  21888. if ($('#currentLevelControl').html() !== htmlCurrentLevel) {
  21889. $('#currentLevelControl').html(htmlCurrentLevel);
  21890. }
  21891. if ($('#nextLevelControl').html() !== htmlNextLevel) {
  21892. $('#nextLevelControl').html(htmlNextLevel);
  21893. }
  21894. if ($('#loadLevelControl').html() !== htmlLoadLevel) {
  21895. $('#loadLevelControl').html(htmlLoadLevel);
  21896. }
  21897. if ($('#levelCappingControl').html() !== htmlCapLevel) {
  21898. $('#levelCappingControl').html(htmlCapLevel);
  21899. }
  21900. }
  21901. function updateAudioTrackInfo() {
  21902. var buttonTemplate = '<button type="button" class="btn btn-sm ';
  21903. var buttonEnabled = 'btn-primary" ';
  21904. var buttonDisabled = 'btn-success" ';
  21905. var html1 = '';
  21906. var audioTrackId = hls.audioTrack;
  21907. var len = hls.audioTracks.length;
  21908. var track = hls.audioTracks[audioTrackId];
  21909. for (var i = 0; i < len; i++) {
  21910. html1 += buttonTemplate;
  21911. if (audioTrackId === i) {
  21912. html1 += buttonEnabled;
  21913. } else {
  21914. html1 += buttonDisabled;
  21915. }
  21916. html1 += 'onclick="hls.audioTrack=' + i + '">' + hls.audioTracks[i].name + '</button>';
  21917. }
  21918. $('#audioTrackLabel').text(track ? track.lang || track.name : 'None selected');
  21919. $('#audioTrackControl').html(html1);
  21920. }
  21921. function codecs2label(levelCodecs) {
  21922. if (levelCodecs) {
  21923. return levelCodecs.replace(/([ah]vc.)[^,;]+/, '$1').replace('mp4a.40.2', 'mp4a');
  21924. }
  21925. return '';
  21926. }
  21927. function level2label(level, i, manifestCodecs) {
  21928. var levelCodecs = codecs2label(level.attrs.CODECS);
  21929. var levelNameInfo = level.name ? "\"" + level.name + "\": " : '';
  21930. var codecInfo = levelCodecs && manifestCodecs.length > 1 ? " / " + levelCodecs : '';
  21931. if (level.height) {
  21932. return i + " (" + levelNameInfo + level.height + "p / " + Math.round(level.bitrate / 1024) + "kb" + codecInfo + ")";
  21933. }
  21934. if (level.bitrate) {
  21935. return i + " (" + levelNameInfo + Math.round(level.bitrate / 1024) + "kb" + codecInfo + ")";
  21936. }
  21937. if (codecInfo) {
  21938. return i + " (" + levelNameInfo + levelCodecs + ")";
  21939. }
  21940. if (level.name) {
  21941. return i + " (" + level.name + ")";
  21942. }
  21943. return "" + i;
  21944. }
  21945. function getDemoConfigPropOrDefault(propName, defaultVal) {
  21946. return typeof demoConfig[propName] !== 'undefined' ? demoConfig[propName] : defaultVal;
  21947. }
  21948. function getURLParam(sParam, defaultValue) {
  21949. var sPageURL = self.location.search.substring(1);
  21950. var sURLVariables = sPageURL.split('&');
  21951. for (var i = 0; i < sURLVariables.length; i++) {
  21952. var sParameterName = sURLVariables[i].split('=');
  21953. if (sParameterName[0] === sParam) {
  21954. return sParameterName[1] === 'undefined' ? undefined : sParameterName[1] === 'false' ? false : sParameterName[1];
  21955. }
  21956. }
  21957. return defaultValue;
  21958. }
  21959. function onDemoConfigChanged(firstLoad) {
  21960. demoConfig = {
  21961. enableStreaming: enableStreaming,
  21962. autoRecoverError: autoRecoverError,
  21963. stopOnStall: stopOnStall,
  21964. dumpfMP4: dumpfMP4,
  21965. levelCapping: levelCapping,
  21966. limitMetrics: limitMetrics
  21967. };
  21968. if (configPersistenceEnabled) {
  21969. persistEditorValue();
  21970. }
  21971. var serializedDemoConfig = btoa(JSON.stringify(demoConfig));
  21972. var baseURL = document.URL.split('?')[0];
  21973. var streamURL = $('#streamURL').val();
  21974. var permalinkURL = baseURL + "?src=" + encodeURIComponent(streamURL) + "&demoConfig=" + serializedDemoConfig;
  21975. $('#StreamPermalink').html("<a href=\"" + permalinkURL + "\">" + permalinkURL + "</a>");
  21976. if (!firstLoad && self.location.href !== permalinkURL) {
  21977. self.history.pushState(null, null, permalinkURL);
  21978. }
  21979. }
  21980. function onConfigPersistenceChanged(event) {
  21981. configPersistenceEnabled = event.target.checked;
  21982. localStorage.setItem(STORAGE_KEYS.Editor_Persistence, JSON.stringify(configPersistenceEnabled));
  21983. if (configPersistenceEnabled) {
  21984. persistEditorValue();
  21985. } else {
  21986. localStorage.removeItem(STORAGE_KEYS.Hls_Config);
  21987. }
  21988. }
  21989. function getEditorValue(options) {
  21990. options = $.extend({
  21991. parse: false
  21992. }, options || {});
  21993. var value = configEditor.session.getValue();
  21994. if (options.parse) {
  21995. try {
  21996. value = JSON.parse(value);
  21997. } catch (e) {
  21998. console.warn('[getEditorValue] could not parse editor value', e);
  21999. value = {};
  22000. }
  22001. }
  22002. return value;
  22003. }
  22004. function getPersistedHlsConfig() {
  22005. var value = localStorage.getItem(STORAGE_KEYS.Hls_Config);
  22006. if (value === null) {
  22007. return value;
  22008. }
  22009. try {
  22010. value = JSON.parse(value);
  22011. } catch (e) {
  22012. console.warn('[getPersistedHlsConfig] could not hls config json', e);
  22013. value = {};
  22014. }
  22015. return value;
  22016. }
  22017. function persistEditorValue() {
  22018. localStorage.setItem(STORAGE_KEYS.Hls_Config, getEditorValue());
  22019. }
  22020. function setupConfigEditor() {
  22021. configEditor = self.ace.edit('config-editor');
  22022. configEditor.setTheme('ace/theme/github');
  22023. configEditor.session.setMode('ace/mode/json');
  22024. var contents = hlsjsDefaults;
  22025. var shouldRestorePersisted = JSON.parse(localStorage.getItem(STORAGE_KEYS.Editor_Persistence)) === true;
  22026. if (shouldRestorePersisted) {
  22027. $.extend(contents, getPersistedHlsConfig());
  22028. }
  22029. var elPersistence = document.querySelector('#config-persistence');
  22030. elPersistence.addEventListener('change', onConfigPersistenceChanged);
  22031. elPersistence.checked = shouldRestorePersisted;
  22032. configPersistenceEnabled = shouldRestorePersisted;
  22033. updateConfigEditorValue(contents);
  22034. }
  22035. function setupTimelineChart() {
  22036. var canvas = document.querySelector('#timeline-chart');
  22037. var chart = new TimelineChart(canvas, {
  22038. responsive: false
  22039. });
  22040. resizeHandlers.push(function () {
  22041. chart.resize();
  22042. });
  22043. chart.resize();
  22044. return chart;
  22045. }
  22046. function addChartEventListeners(hls) {
  22047. var updateLevelOrTrack = function updateLevelOrTrack(eventName, data) {
  22048. chart.updateLevelOrTrack(data.details);
  22049. };
  22050. var updateFragment = function updateFragment(eventName, data) {
  22051. if (data.stats) {
  22052. // Convert 0.x stats to partial v1 stats
  22053. var _data$stats = data.stats,
  22054. retry = _data$stats.retry,
  22055. loaded = _data$stats.loaded,
  22056. total = _data$stats.total,
  22057. trequest = _data$stats.trequest,
  22058. tfirst = _data$stats.tfirst,
  22059. tload = _data$stats.tload;
  22060. if (trequest && tload) {
  22061. data.frag.stats = {
  22062. loaded: loaded,
  22063. retry: retry,
  22064. total: total,
  22065. loading: {
  22066. start: trequest,
  22067. first: tfirst,
  22068. end: tload
  22069. }
  22070. };
  22071. }
  22072. }
  22073. chart.updateFragment(data);
  22074. };
  22075. var updateChart = function updateChart() {
  22076. chart.update();
  22077. };
  22078. hls.on(Hls.Events.MANIFEST_LOADING, function () {
  22079. chart.reset();
  22080. }, chart);
  22081. hls.on(Hls.Events.MANIFEST_PARSED, function (eventName, data) {
  22082. var levels = data.levels;
  22083. chart.removeType('level');
  22084. chart.removeType('audioTrack');
  22085. chart.removeType('subtitleTrack');
  22086. chart.updateLevels(levels);
  22087. }, chart);
  22088. hls.on(Hls.Events.BUFFER_CREATED, function (eventName, _ref) {
  22089. var tracks = _ref.tracks;
  22090. chart.updateSourceBuffers(tracks, hls.media);
  22091. }, chart);
  22092. hls.on(Hls.Events.BUFFER_RESET, function () {
  22093. chart.removeSourceBuffers();
  22094. }, chart);
  22095. hls.on(Hls.Events.LEVELS_UPDATED, function (eventName, _ref2) {
  22096. var levels = _ref2.levels;
  22097. chart.removeType('level');
  22098. chart.updateLevels(levels);
  22099. });
  22100. hls.on(Hls.Events.LEVEL_SWITCHED, function (eventName, _ref3) {
  22101. var level = _ref3.level;
  22102. chart.removeType('level');
  22103. chart.updateLevels(hls.levels, level);
  22104. }, chart);
  22105. hls.on(Hls.Events.LEVEL_LOADING, function () {
  22106. // TODO: mutate level datasets
  22107. // Update loadLevel
  22108. chart.removeType('level');
  22109. chart.updateLevels(hls.levels);
  22110. }, chart);
  22111. hls.on(Hls.Events.LEVEL_UPDATED, function (eventName, _ref4) {
  22112. var details = _ref4.details;
  22113. chart.updateLevelOrTrack(details);
  22114. }, chart);
  22115. hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, function (eventName, _ref5) {
  22116. var audioTracks = _ref5.audioTracks;
  22117. chart.removeType('audioTrack');
  22118. chart.updateAudioTracks(audioTracks);
  22119. }, chart);
  22120. hls.on(Hls.Events.SUBTITLE_TRACKS_UPDATED, function (eventName, _ref6) {
  22121. var subtitleTracks = _ref6.subtitleTracks;
  22122. chart.removeType('subtitleTrack');
  22123. chart.updateSubtitleTracks(subtitleTracks);
  22124. }, chart);
  22125. hls.on(Hls.Events.AUDIO_TRACK_SWITCHED, function (eventName) {
  22126. // TODO: mutate level datasets
  22127. chart.removeType('audioTrack');
  22128. chart.updateAudioTracks(hls.audioTracks);
  22129. }, chart);
  22130. hls.on(Hls.Events.SUBTITLE_TRACK_SWITCH, function (eventName) {
  22131. // TODO: mutate level datasets
  22132. chart.removeType('subtitleTrack');
  22133. chart.updateSubtitleTracks(hls.subtitleTracks);
  22134. }, chart);
  22135. hls.on(Hls.Events.AUDIO_TRACK_LOADED, updateLevelOrTrack, chart);
  22136. hls.on(Hls.Events.SUBTITLE_TRACK_LOADED, updateLevelOrTrack, chart);
  22137. hls.on(Hls.Events.LEVEL_PTS_UPDATED, updateLevelOrTrack, chart);
  22138. hls.on(Hls.Events.FRAG_LOADED, updateFragment, chart);
  22139. hls.on(Hls.Events.FRAG_PARSED, updateFragment, chart);
  22140. hls.on(Hls.Events.FRAG_CHANGED, updateFragment, chart);
  22141. hls.on(Hls.Events.BUFFER_APPENDING, updateChart, chart);
  22142. hls.on(Hls.Events.BUFFER_APPENDED, updateChart, chart);
  22143. hls.on(Hls.Events.BUFFER_FLUSHED, updateChart, chart);
  22144. }
  22145. function updateConfigEditorValue(obj) {
  22146. var json = JSON.stringify(obj, null, 2);
  22147. configEditor.session.setValue(json);
  22148. }
  22149. function applyConfigEditorValue() {
  22150. onDemoConfigChanged();
  22151. loadSelectedStream();
  22152. }
  22153. function createfMP4(type) {
  22154. if (fmp4Data[type].length) {
  22155. var blob = new Blob([arrayConcat(fmp4Data[type])], {
  22156. type: 'application/octet-stream'
  22157. });
  22158. var filename = type + '-' + new Date().toISOString() + '.mp4';
  22159. self.saveAs(blob, filename);
  22160. // $('body').append('<a download="hlsjs-' + filename + '" href="' + self.URL.createObjectURL(blob) + '">Download ' + filename + ' track</a><br>');
  22161. } else if (!dumpfMP4) {
  22162. console.error('Check "Dump transmuxed fMP4 data" first to make appended media available for saving.');
  22163. }
  22164. }
  22165. function arrayConcat(inputArray) {
  22166. var totalLength = inputArray.reduce(function (prev, cur) {
  22167. return prev + cur.length;
  22168. }, 0);
  22169. var result = new Uint8Array(totalLength);
  22170. var offset = 0;
  22171. inputArray.forEach(function (element) {
  22172. result.set(element, offset);
  22173. offset += element.length;
  22174. });
  22175. return result;
  22176. }
  22177. function hideAllTabs() {
  22178. $('.demo-tab-btn').css('background-color', '');
  22179. $('.demo-tab').hide();
  22180. }
  22181. function toggleTabClick(btn) {
  22182. toggleTab(btn);
  22183. var tabIndexes = $('.demo-tab-btn').toArray().map(function (el, i) {
  22184. return $('#' + $(el).data('tab')).is(':visible') ? i : null;
  22185. }).filter(function (i) {
  22186. return i !== null;
  22187. });
  22188. localStorage.setItem(STORAGE_KEYS.demo_tabs, tabIndexes.join(','));
  22189. }
  22190. function toggleTab(btn, dontHideOpenTabs) {
  22191. var tabElId = $(btn).data('tab');
  22192. // eslint-disable-next-line no-restricted-globals
  22193. var modifierPressed = dontHideOpenTabs || self.event && (self.event.metaKey || self.event.shiftKey);
  22194. if (!modifierPressed) {
  22195. hideAllTabs();
  22196. }
  22197. if (modifierPressed) {
  22198. $("#" + tabElId).toggle();
  22199. } else {
  22200. $("#" + tabElId).show();
  22201. }
  22202. $(btn).css('background-color', $("#" + tabElId).is(':visible') ? 'orange' : '');
  22203. if (!$('#statsDisplayTab').is(':visible')) {
  22204. self.hideMetrics();
  22205. }
  22206. if (hls) {
  22207. if ($('#timelineTab').is(':visible')) {
  22208. chart.show();
  22209. chart.resize(chart.chart.data ? chart.chart.data.datasets : null);
  22210. } else {
  22211. chart.hide();
  22212. }
  22213. }
  22214. }
  22215. function appendLog(textElId, message) {
  22216. var el = $('#' + textElId);
  22217. var logText = el.text();
  22218. if (logText.length) {
  22219. logText += '\n';
  22220. }
  22221. var timestamp = (Date.now() - startTime) / 1000;
  22222. var newMessage = timestamp + ' | ' + message;
  22223. logText += newMessage;
  22224. // update
  22225. el.text(logText);
  22226. var element = el[0];
  22227. element.scrollTop = element.scrollHeight - element.clientHeight;
  22228. }
  22229. function logStatus(message) {
  22230. appendLog('statusOut', message);
  22231. }
  22232. function logError(message) {
  22233. appendLog('errorOut', message);
  22234. }
  22235. }));
  22236. //# sourceMappingURL=hls-demo.js.map