hls-demo.js 766 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624
  1. (function (factory) {
  2. typeof define === 'function' && define.amd ? define(factory) :
  3. factory();
  4. })((function () { 'use strict';
  5. function getDefaultExportFromCjs (x) {
  6. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  7. }
  8. /**
  9. * Create test stream
  10. * @param {string} url
  11. * @param {string} description
  12. * @param {boolean} [live]
  13. * @param {boolean} [abr]
  14. * @param {string[]} [skip_ua]
  15. * @returns {{url: string, description: string, live: boolean, abr: boolean, skip_ua: string[]}}
  16. */
  17. var testStreams$1;
  18. var hasRequiredTestStreams;
  19. function requireTestStreams() {
  20. if (hasRequiredTestStreams) return testStreams$1;
  21. hasRequiredTestStreams = 1;
  22. function createTestStream(url, description, live, abr, skip_ua) {
  23. if (live === void 0) {
  24. live = false;
  25. }
  26. if (abr === void 0) {
  27. abr = true;
  28. }
  29. if (skip_ua === void 0) {
  30. skip_ua = [];
  31. }
  32. return {
  33. url: url,
  34. description: description,
  35. live: live,
  36. abr: abr,
  37. skip_ua: skip_ua
  38. };
  39. }
  40. /**
  41. * @param {Object} target
  42. * @param {Object} [config]
  43. * @returns {{url: string, description: string, live: boolean, abr: boolean, skip_ua: string[]}}
  44. */
  45. function createTestStreamWithConfig(target, config) {
  46. if (typeof target !== 'object') {
  47. throw new Error('target should be object');
  48. }
  49. var testStream = createTestStream(target.url, target.description, target.live, target.abr, target.skip_ua);
  50. testStream.config = config;
  51. return testStream;
  52. }
  53. testStreams$1 = {
  54. bbb: {
  55. url: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
  56. description: 'Big Buck Bunny - adaptive qualities',
  57. abr: true
  58. },
  59. fdr: {
  60. url: 'https://cdn.jwplayer.com/manifests/pZxWPRg4.m3u8',
  61. description: 'FDR - CDN packaged, 4s segments, 180p - 1080p',
  62. abr: true
  63. },
  64. bigBuckBunny480p: {
  65. url: 'https://test-streams.mux.dev/x36xhzz/url_6/193039199_mp4_h264_aac_hq_7.m3u8',
  66. description: 'Big Buck Bunny - 480p only',
  67. abr: false
  68. },
  69. arte: {
  70. url: 'https://test-streams.mux.dev/test_001/stream.m3u8',
  71. description: 'ARTE China,ABR',
  72. abr: true
  73. },
  74. deltatreDAI: {
  75. url: 'https://test-streams.mux.dev/dai-discontinuity-deltatre/manifest.m3u8',
  76. description: 'Ad-insertion in event stream',
  77. abr: false
  78. },
  79. issue666: {
  80. url: 'https://playertest.longtailvideo.com/adaptive/issue666/playlists/cisq0gim60007xzvi505emlxx.m3u8',
  81. description: 'Surveillance footage - https://github.com/video-dev/hls.js/issues/666',
  82. abr: false
  83. },
  84. closedCaptions: {
  85. url: 'https://playertest.longtailvideo.com/adaptive/captions/playlist.m3u8',
  86. description: 'CNN special report, with CC',
  87. abr: false
  88. },
  89. customIvBadDts: {
  90. url: 'https://playertest.longtailvideo.com/adaptive/customIV/prog_index.m3u8',
  91. description: 'Custom IV with bad PTS DTS',
  92. abr: false
  93. },
  94. oceansAES: {
  95. url: 'https://playertest.longtailvideo.com/adaptive/oceans_aes/oceans_aes.m3u8',
  96. description: 'AES-128 encrypted, ABR',
  97. abr: true
  98. },
  99. tracksWithAES: {
  100. url: 'https://playertest.longtailvideo.com/adaptive/aes-with-tracks/master.m3u8',
  101. description: 'AES-128 encrypted, TS main with AAC audio track',
  102. abr: false
  103. },
  104. mp3Audio: {
  105. url: 'https://playertest.longtailvideo.com/adaptive/vod-with-mp3/manifest.m3u8',
  106. description: 'MP3 VOD demo',
  107. abr: false
  108. },
  109. mpegAudioOnly: {
  110. url: 'https://pl.streamingvideoprovider.com/mp3-playlist/playlist.m3u8',
  111. description: 'MPEG Audio Only demo',
  112. abr: false,
  113. skip_ua: ['MicrosoftEdge', 'firefox']
  114. },
  115. fmp4: {
  116. url: 'https://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8',
  117. description: 'HLS fMP4 Angel-One multiple audio-tracks',
  118. abr: true
  119. },
  120. fmp4Bitmovin: {
  121. url: 'https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s-fmp4/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8',
  122. description: 'HLS fMP4 by Bitmovin',
  123. abr: true
  124. },
  125. fmp4BitmovinHevc: {
  126. url: 'https://bitmovin-a.akamaihd.net/content/dataset/multi-codec/hevc/stream_fmp4.m3u8',
  127. description: 'HLS HEVC fMP4 by Bitmovin (Safari and Edge? only as of 2020-08)',
  128. abr: true,
  129. skipFunctionalTests: true
  130. },
  131. offset_pts: {
  132. url: 'https://test-streams.mux.dev/pts_shift/master.m3u8',
  133. description: 'DK Turntable, PTS shifted by 2.3s',
  134. abr: true
  135. },
  136. angelOneShakaWidevine: createTestStreamWithConfig({
  137. url: 'https://storage.googleapis.com/shaka-demo-assets/angel-one-widevine-hls/hls.m3u8',
  138. description: 'Shaka-packager Widevine DRM (EME) HLS-fMP4 - Angel One Demo',
  139. abr: true,
  140. skip_ua: ['firefox', 'safari', {
  141. name: 'chrome',
  142. version: '75.0'
  143. }, {
  144. name: 'chrome',
  145. version: '79.0'
  146. }]
  147. }, {
  148. widevineLicenseUrl: 'https://cwip-shaka-proxy.appspot.com/no_auth',
  149. emeEnabled: true
  150. }),
  151. audioOnlyMultipleLevels: {
  152. url: 'https://s3.amazonaws.com/qa.jwplayer.com/~alex/121628/new_master.m3u8',
  153. description: 'Multiple non-alternate audio levels',
  154. abr: true
  155. },
  156. pdtDuplicate: {
  157. url: 'https://playertest.longtailvideo.com/adaptive/artbeats/manifest.m3u8',
  158. description: 'Duplicate sequential PDT values',
  159. abr: false
  160. },
  161. pdtLargeGap: createTestStreamWithConfig({
  162. url: 'https://playertest.longtailvideo.com/adaptive/boxee/playlist.m3u8',
  163. description: 'PDTs with large gaps following discontinuities',
  164. abr: false
  165. }, {
  166. // gaps are introduced by missing audio samples in the TS segments
  167. // silent audio insertion can only prepend missing back to the last appended time provided there is room
  168. // The discontinuities and starting offset of the timestamps do not allow prepending earlier than the start of the disco
  169. allowedBufferedRangesInSeekTest: 7,
  170. // Ignore "should buffer up to maxBufferLength" result
  171. avBufferOffset: 39
  172. }),
  173. pdtBadValues: {
  174. url: 'https://playertest.longtailvideo.com/adaptive/progdatime/playlist2.m3u8',
  175. description: 'PDTs with bad values',
  176. abr: false
  177. },
  178. pdtOneValue: {
  179. url: 'https://playertest.longtailvideo.com/adaptive/aviion/manifest.m3u8',
  180. description: 'One PDT, no discontinuities',
  181. abr: false
  182. },
  183. noTrackIntersection: createTestStreamWithConfig({
  184. url: 'https://s3.amazonaws.com/qa.jwplayer.com/~alex/123633/new_master.m3u8',
  185. description: 'Audio/video track PTS values do not intersect; 10 second start gap',
  186. abr: false
  187. }, {
  188. avBufferOffset: 10.5
  189. }),
  190. altAudioAndTracks: {
  191. // url: 'https://wowzaec2demo.streamlock.net/vod-multitrack/_definst_/smil:ElephantsDream/elephantsdream2.smil/playlist.m3u',
  192. url: 'https://playertest.longtailvideo.com/adaptive/elephants_dream_v4/index.m3u8',
  193. description: 'Alternate audio tracks, and multiple VTT tracks',
  194. vendor: 'wowza',
  195. abr: true
  196. },
  197. altAudioAudioOnly: createTestStreamWithConfig({
  198. url: 'https://playertest.longtailvideo.com/adaptive/alt-audio-no-video/sintel/playlist.m3u8',
  199. description: 'Audio only with alternate audio track (Sintel)',
  200. abr: false
  201. }, {
  202. // the playlist segment durations are longer than the media. So much so, that when seeking near the end,
  203. // the timeline shifts roughly 10 seconds seconds back, and as a result buffering skips several segments
  204. // to adjust for the currentTime now being places at the very end of the stream.
  205. allowedBufferedRangesInSeekTest: 3
  206. }),
  207. altAudioMultiAudioOnly: {
  208. url: 'https://playertest.longtailvideo.com/adaptive/alt-audio-no-video/angel-one.m3u8',
  209. description: 'Audio only with multiple alternate audio tracks (Angel One)',
  210. abr: false
  211. },
  212. muxedFmp4: {
  213. url: 'https://s3.amazonaws.com/qa.jwplayer.com/hlsjs/muxed-fmp4/hls.m3u8',
  214. description: 'Muxed av fmp4 - appended to "audiovideo" SourceBuffer',
  215. abr: false
  216. },
  217. altAudioWithPdtAndStartGap: {
  218. url: 'https://playertest.longtailvideo.com/adaptive/hls-test-streams/test-audio-pdt/playlist.m3u8',
  219. description: 'PDT before each segment, 1.59s start gap',
  220. // 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).
  221. // abr: true,
  222. startSeek: true
  223. },
  224. AppleAdvancedHevcAvcHls: {
  225. url: 'https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/master.m3u8',
  226. description: 'Advanced stream (HEVC/H.264, AC-3/AAC, WebVTT, fMP4 segments)'
  227. },
  228. MuxLowLatencyHls: {
  229. url: 'https://stream.mux.com/v69RSHhFelSm4701snP22dYz2jICy4E4FUyk02rW4gxRM.m3u8',
  230. description: 'Low-Latency HLS sample of Big Buck Bunny loop and a timer. Restarts every 12 hours. (fMP4 segments)',
  231. live: true
  232. },
  233. // AppleLowLatencyHls: {
  234. // url: 'https://ll-hls-test.apple.com/master.m3u8',
  235. // description: 'Apple Low-Latency HLS sample (TS segments)',
  236. // live: true,
  237. // },
  238. // AppleLowLatencyCmafHls: {
  239. // url: 'https://ll-hls-test.apple.com/cmaf/master.m3u8',
  240. // description: 'Apple Low-Latency HLS sample (fMP4 segments)',
  241. // live: true,
  242. // },
  243. groupIds: {
  244. url: 'https://mtoczko.github.io/hls-test-streams/test-group/playlist.m3u8',
  245. description: 'Group-id: subtitle and audio',
  246. abr: true,
  247. skipFunctionalTests: true
  248. },
  249. redundantLevelsWithTrackGroups: {
  250. url: 'https://playertest.longtailvideo.com/adaptive/elephants_dream_v4/redundant.m3u8',
  251. description: 'Redundant levels with subtitle and audio track groups',
  252. abr: true,
  253. skipFunctionalTests: true
  254. },
  255. startDelimiterOverlappingBetweenPESPackets: {
  256. url: 'https://wistia.github.io/hlsjs-test-streams/assets/start-delimiter.m3u8',
  257. 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.",
  258. abr: false,
  259. skipFunctionalTests: true
  260. },
  261. aes256: {
  262. url: 'https://jvaryhlstests.blob.core.windows.net/hlstestdata/playlist_encrypted.m3u8',
  263. description: 'aes-256 and aes-256-ctr full segment encryption',
  264. abr: false
  265. },
  266. mpegTsHevcHls: {
  267. url: 'https://devoldemar.github.io/streams/hls/bipbop/hevc.m3u8',
  268. description: 'Advanced stream (HEVC Main 10, MPEG-TS segments)',
  269. skipFunctionalTests: true
  270. },
  271. mpegTsBitmovinHevc: {
  272. url: 'https://bitmovin-a.akamaihd.net/content/dataset/multi-codec/hevc/v720p_ts.m3u8',
  273. description: 'HLS M2TS by Bitmovin (HEVC Main, many NALUs overflowing PESes, video only)',
  274. abr: false,
  275. skipFunctionalTests: true
  276. }
  277. };
  278. return testStreams$1;
  279. }
  280. var main = {};
  281. /*
  282. Copyright (c) 2013, Rodrigo González, Sapienlab All Rights Reserved.
  283. Available via MIT LICENSE. See https://github.com/roro89/jsonpack/blob/master/LICENSE.md for details.
  284. */
  285. var hasRequiredMain;
  286. function requireMain () {
  287. if (hasRequiredMain) return main;
  288. hasRequiredMain = 1;
  289. (function (exports) {
  290. (function(define) {
  291. define([], function() {
  292. var TOKEN_TRUE = -1;
  293. var TOKEN_FALSE = -2;
  294. var TOKEN_NULL = -3;
  295. var TOKEN_EMPTY_STRING = -4;
  296. var TOKEN_UNDEFINED = -5;
  297. var pack = function(json, options) {
  298. // Canonizes the options
  299. options = options || {};
  300. // A shorthand for debugging
  301. var verbose = options.verbose || false;
  302. verbose && console.log('Normalize the JSON Object');
  303. // JSON as Javascript Object (Not string representation)
  304. json = typeof json === 'string' ? this.JSON.parse(json) : json;
  305. verbose && console.log('Creating a empty dictionary');
  306. // The dictionary
  307. var dictionary = {
  308. strings : [],
  309. integers : [],
  310. floats : []
  311. };
  312. verbose && console.log('Creating the AST');
  313. // The AST
  314. var ast = (function recursiveAstBuilder(item) {
  315. verbose && console.log('Calling recursiveAstBuilder with ' + this.JSON.stringify(item));
  316. // The type of the item
  317. var type = typeof item;
  318. // Case 7: The item is null
  319. if (item === null) {
  320. return {
  321. type : 'null',
  322. index : TOKEN_NULL
  323. };
  324. }
  325. //add undefined
  326. if (typeof item === 'undefined') {
  327. return {
  328. type : 'undefined',
  329. index : TOKEN_UNDEFINED
  330. };
  331. }
  332. // Case 1: The item is Array Object
  333. if ( item instanceof Array) {
  334. // Create a new sub-AST of type Array (@)
  335. var ast = ['@'];
  336. // Add each items
  337. for (var i in item) {
  338. if (!item.hasOwnProperty(i)) continue;
  339. ast.push(recursiveAstBuilder(item[i]));
  340. }
  341. // And return
  342. return ast;
  343. }
  344. // Case 2: The item is Object
  345. if (type === 'object') {
  346. // Create a new sub-AST of type Object ($)
  347. var ast = ['$'];
  348. // Add each items
  349. for (var key in item) {
  350. if (!item.hasOwnProperty(key))
  351. continue;
  352. ast.push(recursiveAstBuilder(key));
  353. ast.push(recursiveAstBuilder(item[key]));
  354. }
  355. // And return
  356. return ast;
  357. }
  358. // Case 3: The item empty string
  359. if (item === '') {
  360. return {
  361. type : 'empty',
  362. index : TOKEN_EMPTY_STRING
  363. };
  364. }
  365. // Case 4: The item is String
  366. if (type === 'string') {
  367. // The index of that word in the dictionary
  368. var index = _indexOf.call(dictionary.strings, item);
  369. // If not, add to the dictionary and actualize the index
  370. if (index == -1) {
  371. dictionary.strings.push(_encode(item));
  372. index = dictionary.strings.length - 1;
  373. }
  374. // Return the token
  375. return {
  376. type : 'strings',
  377. index : index
  378. };
  379. }
  380. // Case 5: The item is integer
  381. if (type === 'number' && item % 1 === 0) {
  382. // The index of that number in the dictionary
  383. var index = _indexOf.call(dictionary.integers, item);
  384. // If not, add to the dictionary and actualize the index
  385. if (index == -1) {
  386. dictionary.integers.push(_base10To36(item));
  387. index = dictionary.integers.length - 1;
  388. }
  389. // Return the token
  390. return {
  391. type : 'integers',
  392. index : index
  393. };
  394. }
  395. // Case 6: The item is float
  396. if (type === 'number') {
  397. // The index of that number in the dictionary
  398. var index = _indexOf.call(dictionary.floats, item);
  399. // If not, add to the dictionary and actualize the index
  400. if (index == -1) {
  401. // Float not use base 36
  402. dictionary.floats.push(item);
  403. index = dictionary.floats.length - 1;
  404. }
  405. // Return the token
  406. return {
  407. type : 'floats',
  408. index : index
  409. };
  410. }
  411. // Case 7: The item is boolean
  412. if (type === 'boolean') {
  413. return {
  414. type : 'boolean',
  415. index : item ? TOKEN_TRUE : TOKEN_FALSE
  416. };
  417. }
  418. // Default
  419. throw new Error('Unexpected argument of type ' + typeof (item));
  420. })(json);
  421. // A set of shorthands proxies for the length of the dictionaries
  422. var stringLength = dictionary.strings.length;
  423. var integerLength = dictionary.integers.length;
  424. dictionary.floats.length;
  425. verbose && console.log('Parsing the dictionary');
  426. // Create a raw dictionary
  427. var packed = dictionary.strings.join('|');
  428. packed += '^' + dictionary.integers.join('|');
  429. packed += '^' + dictionary.floats.join('|');
  430. verbose && console.log('Parsing the structure');
  431. // And add the structure
  432. packed += '^' + (function recursiveParser(item) {
  433. verbose && console.log('Calling a recursiveParser with ' + this.JSON.stringify(item));
  434. // If the item is Array, then is a object of
  435. // type [object Object] or [object Array]
  436. if ( item instanceof Array) {
  437. // The packed resulting
  438. var packed = item.shift();
  439. for (var i in item) {
  440. if (!item.hasOwnProperty(i))
  441. continue;
  442. packed += recursiveParser(item[i]) + '|';
  443. }
  444. return (packed[packed.length - 1] === '|' ? packed.slice(0, -1) : packed) + ']';
  445. }
  446. // A shorthand proxies
  447. var type = item.type, index = item.index;
  448. if (type === 'strings') {
  449. // Just return the base 36 of index
  450. return _base10To36(index);
  451. }
  452. if (type === 'integers') {
  453. // Return a base 36 of index plus stringLength offset
  454. return _base10To36(stringLength + index);
  455. }
  456. if (type === 'floats') {
  457. // Return a base 36 of index plus stringLength and integerLength offset
  458. return _base10To36(stringLength + integerLength + index);
  459. }
  460. if (type === 'boolean') {
  461. return item.index;
  462. }
  463. if (type === 'null') {
  464. return TOKEN_NULL;
  465. }
  466. if (type === 'undefined') {
  467. return TOKEN_UNDEFINED;
  468. }
  469. if (type === 'empty') {
  470. return TOKEN_EMPTY_STRING;
  471. }
  472. throw new TypeError('The item is alien!');
  473. })(ast);
  474. verbose && console.log('Ending parser');
  475. // If debug, return a internal representation of dictionary and stuff
  476. if (options.debug)
  477. return {
  478. dictionary : dictionary,
  479. ast : ast,
  480. packed : packed
  481. };
  482. return packed;
  483. };
  484. var unpack = function(packed, options) {
  485. // Canonizes the options
  486. options = options || {};
  487. // A raw buffer
  488. var rawBuffers = packed.split('^');
  489. // Create a dictionary
  490. options.verbose && console.log('Building dictionary');
  491. var dictionary = [];
  492. // Add the strings values
  493. var buffer = rawBuffers[0];
  494. if (buffer !== '') {
  495. buffer = buffer.split('|');
  496. options.verbose && console.log('Parse the strings dictionary');
  497. for (var i=0, n=buffer.length; i<n; i++){
  498. dictionary.push(_decode(buffer[i]));
  499. }
  500. }
  501. // Add the integers values
  502. buffer = rawBuffers[1];
  503. if (buffer !== '') {
  504. buffer = buffer.split('|');
  505. options.verbose && console.log('Parse the integers dictionary');
  506. for (var i=0, n=buffer.length; i<n; i++){
  507. dictionary.push(_base36To10(buffer[i]));
  508. }
  509. }
  510. // Add the floats values
  511. buffer = rawBuffers[2];
  512. if (buffer !== '') {
  513. buffer = buffer.split('|');
  514. options.verbose && console.log('Parse the floats dictionary');
  515. for (var i=0, n=buffer.length; i<n; i++){
  516. dictionary.push(parseFloat(buffer[i]));
  517. }
  518. }
  519. // Free memory
  520. buffer = null;
  521. options.verbose && console.log('Tokenizing the structure');
  522. // Tokenizer the structure
  523. var number36 = '';
  524. var tokens = [];
  525. var len=rawBuffers[3].length;
  526. for (var i = 0; i < len; i++) {
  527. var symbol = rawBuffers[3].charAt(i);
  528. if (symbol === '|' || symbol === '$' || symbol === '@' || symbol === ']') {
  529. if (number36) {
  530. tokens.push(_base36To10(number36));
  531. number36 = '';
  532. }
  533. symbol !== '|' && tokens.push(symbol);
  534. } else {
  535. number36 += symbol;
  536. }
  537. }
  538. // A shorthand proxy for tokens.length
  539. var tokensLength = tokens.length;
  540. // The index of the next token to read
  541. var tokensIndex = 0;
  542. options.verbose && console.log('Starting recursive parser');
  543. return (function recursiveUnpackerParser() {
  544. // Maybe '$' (object) or '@' (array)
  545. var type = tokens[tokensIndex++];
  546. options.verbose && console.log('Reading collection type ' + (type === '$' ? 'object' : 'Array'));
  547. // Parse an array
  548. if (type === '@') {
  549. var node = [];
  550. for (; tokensIndex < tokensLength; tokensIndex++) {
  551. var value = tokens[tokensIndex];
  552. options.verbose && console.log('Read ' + value + ' symbol');
  553. if (value === ']')
  554. return node;
  555. if (value === '@' || value === '$') {
  556. node.push(recursiveUnpackerParser());
  557. } else {
  558. switch(value) {
  559. case TOKEN_TRUE:
  560. node.push(true);
  561. break;
  562. case TOKEN_FALSE:
  563. node.push(false);
  564. break;
  565. case TOKEN_NULL:
  566. node.push(null);
  567. break;
  568. case TOKEN_UNDEFINED:
  569. node.push(undefined);
  570. break;
  571. case TOKEN_EMPTY_STRING:
  572. node.push('');
  573. break;
  574. default:
  575. node.push(dictionary[value]);
  576. }
  577. }
  578. }
  579. options.verbose && console.log('Parsed ' + this.JSON.stringify(node));
  580. return node;
  581. }
  582. // Parse a object
  583. if (type === '$') {
  584. var node = {};
  585. for (; tokensIndex < tokensLength; tokensIndex++) {
  586. var key = tokens[tokensIndex];
  587. if (key === ']')
  588. return node;
  589. if (key === TOKEN_EMPTY_STRING)
  590. key = '';
  591. else
  592. key = dictionary[key];
  593. var value = tokens[++tokensIndex];
  594. if (value === '@' || value === '$') {
  595. node[key] = recursiveUnpackerParser();
  596. } else {
  597. switch(value) {
  598. case TOKEN_TRUE:
  599. node[key] = true;
  600. break;
  601. case TOKEN_FALSE:
  602. node[key] = false;
  603. break;
  604. case TOKEN_NULL:
  605. node[key] = null;
  606. break;
  607. case TOKEN_UNDEFINED:
  608. node[key] = undefined;
  609. break;
  610. case TOKEN_EMPTY_STRING:
  611. node[key] = '';
  612. break;
  613. default:
  614. node[key] = dictionary[value];
  615. }
  616. }
  617. }
  618. options.verbose && console.log('Parsed ' + this.JSON.stringify(node));
  619. return node;
  620. }
  621. throw new TypeError('Bad token ' + type + ' isn\'t a type');
  622. })();
  623. };
  624. var _encode = function(str) {
  625. if ( typeof str !== 'string')
  626. return str;
  627. return str.replace(/[\+ \|\^\%]/g, function(a) {
  628. return ({
  629. ' ' : '+',
  630. '+' : '%2B',
  631. '|' : '%7C',
  632. '^' : '%5E',
  633. '%' : '%25'
  634. })[a]
  635. });
  636. };
  637. var _decode = function(str) {
  638. if ( typeof str !== 'string')
  639. return str;
  640. return str.replace(/\+|%2B|%7C|%5E|%25/g, function(a) {
  641. return ({
  642. '+' : ' ',
  643. '%2B' : '+',
  644. '%7C' : '|',
  645. '%5E' : '^',
  646. '%25' : '%'
  647. })[a]
  648. })
  649. };
  650. var _base10To36 = function(number) {
  651. return Number.prototype.toString.call(number, 36).toUpperCase();
  652. };
  653. var _base36To10 = function(number) {
  654. return parseInt(number, 36);
  655. };
  656. var _indexOf = Array.prototype.indexOf ||
  657. function(obj, start) {
  658. for (var i = (start || 0), j = this.length; i < j; i++) {
  659. if (this[i] === obj) {
  660. return i;
  661. }
  662. }
  663. return -1;
  664. };
  665. return {
  666. JSON : JSON,
  667. pack : pack,
  668. unpack : unpack
  669. };
  670. });
  671. })( function(deps, factory) {
  672. var jsonpack = factory();
  673. for (var key in jsonpack)
  674. exports[key] = jsonpack[key];
  675. } );
  676. } (main));
  677. return main;
  678. }
  679. var mainExports = requireMain();
  680. /**
  681. * @this {Promise}
  682. */
  683. function finallyConstructor(callback) {
  684. var constructor = this.constructor;
  685. return this.then(
  686. function(value) {
  687. // @ts-ignore
  688. return constructor.resolve(callback()).then(function() {
  689. return value;
  690. });
  691. },
  692. function(reason) {
  693. // @ts-ignore
  694. return constructor.resolve(callback()).then(function() {
  695. // @ts-ignore
  696. return constructor.reject(reason);
  697. });
  698. }
  699. );
  700. }
  701. function allSettled(arr) {
  702. var P = this;
  703. return new P(function(resolve, reject) {
  704. if (!(arr && typeof arr.length !== 'undefined')) {
  705. return reject(
  706. new TypeError(
  707. typeof arr +
  708. ' ' +
  709. arr +
  710. ' is not iterable(cannot read property Symbol(Symbol.iterator))'
  711. )
  712. );
  713. }
  714. var args = Array.prototype.slice.call(arr);
  715. if (args.length === 0) return resolve([]);
  716. var remaining = args.length;
  717. function res(i, val) {
  718. if (val && (typeof val === 'object' || typeof val === 'function')) {
  719. var then = val.then;
  720. if (typeof then === 'function') {
  721. then.call(
  722. val,
  723. function(val) {
  724. res(i, val);
  725. },
  726. function(e) {
  727. args[i] = { status: 'rejected', reason: e };
  728. if (--remaining === 0) {
  729. resolve(args);
  730. }
  731. }
  732. );
  733. return;
  734. }
  735. }
  736. args[i] = { status: 'fulfilled', value: val };
  737. if (--remaining === 0) {
  738. resolve(args);
  739. }
  740. }
  741. for (var i = 0; i < args.length; i++) {
  742. res(i, args[i]);
  743. }
  744. });
  745. }
  746. /**
  747. * @constructor
  748. */
  749. function AggregateError(errors, message) {
  750. (this.name = 'AggregateError'), (this.errors = errors);
  751. this.message = message || '';
  752. }
  753. AggregateError.prototype = Error.prototype;
  754. function any(arr) {
  755. var P = this;
  756. return new P(function(resolve, reject) {
  757. if (!(arr && typeof arr.length !== 'undefined')) {
  758. return reject(new TypeError('Promise.any accepts an array'));
  759. }
  760. var args = Array.prototype.slice.call(arr);
  761. if (args.length === 0) return reject();
  762. var rejectionReasons = [];
  763. for (var i = 0; i < args.length; i++) {
  764. try {
  765. P.resolve(args[i])
  766. .then(resolve)
  767. .catch(function(error) {
  768. rejectionReasons.push(error);
  769. if (rejectionReasons.length === args.length) {
  770. reject(
  771. new AggregateError(
  772. rejectionReasons,
  773. 'All promises were rejected'
  774. )
  775. );
  776. }
  777. });
  778. } catch (ex) {
  779. reject(ex);
  780. }
  781. }
  782. });
  783. }
  784. // Store setTimeout reference so promise-polyfill will be unaffected by
  785. // other code modifying setTimeout (like sinon.useFakeTimers())
  786. var setTimeoutFunc = setTimeout;
  787. function isArray(x) {
  788. return Boolean(x && typeof x.length !== 'undefined');
  789. }
  790. function noop() {}
  791. // Polyfill for Function.prototype.bind
  792. function bind(fn, thisArg) {
  793. return function() {
  794. fn.apply(thisArg, arguments);
  795. };
  796. }
  797. /**
  798. * @constructor
  799. * @param {Function} fn
  800. */
  801. function Promise$1(fn) {
  802. if (!(this instanceof Promise$1))
  803. throw new TypeError('Promises must be constructed via new');
  804. if (typeof fn !== 'function') throw new TypeError('not a function');
  805. /** @type {!number} */
  806. this._state = 0;
  807. /** @type {!boolean} */
  808. this._handled = false;
  809. /** @type {Promise|undefined} */
  810. this._value = undefined;
  811. /** @type {!Array<!Function>} */
  812. this._deferreds = [];
  813. doResolve(fn, this);
  814. }
  815. function handle(self, deferred) {
  816. while (self._state === 3) {
  817. self = self._value;
  818. }
  819. if (self._state === 0) {
  820. self._deferreds.push(deferred);
  821. return;
  822. }
  823. self._handled = true;
  824. Promise$1._immediateFn(function() {
  825. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  826. if (cb === null) {
  827. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  828. return;
  829. }
  830. var ret;
  831. try {
  832. ret = cb(self._value);
  833. } catch (e) {
  834. reject(deferred.promise, e);
  835. return;
  836. }
  837. resolve(deferred.promise, ret);
  838. });
  839. }
  840. function resolve(self, newValue) {
  841. try {
  842. // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  843. if (newValue === self)
  844. throw new TypeError('A promise cannot be resolved with itself.');
  845. if (
  846. newValue &&
  847. (typeof newValue === 'object' || typeof newValue === 'function')
  848. ) {
  849. var then = newValue.then;
  850. if (newValue instanceof Promise$1) {
  851. self._state = 3;
  852. self._value = newValue;
  853. finale(self);
  854. return;
  855. } else if (typeof then === 'function') {
  856. doResolve(bind(then, newValue), self);
  857. return;
  858. }
  859. }
  860. self._state = 1;
  861. self._value = newValue;
  862. finale(self);
  863. } catch (e) {
  864. reject(self, e);
  865. }
  866. }
  867. function reject(self, newValue) {
  868. self._state = 2;
  869. self._value = newValue;
  870. finale(self);
  871. }
  872. function finale(self) {
  873. if (self._state === 2 && self._deferreds.length === 0) {
  874. Promise$1._immediateFn(function() {
  875. if (!self._handled) {
  876. Promise$1._unhandledRejectionFn(self._value);
  877. }
  878. });
  879. }
  880. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  881. handle(self, self._deferreds[i]);
  882. }
  883. self._deferreds = null;
  884. }
  885. /**
  886. * @constructor
  887. */
  888. function Handler(onFulfilled, onRejected, promise) {
  889. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  890. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  891. this.promise = promise;
  892. }
  893. /**
  894. * Take a potentially misbehaving resolver function and make sure
  895. * onFulfilled and onRejected are only called once.
  896. *
  897. * Makes no guarantees about asynchrony.
  898. */
  899. function doResolve(fn, self) {
  900. var done = false;
  901. try {
  902. fn(
  903. function(value) {
  904. if (done) return;
  905. done = true;
  906. resolve(self, value);
  907. },
  908. function(reason) {
  909. if (done) return;
  910. done = true;
  911. reject(self, reason);
  912. }
  913. );
  914. } catch (ex) {
  915. if (done) return;
  916. done = true;
  917. reject(self, ex);
  918. }
  919. }
  920. Promise$1.prototype['catch'] = function(onRejected) {
  921. return this.then(null, onRejected);
  922. };
  923. Promise$1.prototype.then = function(onFulfilled, onRejected) {
  924. // @ts-ignore
  925. var prom = new this.constructor(noop);
  926. handle(this, new Handler(onFulfilled, onRejected, prom));
  927. return prom;
  928. };
  929. Promise$1.prototype['finally'] = finallyConstructor;
  930. Promise$1.all = function(arr) {
  931. return new Promise$1(function(resolve, reject) {
  932. if (!isArray(arr)) {
  933. return reject(new TypeError('Promise.all accepts an array'));
  934. }
  935. var args = Array.prototype.slice.call(arr);
  936. if (args.length === 0) return resolve([]);
  937. var remaining = args.length;
  938. function res(i, val) {
  939. try {
  940. if (val && (typeof val === 'object' || typeof val === 'function')) {
  941. var then = val.then;
  942. if (typeof then === 'function') {
  943. then.call(
  944. val,
  945. function(val) {
  946. res(i, val);
  947. },
  948. reject
  949. );
  950. return;
  951. }
  952. }
  953. args[i] = val;
  954. if (--remaining === 0) {
  955. resolve(args);
  956. }
  957. } catch (ex) {
  958. reject(ex);
  959. }
  960. }
  961. for (var i = 0; i < args.length; i++) {
  962. res(i, args[i]);
  963. }
  964. });
  965. };
  966. Promise$1.any = any;
  967. Promise$1.allSettled = allSettled;
  968. Promise$1.resolve = function(value) {
  969. if (value && typeof value === 'object' && value.constructor === Promise$1) {
  970. return value;
  971. }
  972. return new Promise$1(function(resolve) {
  973. resolve(value);
  974. });
  975. };
  976. Promise$1.reject = function(value) {
  977. return new Promise$1(function(resolve, reject) {
  978. reject(value);
  979. });
  980. };
  981. Promise$1.race = function(arr) {
  982. return new Promise$1(function(resolve, reject) {
  983. if (!isArray(arr)) {
  984. return reject(new TypeError('Promise.race accepts an array'));
  985. }
  986. for (var i = 0, len = arr.length; i < len; i++) {
  987. Promise$1.resolve(arr[i]).then(resolve, reject);
  988. }
  989. });
  990. };
  991. // Use polyfill for setImmediate for performance gains
  992. Promise$1._immediateFn =
  993. // @ts-ignore
  994. (typeof setImmediate === 'function' &&
  995. function(fn) {
  996. // @ts-ignore
  997. setImmediate(fn);
  998. }) ||
  999. function(fn) {
  1000. setTimeoutFunc(fn, 0);
  1001. };
  1002. Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  1003. if (typeof console !== 'undefined' && console) {
  1004. console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  1005. }
  1006. };
  1007. /** @suppress {undefinedVars} */
  1008. var globalNS = (function() {
  1009. // the only reliable means to get the global object is
  1010. // `Function('return this')()`
  1011. // However, this causes CSP violations in Chrome apps.
  1012. if (typeof self !== 'undefined') {
  1013. return self;
  1014. }
  1015. if (typeof window !== 'undefined') {
  1016. return window;
  1017. }
  1018. if (typeof global !== 'undefined') {
  1019. return global;
  1020. }
  1021. throw new Error('unable to locate global object');
  1022. })();
  1023. // Expose the polyfill if Promise is undefined or set to a
  1024. // non-function value. The latter can be due to a named HTMLElement
  1025. // being exposed by browsers for legacy reasons.
  1026. // https://github.com/taylorhakes/promise-polyfill/issues/114
  1027. if (typeof globalNS['Promise'] !== 'function') {
  1028. globalNS['Promise'] = Promise$1;
  1029. } else {
  1030. if (!globalNS.Promise.prototype['finally']) {
  1031. globalNS.Promise.prototype['finally'] = finallyConstructor;
  1032. }
  1033. if (!globalNS.Promise.allSettled) {
  1034. globalNS.Promise.allSettled = allSettled;
  1035. }
  1036. if (!globalNS.Promise.any) {
  1037. globalNS.Promise.any = any;
  1038. }
  1039. }
  1040. function sortObject(obj) {
  1041. if (typeof obj !== 'object') {
  1042. return obj;
  1043. }
  1044. var temp = {};
  1045. var keys = [];
  1046. for (var key in obj) {
  1047. keys.push(key);
  1048. }
  1049. keys.sort();
  1050. for (var index in keys) {
  1051. temp[keys[index]] = sortObject(obj[keys[index]]);
  1052. }
  1053. return temp;
  1054. }
  1055. function copyTextToClipboard(text) {
  1056. var textArea = document.createElement('textarea');
  1057. textArea.value = text;
  1058. document.body.appendChild(textArea);
  1059. textArea.select();
  1060. try {
  1061. var successful = document.execCommand('copy');
  1062. var msg = successful ? 'successful' : 'unsuccessful';
  1063. console.log('Copying text command was ' + msg);
  1064. } catch (err) {
  1065. console.log('Oops, unable to copy');
  1066. }
  1067. document.body.removeChild(textArea);
  1068. }
  1069. function _defineProperties(e, r) {
  1070. for (var t = 0; t < r.length; t++) {
  1071. var o = r[t];
  1072. o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
  1073. }
  1074. }
  1075. function _createClass(e, r, t) {
  1076. return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", {
  1077. writable: false
  1078. }), e;
  1079. }
  1080. function _extends() {
  1081. return _extends = Object.assign ? Object.assign.bind() : function (n) {
  1082. for (var e = 1; e < arguments.length; e++) {
  1083. var t = arguments[e];
  1084. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  1085. }
  1086. return n;
  1087. }, _extends.apply(null, arguments);
  1088. }
  1089. function _toPrimitive(t, r) {
  1090. if ("object" != typeof t || !t) return t;
  1091. var e = t[Symbol.toPrimitive];
  1092. if (void 0 !== e) {
  1093. var i = e.call(t, r);
  1094. if ("object" != typeof i) return i;
  1095. throw new TypeError("@@toPrimitive must return a primitive value.");
  1096. }
  1097. return (String )(t);
  1098. }
  1099. function _toPropertyKey(t) {
  1100. var i = _toPrimitive(t, "string");
  1101. return "symbol" == typeof i ? i : i + "";
  1102. }
  1103. var Chart$2 = {exports: {}};
  1104. function commonjsRequire(path) {
  1105. 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.');
  1106. }
  1107. var moment$1 = {exports: {}};
  1108. var moment = moment$1.exports;
  1109. var hasRequiredMoment;
  1110. function requireMoment () {
  1111. if (hasRequiredMoment) return moment$1.exports;
  1112. hasRequiredMoment = 1;
  1113. (function (module, exports) {
  1114. (function (global, factory) {
  1115. module.exports = factory() ;
  1116. }(moment, (function () {
  1117. var hookCallback;
  1118. function hooks() {
  1119. return hookCallback.apply(null, arguments);
  1120. }
  1121. // This is done to register the method called with moment()
  1122. // without creating circular dependencies.
  1123. function setHookCallback(callback) {
  1124. hookCallback = callback;
  1125. }
  1126. function isArray(input) {
  1127. return (
  1128. input instanceof Array ||
  1129. Object.prototype.toString.call(input) === '[object Array]'
  1130. );
  1131. }
  1132. function isObject(input) {
  1133. // IE8 will treat undefined and null as object if it wasn't for
  1134. // input != null
  1135. return (
  1136. input != null &&
  1137. Object.prototype.toString.call(input) === '[object Object]'
  1138. );
  1139. }
  1140. function hasOwnProp(a, b) {
  1141. return Object.prototype.hasOwnProperty.call(a, b);
  1142. }
  1143. function isObjectEmpty(obj) {
  1144. if (Object.getOwnPropertyNames) {
  1145. return Object.getOwnPropertyNames(obj).length === 0;
  1146. } else {
  1147. var k;
  1148. for (k in obj) {
  1149. if (hasOwnProp(obj, k)) {
  1150. return false;
  1151. }
  1152. }
  1153. return true;
  1154. }
  1155. }
  1156. function isUndefined(input) {
  1157. return input === void 0;
  1158. }
  1159. function isNumber(input) {
  1160. return (
  1161. typeof input === 'number' ||
  1162. Object.prototype.toString.call(input) === '[object Number]'
  1163. );
  1164. }
  1165. function isDate(input) {
  1166. return (
  1167. input instanceof Date ||
  1168. Object.prototype.toString.call(input) === '[object Date]'
  1169. );
  1170. }
  1171. function map(arr, fn) {
  1172. var res = [],
  1173. i,
  1174. arrLen = arr.length;
  1175. for (i = 0; i < arrLen; ++i) {
  1176. res.push(fn(arr[i], i));
  1177. }
  1178. return res;
  1179. }
  1180. function extend(a, b) {
  1181. for (var i in b) {
  1182. if (hasOwnProp(b, i)) {
  1183. a[i] = b[i];
  1184. }
  1185. }
  1186. if (hasOwnProp(b, 'toString')) {
  1187. a.toString = b.toString;
  1188. }
  1189. if (hasOwnProp(b, 'valueOf')) {
  1190. a.valueOf = b.valueOf;
  1191. }
  1192. return a;
  1193. }
  1194. function createUTC(input, format, locale, strict) {
  1195. return createLocalOrUTC(input, format, locale, strict, true).utc();
  1196. }
  1197. function defaultParsingFlags() {
  1198. // We need to deep clone this object.
  1199. return {
  1200. empty: false,
  1201. unusedTokens: [],
  1202. unusedInput: [],
  1203. overflow: -2,
  1204. charsLeftOver: 0,
  1205. nullInput: false,
  1206. invalidEra: null,
  1207. invalidMonth: null,
  1208. invalidFormat: false,
  1209. userInvalidated: false,
  1210. iso: false,
  1211. parsedDateParts: [],
  1212. era: null,
  1213. meridiem: null,
  1214. rfc2822: false,
  1215. weekdayMismatch: false,
  1216. };
  1217. }
  1218. function getParsingFlags(m) {
  1219. if (m._pf == null) {
  1220. m._pf = defaultParsingFlags();
  1221. }
  1222. return m._pf;
  1223. }
  1224. var some;
  1225. if (Array.prototype.some) {
  1226. some = Array.prototype.some;
  1227. } else {
  1228. some = function (fun) {
  1229. var t = Object(this),
  1230. len = t.length >>> 0,
  1231. i;
  1232. for (i = 0; i < len; i++) {
  1233. if (i in t && fun.call(this, t[i], i, t)) {
  1234. return true;
  1235. }
  1236. }
  1237. return false;
  1238. };
  1239. }
  1240. function isValid(m) {
  1241. if (m._isValid == null) {
  1242. var flags = getParsingFlags(m),
  1243. parsedParts = some.call(flags.parsedDateParts, function (i) {
  1244. return i != null;
  1245. }),
  1246. isNowValid =
  1247. !isNaN(m._d.getTime()) &&
  1248. flags.overflow < 0 &&
  1249. !flags.empty &&
  1250. !flags.invalidEra &&
  1251. !flags.invalidMonth &&
  1252. !flags.invalidWeekday &&
  1253. !flags.weekdayMismatch &&
  1254. !flags.nullInput &&
  1255. !flags.invalidFormat &&
  1256. !flags.userInvalidated &&
  1257. (!flags.meridiem || (flags.meridiem && parsedParts));
  1258. if (m._strict) {
  1259. isNowValid =
  1260. isNowValid &&
  1261. flags.charsLeftOver === 0 &&
  1262. flags.unusedTokens.length === 0 &&
  1263. flags.bigHour === undefined;
  1264. }
  1265. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  1266. m._isValid = isNowValid;
  1267. } else {
  1268. return isNowValid;
  1269. }
  1270. }
  1271. return m._isValid;
  1272. }
  1273. function createInvalid(flags) {
  1274. var m = createUTC(NaN);
  1275. if (flags != null) {
  1276. extend(getParsingFlags(m), flags);
  1277. } else {
  1278. getParsingFlags(m).userInvalidated = true;
  1279. }
  1280. return m;
  1281. }
  1282. // Plugins that add properties should also add the key here (null value),
  1283. // so we can properly clone ourselves.
  1284. var momentProperties = (hooks.momentProperties = []),
  1285. updateInProgress = false;
  1286. function copyConfig(to, from) {
  1287. var i,
  1288. prop,
  1289. val,
  1290. momentPropertiesLen = momentProperties.length;
  1291. if (!isUndefined(from._isAMomentObject)) {
  1292. to._isAMomentObject = from._isAMomentObject;
  1293. }
  1294. if (!isUndefined(from._i)) {
  1295. to._i = from._i;
  1296. }
  1297. if (!isUndefined(from._f)) {
  1298. to._f = from._f;
  1299. }
  1300. if (!isUndefined(from._l)) {
  1301. to._l = from._l;
  1302. }
  1303. if (!isUndefined(from._strict)) {
  1304. to._strict = from._strict;
  1305. }
  1306. if (!isUndefined(from._tzm)) {
  1307. to._tzm = from._tzm;
  1308. }
  1309. if (!isUndefined(from._isUTC)) {
  1310. to._isUTC = from._isUTC;
  1311. }
  1312. if (!isUndefined(from._offset)) {
  1313. to._offset = from._offset;
  1314. }
  1315. if (!isUndefined(from._pf)) {
  1316. to._pf = getParsingFlags(from);
  1317. }
  1318. if (!isUndefined(from._locale)) {
  1319. to._locale = from._locale;
  1320. }
  1321. if (momentPropertiesLen > 0) {
  1322. for (i = 0; i < momentPropertiesLen; i++) {
  1323. prop = momentProperties[i];
  1324. val = from[prop];
  1325. if (!isUndefined(val)) {
  1326. to[prop] = val;
  1327. }
  1328. }
  1329. }
  1330. return to;
  1331. }
  1332. // Moment prototype object
  1333. function Moment(config) {
  1334. copyConfig(this, config);
  1335. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  1336. if (!this.isValid()) {
  1337. this._d = new Date(NaN);
  1338. }
  1339. // Prevent infinite loop in case updateOffset creates new moment
  1340. // objects.
  1341. if (updateInProgress === false) {
  1342. updateInProgress = true;
  1343. hooks.updateOffset(this);
  1344. updateInProgress = false;
  1345. }
  1346. }
  1347. function isMoment(obj) {
  1348. return (
  1349. obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
  1350. );
  1351. }
  1352. function warn(msg) {
  1353. if (
  1354. hooks.suppressDeprecationWarnings === false &&
  1355. typeof console !== 'undefined' &&
  1356. console.warn
  1357. ) {
  1358. console.warn('Deprecation warning: ' + msg);
  1359. }
  1360. }
  1361. function deprecate(msg, fn) {
  1362. var firstTime = true;
  1363. return extend(function () {
  1364. if (hooks.deprecationHandler != null) {
  1365. hooks.deprecationHandler(null, msg);
  1366. }
  1367. if (firstTime) {
  1368. var args = [],
  1369. arg,
  1370. i,
  1371. key,
  1372. argLen = arguments.length;
  1373. for (i = 0; i < argLen; i++) {
  1374. arg = '';
  1375. if (typeof arguments[i] === 'object') {
  1376. arg += '\n[' + i + '] ';
  1377. for (key in arguments[0]) {
  1378. if (hasOwnProp(arguments[0], key)) {
  1379. arg += key + ': ' + arguments[0][key] + ', ';
  1380. }
  1381. }
  1382. arg = arg.slice(0, -2); // Remove trailing comma and space
  1383. } else {
  1384. arg = arguments[i];
  1385. }
  1386. args.push(arg);
  1387. }
  1388. warn(
  1389. msg +
  1390. '\nArguments: ' +
  1391. Array.prototype.slice.call(args).join('') +
  1392. '\n' +
  1393. new Error().stack
  1394. );
  1395. firstTime = false;
  1396. }
  1397. return fn.apply(this, arguments);
  1398. }, fn);
  1399. }
  1400. var deprecations = {};
  1401. function deprecateSimple(name, msg) {
  1402. if (hooks.deprecationHandler != null) {
  1403. hooks.deprecationHandler(name, msg);
  1404. }
  1405. if (!deprecations[name]) {
  1406. warn(msg);
  1407. deprecations[name] = true;
  1408. }
  1409. }
  1410. hooks.suppressDeprecationWarnings = false;
  1411. hooks.deprecationHandler = null;
  1412. function isFunction(input) {
  1413. return (
  1414. (typeof Function !== 'undefined' && input instanceof Function) ||
  1415. Object.prototype.toString.call(input) === '[object Function]'
  1416. );
  1417. }
  1418. function set(config) {
  1419. var prop, i;
  1420. for (i in config) {
  1421. if (hasOwnProp(config, i)) {
  1422. prop = config[i];
  1423. if (isFunction(prop)) {
  1424. this[i] = prop;
  1425. } else {
  1426. this['_' + i] = prop;
  1427. }
  1428. }
  1429. }
  1430. this._config = config;
  1431. // Lenient ordinal parsing accepts just a number in addition to
  1432. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  1433. // TODO: Remove "ordinalParse" fallback in next major release.
  1434. this._dayOfMonthOrdinalParseLenient = new RegExp(
  1435. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  1436. '|' +
  1437. /\d{1,2}/.source
  1438. );
  1439. }
  1440. function mergeConfigs(parentConfig, childConfig) {
  1441. var res = extend({}, parentConfig),
  1442. prop;
  1443. for (prop in childConfig) {
  1444. if (hasOwnProp(childConfig, prop)) {
  1445. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  1446. res[prop] = {};
  1447. extend(res[prop], parentConfig[prop]);
  1448. extend(res[prop], childConfig[prop]);
  1449. } else if (childConfig[prop] != null) {
  1450. res[prop] = childConfig[prop];
  1451. } else {
  1452. delete res[prop];
  1453. }
  1454. }
  1455. }
  1456. for (prop in parentConfig) {
  1457. if (
  1458. hasOwnProp(parentConfig, prop) &&
  1459. !hasOwnProp(childConfig, prop) &&
  1460. isObject(parentConfig[prop])
  1461. ) {
  1462. // make sure changes to properties don't modify parent config
  1463. res[prop] = extend({}, res[prop]);
  1464. }
  1465. }
  1466. return res;
  1467. }
  1468. function Locale(config) {
  1469. if (config != null) {
  1470. this.set(config);
  1471. }
  1472. }
  1473. var keys;
  1474. if (Object.keys) {
  1475. keys = Object.keys;
  1476. } else {
  1477. keys = function (obj) {
  1478. var i,
  1479. res = [];
  1480. for (i in obj) {
  1481. if (hasOwnProp(obj, i)) {
  1482. res.push(i);
  1483. }
  1484. }
  1485. return res;
  1486. };
  1487. }
  1488. var defaultCalendar = {
  1489. sameDay: '[Today at] LT',
  1490. nextDay: '[Tomorrow at] LT',
  1491. nextWeek: 'dddd [at] LT',
  1492. lastDay: '[Yesterday at] LT',
  1493. lastWeek: '[Last] dddd [at] LT',
  1494. sameElse: 'L',
  1495. };
  1496. function calendar(key, mom, now) {
  1497. var output = this._calendar[key] || this._calendar['sameElse'];
  1498. return isFunction(output) ? output.call(mom, now) : output;
  1499. }
  1500. function zeroFill(number, targetLength, forceSign) {
  1501. var absNumber = '' + Math.abs(number),
  1502. zerosToFill = targetLength - absNumber.length,
  1503. sign = number >= 0;
  1504. return (
  1505. (sign ? (forceSign ? '+' : '') : '-') +
  1506. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
  1507. absNumber
  1508. );
  1509. }
  1510. var formattingTokens =
  1511. /(\[[^\[]*\])|(\\)?([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,
  1512. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
  1513. formatFunctions = {},
  1514. formatTokenFunctions = {};
  1515. // token: 'M'
  1516. // padded: ['MM', 2]
  1517. // ordinal: 'Mo'
  1518. // callback: function () { this.month() + 1 }
  1519. function addFormatToken(token, padded, ordinal, callback) {
  1520. var func = callback;
  1521. if (typeof callback === 'string') {
  1522. func = function () {
  1523. return this[callback]();
  1524. };
  1525. }
  1526. if (token) {
  1527. formatTokenFunctions[token] = func;
  1528. }
  1529. if (padded) {
  1530. formatTokenFunctions[padded[0]] = function () {
  1531. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  1532. };
  1533. }
  1534. if (ordinal) {
  1535. formatTokenFunctions[ordinal] = function () {
  1536. return this.localeData().ordinal(
  1537. func.apply(this, arguments),
  1538. token
  1539. );
  1540. };
  1541. }
  1542. }
  1543. function removeFormattingTokens(input) {
  1544. if (input.match(/\[[\s\S]/)) {
  1545. return input.replace(/^\[|\]$/g, '');
  1546. }
  1547. return input.replace(/\\/g, '');
  1548. }
  1549. function makeFormatFunction(format) {
  1550. var array = format.match(formattingTokens),
  1551. i,
  1552. length;
  1553. for (i = 0, length = array.length; i < length; i++) {
  1554. if (formatTokenFunctions[array[i]]) {
  1555. array[i] = formatTokenFunctions[array[i]];
  1556. } else {
  1557. array[i] = removeFormattingTokens(array[i]);
  1558. }
  1559. }
  1560. return function (mom) {
  1561. var output = '',
  1562. i;
  1563. for (i = 0; i < length; i++) {
  1564. output += isFunction(array[i])
  1565. ? array[i].call(mom, format)
  1566. : array[i];
  1567. }
  1568. return output;
  1569. };
  1570. }
  1571. // format date using native date object
  1572. function formatMoment(m, format) {
  1573. if (!m.isValid()) {
  1574. return m.localeData().invalidDate();
  1575. }
  1576. format = expandFormat(format, m.localeData());
  1577. formatFunctions[format] =
  1578. formatFunctions[format] || makeFormatFunction(format);
  1579. return formatFunctions[format](m);
  1580. }
  1581. function expandFormat(format, locale) {
  1582. var i = 5;
  1583. function replaceLongDateFormatTokens(input) {
  1584. return locale.longDateFormat(input) || input;
  1585. }
  1586. localFormattingTokens.lastIndex = 0;
  1587. while (i >= 0 && localFormattingTokens.test(format)) {
  1588. format = format.replace(
  1589. localFormattingTokens,
  1590. replaceLongDateFormatTokens
  1591. );
  1592. localFormattingTokens.lastIndex = 0;
  1593. i -= 1;
  1594. }
  1595. return format;
  1596. }
  1597. var defaultLongDateFormat = {
  1598. LTS: 'h:mm:ss A',
  1599. LT: 'h:mm A',
  1600. L: 'MM/DD/YYYY',
  1601. LL: 'MMMM D, YYYY',
  1602. LLL: 'MMMM D, YYYY h:mm A',
  1603. LLLL: 'dddd, MMMM D, YYYY h:mm A',
  1604. };
  1605. function longDateFormat(key) {
  1606. var format = this._longDateFormat[key],
  1607. formatUpper = this._longDateFormat[key.toUpperCase()];
  1608. if (format || !formatUpper) {
  1609. return format;
  1610. }
  1611. this._longDateFormat[key] = formatUpper
  1612. .match(formattingTokens)
  1613. .map(function (tok) {
  1614. if (
  1615. tok === 'MMMM' ||
  1616. tok === 'MM' ||
  1617. tok === 'DD' ||
  1618. tok === 'dddd'
  1619. ) {
  1620. return tok.slice(1);
  1621. }
  1622. return tok;
  1623. })
  1624. .join('');
  1625. return this._longDateFormat[key];
  1626. }
  1627. var defaultInvalidDate = 'Invalid date';
  1628. function invalidDate() {
  1629. return this._invalidDate;
  1630. }
  1631. var defaultOrdinal = '%d',
  1632. defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  1633. function ordinal(number) {
  1634. return this._ordinal.replace('%d', number);
  1635. }
  1636. var defaultRelativeTime = {
  1637. future: 'in %s',
  1638. past: '%s ago',
  1639. s: 'a few seconds',
  1640. ss: '%d seconds',
  1641. m: 'a minute',
  1642. mm: '%d minutes',
  1643. h: 'an hour',
  1644. hh: '%d hours',
  1645. d: 'a day',
  1646. dd: '%d days',
  1647. w: 'a week',
  1648. ww: '%d weeks',
  1649. M: 'a month',
  1650. MM: '%d months',
  1651. y: 'a year',
  1652. yy: '%d years',
  1653. };
  1654. function relativeTime(number, withoutSuffix, string, isFuture) {
  1655. var output = this._relativeTime[string];
  1656. return isFunction(output)
  1657. ? output(number, withoutSuffix, string, isFuture)
  1658. : output.replace(/%d/i, number);
  1659. }
  1660. function pastFuture(diff, output) {
  1661. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  1662. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  1663. }
  1664. var aliases = {};
  1665. function addUnitAlias(unit, shorthand) {
  1666. var lowerCase = unit.toLowerCase();
  1667. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  1668. }
  1669. function normalizeUnits(units) {
  1670. return typeof units === 'string'
  1671. ? aliases[units] || aliases[units.toLowerCase()]
  1672. : undefined;
  1673. }
  1674. function normalizeObjectUnits(inputObject) {
  1675. var normalizedInput = {},
  1676. normalizedProp,
  1677. prop;
  1678. for (prop in inputObject) {
  1679. if (hasOwnProp(inputObject, prop)) {
  1680. normalizedProp = normalizeUnits(prop);
  1681. if (normalizedProp) {
  1682. normalizedInput[normalizedProp] = inputObject[prop];
  1683. }
  1684. }
  1685. }
  1686. return normalizedInput;
  1687. }
  1688. var priorities = {};
  1689. function addUnitPriority(unit, priority) {
  1690. priorities[unit] = priority;
  1691. }
  1692. function getPrioritizedUnits(unitsObj) {
  1693. var units = [],
  1694. u;
  1695. for (u in unitsObj) {
  1696. if (hasOwnProp(unitsObj, u)) {
  1697. units.push({ unit: u, priority: priorities[u] });
  1698. }
  1699. }
  1700. units.sort(function (a, b) {
  1701. return a.priority - b.priority;
  1702. });
  1703. return units;
  1704. }
  1705. function isLeapYear(year) {
  1706. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  1707. }
  1708. function absFloor(number) {
  1709. if (number < 0) {
  1710. // -0 -> 0
  1711. return Math.ceil(number) || 0;
  1712. } else {
  1713. return Math.floor(number);
  1714. }
  1715. }
  1716. function toInt(argumentForCoercion) {
  1717. var coercedNumber = +argumentForCoercion,
  1718. value = 0;
  1719. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  1720. value = absFloor(coercedNumber);
  1721. }
  1722. return value;
  1723. }
  1724. function makeGetSet(unit, keepTime) {
  1725. return function (value) {
  1726. if (value != null) {
  1727. set$1(this, unit, value);
  1728. hooks.updateOffset(this, keepTime);
  1729. return this;
  1730. } else {
  1731. return get(this, unit);
  1732. }
  1733. };
  1734. }
  1735. function get(mom, unit) {
  1736. return mom.isValid()
  1737. ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
  1738. : NaN;
  1739. }
  1740. function set$1(mom, unit, value) {
  1741. if (mom.isValid() && !isNaN(value)) {
  1742. if (
  1743. unit === 'FullYear' &&
  1744. isLeapYear(mom.year()) &&
  1745. mom.month() === 1 &&
  1746. mom.date() === 29
  1747. ) {
  1748. value = toInt(value);
  1749. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
  1750. value,
  1751. mom.month(),
  1752. daysInMonth(value, mom.month())
  1753. );
  1754. } else {
  1755. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  1756. }
  1757. }
  1758. }
  1759. // MOMENTS
  1760. function stringGet(units) {
  1761. units = normalizeUnits(units);
  1762. if (isFunction(this[units])) {
  1763. return this[units]();
  1764. }
  1765. return this;
  1766. }
  1767. function stringSet(units, value) {
  1768. if (typeof units === 'object') {
  1769. units = normalizeObjectUnits(units);
  1770. var prioritized = getPrioritizedUnits(units),
  1771. i,
  1772. prioritizedLen = prioritized.length;
  1773. for (i = 0; i < prioritizedLen; i++) {
  1774. this[prioritized[i].unit](units[prioritized[i].unit]);
  1775. }
  1776. } else {
  1777. units = normalizeUnits(units);
  1778. if (isFunction(this[units])) {
  1779. return this[units](value);
  1780. }
  1781. }
  1782. return this;
  1783. }
  1784. var match1 = /\d/, // 0 - 9
  1785. match2 = /\d\d/, // 00 - 99
  1786. match3 = /\d{3}/, // 000 - 999
  1787. match4 = /\d{4}/, // 0000 - 9999
  1788. match6 = /[+-]?\d{6}/, // -999999 - 999999
  1789. match1to2 = /\d\d?/, // 0 - 99
  1790. match3to4 = /\d\d\d\d?/, // 999 - 9999
  1791. match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
  1792. match1to3 = /\d{1,3}/, // 0 - 999
  1793. match1to4 = /\d{1,4}/, // 0 - 9999
  1794. match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
  1795. matchUnsigned = /\d+/, // 0 - inf
  1796. matchSigned = /[+-]?\d+/, // -inf - inf
  1797. matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  1798. matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  1799. matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  1800. // any word (or two) characters or numbers including two/three word month in arabic.
  1801. // includes scottish gaelic two word and hyphenated months
  1802. matchWord =
  1803. /[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,
  1804. regexes;
  1805. regexes = {};
  1806. function addRegexToken(token, regex, strictRegex) {
  1807. regexes[token] = isFunction(regex)
  1808. ? regex
  1809. : function (isStrict, localeData) {
  1810. return isStrict && strictRegex ? strictRegex : regex;
  1811. };
  1812. }
  1813. function getParseRegexForToken(token, config) {
  1814. if (!hasOwnProp(regexes, token)) {
  1815. return new RegExp(unescapeFormat(token));
  1816. }
  1817. return regexes[token](config._strict, config._locale);
  1818. }
  1819. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  1820. function unescapeFormat(s) {
  1821. return regexEscape(
  1822. s
  1823. .replace('\\', '')
  1824. .replace(
  1825. /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,
  1826. function (matched, p1, p2, p3, p4) {
  1827. return p1 || p2 || p3 || p4;
  1828. }
  1829. )
  1830. );
  1831. }
  1832. function regexEscape(s) {
  1833. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  1834. }
  1835. var tokens = {};
  1836. function addParseToken(token, callback) {
  1837. var i,
  1838. func = callback,
  1839. tokenLen;
  1840. if (typeof token === 'string') {
  1841. token = [token];
  1842. }
  1843. if (isNumber(callback)) {
  1844. func = function (input, array) {
  1845. array[callback] = toInt(input);
  1846. };
  1847. }
  1848. tokenLen = token.length;
  1849. for (i = 0; i < tokenLen; i++) {
  1850. tokens[token[i]] = func;
  1851. }
  1852. }
  1853. function addWeekParseToken(token, callback) {
  1854. addParseToken(token, function (input, array, config, token) {
  1855. config._w = config._w || {};
  1856. callback(input, config._w, config, token);
  1857. });
  1858. }
  1859. function addTimeToArrayFromToken(token, input, config) {
  1860. if (input != null && hasOwnProp(tokens, token)) {
  1861. tokens[token](input, config._a, config, token);
  1862. }
  1863. }
  1864. var YEAR = 0,
  1865. MONTH = 1,
  1866. DATE = 2,
  1867. HOUR = 3,
  1868. MINUTE = 4,
  1869. SECOND = 5,
  1870. MILLISECOND = 6,
  1871. WEEK = 7,
  1872. WEEKDAY = 8;
  1873. function mod(n, x) {
  1874. return ((n % x) + x) % x;
  1875. }
  1876. var indexOf;
  1877. if (Array.prototype.indexOf) {
  1878. indexOf = Array.prototype.indexOf;
  1879. } else {
  1880. indexOf = function (o) {
  1881. // I know
  1882. var i;
  1883. for (i = 0; i < this.length; ++i) {
  1884. if (this[i] === o) {
  1885. return i;
  1886. }
  1887. }
  1888. return -1;
  1889. };
  1890. }
  1891. function daysInMonth(year, month) {
  1892. if (isNaN(year) || isNaN(month)) {
  1893. return NaN;
  1894. }
  1895. var modMonth = mod(month, 12);
  1896. year += (month - modMonth) / 12;
  1897. return modMonth === 1
  1898. ? isLeapYear(year)
  1899. ? 29
  1900. : 28
  1901. : 31 - ((modMonth % 7) % 2);
  1902. }
  1903. // FORMATTING
  1904. addFormatToken('M', ['MM', 2], 'Mo', function () {
  1905. return this.month() + 1;
  1906. });
  1907. addFormatToken('MMM', 0, 0, function (format) {
  1908. return this.localeData().monthsShort(this, format);
  1909. });
  1910. addFormatToken('MMMM', 0, 0, function (format) {
  1911. return this.localeData().months(this, format);
  1912. });
  1913. // ALIASES
  1914. addUnitAlias('month', 'M');
  1915. // PRIORITY
  1916. addUnitPriority('month', 8);
  1917. // PARSING
  1918. addRegexToken('M', match1to2);
  1919. addRegexToken('MM', match1to2, match2);
  1920. addRegexToken('MMM', function (isStrict, locale) {
  1921. return locale.monthsShortRegex(isStrict);
  1922. });
  1923. addRegexToken('MMMM', function (isStrict, locale) {
  1924. return locale.monthsRegex(isStrict);
  1925. });
  1926. addParseToken(['M', 'MM'], function (input, array) {
  1927. array[MONTH] = toInt(input) - 1;
  1928. });
  1929. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  1930. var month = config._locale.monthsParse(input, token, config._strict);
  1931. // if we didn't find a month name, mark the date as invalid.
  1932. if (month != null) {
  1933. array[MONTH] = month;
  1934. } else {
  1935. getParsingFlags(config).invalidMonth = input;
  1936. }
  1937. });
  1938. // LOCALES
  1939. var defaultLocaleMonths =
  1940. 'January_February_March_April_May_June_July_August_September_October_November_December'.split(
  1941. '_'
  1942. ),
  1943. defaultLocaleMonthsShort =
  1944. 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
  1945. MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
  1946. defaultMonthsShortRegex = matchWord,
  1947. defaultMonthsRegex = matchWord;
  1948. function localeMonths(m, format) {
  1949. if (!m) {
  1950. return isArray(this._months)
  1951. ? this._months
  1952. : this._months['standalone'];
  1953. }
  1954. return isArray(this._months)
  1955. ? this._months[m.month()]
  1956. : this._months[
  1957. (this._months.isFormat || MONTHS_IN_FORMAT).test(format)
  1958. ? 'format'
  1959. : 'standalone'
  1960. ][m.month()];
  1961. }
  1962. function localeMonthsShort(m, format) {
  1963. if (!m) {
  1964. return isArray(this._monthsShort)
  1965. ? this._monthsShort
  1966. : this._monthsShort['standalone'];
  1967. }
  1968. return isArray(this._monthsShort)
  1969. ? this._monthsShort[m.month()]
  1970. : this._monthsShort[
  1971. MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
  1972. ][m.month()];
  1973. }
  1974. function handleStrictParse(monthName, format, strict) {
  1975. var i,
  1976. ii,
  1977. mom,
  1978. llc = monthName.toLocaleLowerCase();
  1979. if (!this._monthsParse) {
  1980. // this is not used
  1981. this._monthsParse = [];
  1982. this._longMonthsParse = [];
  1983. this._shortMonthsParse = [];
  1984. for (i = 0; i < 12; ++i) {
  1985. mom = createUTC([2000, i]);
  1986. this._shortMonthsParse[i] = this.monthsShort(
  1987. mom,
  1988. ''
  1989. ).toLocaleLowerCase();
  1990. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  1991. }
  1992. }
  1993. if (strict) {
  1994. if (format === 'MMM') {
  1995. ii = indexOf.call(this._shortMonthsParse, llc);
  1996. return ii !== -1 ? ii : null;
  1997. } else {
  1998. ii = indexOf.call(this._longMonthsParse, llc);
  1999. return ii !== -1 ? ii : null;
  2000. }
  2001. } else {
  2002. if (format === 'MMM') {
  2003. ii = indexOf.call(this._shortMonthsParse, llc);
  2004. if (ii !== -1) {
  2005. return ii;
  2006. }
  2007. ii = indexOf.call(this._longMonthsParse, llc);
  2008. return ii !== -1 ? ii : null;
  2009. } else {
  2010. ii = indexOf.call(this._longMonthsParse, llc);
  2011. if (ii !== -1) {
  2012. return ii;
  2013. }
  2014. ii = indexOf.call(this._shortMonthsParse, llc);
  2015. return ii !== -1 ? ii : null;
  2016. }
  2017. }
  2018. }
  2019. function localeMonthsParse(monthName, format, strict) {
  2020. var i, mom, regex;
  2021. if (this._monthsParseExact) {
  2022. return handleStrictParse.call(this, monthName, format, strict);
  2023. }
  2024. if (!this._monthsParse) {
  2025. this._monthsParse = [];
  2026. this._longMonthsParse = [];
  2027. this._shortMonthsParse = [];
  2028. }
  2029. // TODO: add sorting
  2030. // Sorting makes sure if one month (or abbr) is a prefix of another
  2031. // see sorting in computeMonthsParse
  2032. for (i = 0; i < 12; i++) {
  2033. // make the regex if we don't have it already
  2034. mom = createUTC([2000, i]);
  2035. if (strict && !this._longMonthsParse[i]) {
  2036. this._longMonthsParse[i] = new RegExp(
  2037. '^' + this.months(mom, '').replace('.', '') + '$',
  2038. 'i'
  2039. );
  2040. this._shortMonthsParse[i] = new RegExp(
  2041. '^' + this.monthsShort(mom, '').replace('.', '') + '$',
  2042. 'i'
  2043. );
  2044. }
  2045. if (!strict && !this._monthsParse[i]) {
  2046. regex =
  2047. '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  2048. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  2049. }
  2050. // test the regex
  2051. if (
  2052. strict &&
  2053. format === 'MMMM' &&
  2054. this._longMonthsParse[i].test(monthName)
  2055. ) {
  2056. return i;
  2057. } else if (
  2058. strict &&
  2059. format === 'MMM' &&
  2060. this._shortMonthsParse[i].test(monthName)
  2061. ) {
  2062. return i;
  2063. } else if (!strict && this._monthsParse[i].test(monthName)) {
  2064. return i;
  2065. }
  2066. }
  2067. }
  2068. // MOMENTS
  2069. function setMonth(mom, value) {
  2070. var dayOfMonth;
  2071. if (!mom.isValid()) {
  2072. // No op
  2073. return mom;
  2074. }
  2075. if (typeof value === 'string') {
  2076. if (/^\d+$/.test(value)) {
  2077. value = toInt(value);
  2078. } else {
  2079. value = mom.localeData().monthsParse(value);
  2080. // TODO: Another silent failure?
  2081. if (!isNumber(value)) {
  2082. return mom;
  2083. }
  2084. }
  2085. }
  2086. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  2087. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  2088. return mom;
  2089. }
  2090. function getSetMonth(value) {
  2091. if (value != null) {
  2092. setMonth(this, value);
  2093. hooks.updateOffset(this, true);
  2094. return this;
  2095. } else {
  2096. return get(this, 'Month');
  2097. }
  2098. }
  2099. function getDaysInMonth() {
  2100. return daysInMonth(this.year(), this.month());
  2101. }
  2102. function monthsShortRegex(isStrict) {
  2103. if (this._monthsParseExact) {
  2104. if (!hasOwnProp(this, '_monthsRegex')) {
  2105. computeMonthsParse.call(this);
  2106. }
  2107. if (isStrict) {
  2108. return this._monthsShortStrictRegex;
  2109. } else {
  2110. return this._monthsShortRegex;
  2111. }
  2112. } else {
  2113. if (!hasOwnProp(this, '_monthsShortRegex')) {
  2114. this._monthsShortRegex = defaultMonthsShortRegex;
  2115. }
  2116. return this._monthsShortStrictRegex && isStrict
  2117. ? this._monthsShortStrictRegex
  2118. : this._monthsShortRegex;
  2119. }
  2120. }
  2121. function monthsRegex(isStrict) {
  2122. if (this._monthsParseExact) {
  2123. if (!hasOwnProp(this, '_monthsRegex')) {
  2124. computeMonthsParse.call(this);
  2125. }
  2126. if (isStrict) {
  2127. return this._monthsStrictRegex;
  2128. } else {
  2129. return this._monthsRegex;
  2130. }
  2131. } else {
  2132. if (!hasOwnProp(this, '_monthsRegex')) {
  2133. this._monthsRegex = defaultMonthsRegex;
  2134. }
  2135. return this._monthsStrictRegex && isStrict
  2136. ? this._monthsStrictRegex
  2137. : this._monthsRegex;
  2138. }
  2139. }
  2140. function computeMonthsParse() {
  2141. function cmpLenRev(a, b) {
  2142. return b.length - a.length;
  2143. }
  2144. var shortPieces = [],
  2145. longPieces = [],
  2146. mixedPieces = [],
  2147. i,
  2148. mom;
  2149. for (i = 0; i < 12; i++) {
  2150. // make the regex if we don't have it already
  2151. mom = createUTC([2000, i]);
  2152. shortPieces.push(this.monthsShort(mom, ''));
  2153. longPieces.push(this.months(mom, ''));
  2154. mixedPieces.push(this.months(mom, ''));
  2155. mixedPieces.push(this.monthsShort(mom, ''));
  2156. }
  2157. // Sorting makes sure if one month (or abbr) is a prefix of another it
  2158. // will match the longer piece.
  2159. shortPieces.sort(cmpLenRev);
  2160. longPieces.sort(cmpLenRev);
  2161. mixedPieces.sort(cmpLenRev);
  2162. for (i = 0; i < 12; i++) {
  2163. shortPieces[i] = regexEscape(shortPieces[i]);
  2164. longPieces[i] = regexEscape(longPieces[i]);
  2165. }
  2166. for (i = 0; i < 24; i++) {
  2167. mixedPieces[i] = regexEscape(mixedPieces[i]);
  2168. }
  2169. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  2170. this._monthsShortRegex = this._monthsRegex;
  2171. this._monthsStrictRegex = new RegExp(
  2172. '^(' + longPieces.join('|') + ')',
  2173. 'i'
  2174. );
  2175. this._monthsShortStrictRegex = new RegExp(
  2176. '^(' + shortPieces.join('|') + ')',
  2177. 'i'
  2178. );
  2179. }
  2180. // FORMATTING
  2181. addFormatToken('Y', 0, 0, function () {
  2182. var y = this.year();
  2183. return y <= 9999 ? zeroFill(y, 4) : '+' + y;
  2184. });
  2185. addFormatToken(0, ['YY', 2], 0, function () {
  2186. return this.year() % 100;
  2187. });
  2188. addFormatToken(0, ['YYYY', 4], 0, 'year');
  2189. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  2190. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  2191. // ALIASES
  2192. addUnitAlias('year', 'y');
  2193. // PRIORITIES
  2194. addUnitPriority('year', 1);
  2195. // PARSING
  2196. addRegexToken('Y', matchSigned);
  2197. addRegexToken('YY', match1to2, match2);
  2198. addRegexToken('YYYY', match1to4, match4);
  2199. addRegexToken('YYYYY', match1to6, match6);
  2200. addRegexToken('YYYYYY', match1to6, match6);
  2201. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  2202. addParseToken('YYYY', function (input, array) {
  2203. array[YEAR] =
  2204. input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  2205. });
  2206. addParseToken('YY', function (input, array) {
  2207. array[YEAR] = hooks.parseTwoDigitYear(input);
  2208. });
  2209. addParseToken('Y', function (input, array) {
  2210. array[YEAR] = parseInt(input, 10);
  2211. });
  2212. // HELPERS
  2213. function daysInYear(year) {
  2214. return isLeapYear(year) ? 366 : 365;
  2215. }
  2216. // HOOKS
  2217. hooks.parseTwoDigitYear = function (input) {
  2218. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  2219. };
  2220. // MOMENTS
  2221. var getSetYear = makeGetSet('FullYear', true);
  2222. function getIsLeapYear() {
  2223. return isLeapYear(this.year());
  2224. }
  2225. function createDate(y, m, d, h, M, s, ms) {
  2226. // can't just apply() to create a date:
  2227. // https://stackoverflow.com/q/181348
  2228. var date;
  2229. // the date constructor remaps years 0-99 to 1900-1999
  2230. if (y < 100 && y >= 0) {
  2231. // preserve leap years using a full 400 year cycle, then reset
  2232. date = new Date(y + 400, m, d, h, M, s, ms);
  2233. if (isFinite(date.getFullYear())) {
  2234. date.setFullYear(y);
  2235. }
  2236. } else {
  2237. date = new Date(y, m, d, h, M, s, ms);
  2238. }
  2239. return date;
  2240. }
  2241. function createUTCDate(y) {
  2242. var date, args;
  2243. // the Date.UTC function remaps years 0-99 to 1900-1999
  2244. if (y < 100 && y >= 0) {
  2245. args = Array.prototype.slice.call(arguments);
  2246. // preserve leap years using a full 400 year cycle, then reset
  2247. args[0] = y + 400;
  2248. date = new Date(Date.UTC.apply(null, args));
  2249. if (isFinite(date.getUTCFullYear())) {
  2250. date.setUTCFullYear(y);
  2251. }
  2252. } else {
  2253. date = new Date(Date.UTC.apply(null, arguments));
  2254. }
  2255. return date;
  2256. }
  2257. // start-of-first-week - start-of-year
  2258. function firstWeekOffset(year, dow, doy) {
  2259. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  2260. fwd = 7 + dow - doy,
  2261. // first-week day local weekday -- which local weekday is fwd
  2262. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  2263. return -fwdlw + fwd - 1;
  2264. }
  2265. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  2266. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  2267. var localWeekday = (7 + weekday - dow) % 7,
  2268. weekOffset = firstWeekOffset(year, dow, doy),
  2269. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  2270. resYear,
  2271. resDayOfYear;
  2272. if (dayOfYear <= 0) {
  2273. resYear = year - 1;
  2274. resDayOfYear = daysInYear(resYear) + dayOfYear;
  2275. } else if (dayOfYear > daysInYear(year)) {
  2276. resYear = year + 1;
  2277. resDayOfYear = dayOfYear - daysInYear(year);
  2278. } else {
  2279. resYear = year;
  2280. resDayOfYear = dayOfYear;
  2281. }
  2282. return {
  2283. year: resYear,
  2284. dayOfYear: resDayOfYear,
  2285. };
  2286. }
  2287. function weekOfYear(mom, dow, doy) {
  2288. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  2289. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  2290. resWeek,
  2291. resYear;
  2292. if (week < 1) {
  2293. resYear = mom.year() - 1;
  2294. resWeek = week + weeksInYear(resYear, dow, doy);
  2295. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  2296. resWeek = week - weeksInYear(mom.year(), dow, doy);
  2297. resYear = mom.year() + 1;
  2298. } else {
  2299. resYear = mom.year();
  2300. resWeek = week;
  2301. }
  2302. return {
  2303. week: resWeek,
  2304. year: resYear,
  2305. };
  2306. }
  2307. function weeksInYear(year, dow, doy) {
  2308. var weekOffset = firstWeekOffset(year, dow, doy),
  2309. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  2310. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  2311. }
  2312. // FORMATTING
  2313. addFormatToken('w', ['ww', 2], 'wo', 'week');
  2314. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  2315. // ALIASES
  2316. addUnitAlias('week', 'w');
  2317. addUnitAlias('isoWeek', 'W');
  2318. // PRIORITIES
  2319. addUnitPriority('week', 5);
  2320. addUnitPriority('isoWeek', 5);
  2321. // PARSING
  2322. addRegexToken('w', match1to2);
  2323. addRegexToken('ww', match1to2, match2);
  2324. addRegexToken('W', match1to2);
  2325. addRegexToken('WW', match1to2, match2);
  2326. addWeekParseToken(
  2327. ['w', 'ww', 'W', 'WW'],
  2328. function (input, week, config, token) {
  2329. week[token.substr(0, 1)] = toInt(input);
  2330. }
  2331. );
  2332. // HELPERS
  2333. // LOCALES
  2334. function localeWeek(mom) {
  2335. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  2336. }
  2337. var defaultLocaleWeek = {
  2338. dow: 0, // Sunday is the first day of the week.
  2339. doy: 6, // The week that contains Jan 6th is the first week of the year.
  2340. };
  2341. function localeFirstDayOfWeek() {
  2342. return this._week.dow;
  2343. }
  2344. function localeFirstDayOfYear() {
  2345. return this._week.doy;
  2346. }
  2347. // MOMENTS
  2348. function getSetWeek(input) {
  2349. var week = this.localeData().week(this);
  2350. return input == null ? week : this.add((input - week) * 7, 'd');
  2351. }
  2352. function getSetISOWeek(input) {
  2353. var week = weekOfYear(this, 1, 4).week;
  2354. return input == null ? week : this.add((input - week) * 7, 'd');
  2355. }
  2356. // FORMATTING
  2357. addFormatToken('d', 0, 'do', 'day');
  2358. addFormatToken('dd', 0, 0, function (format) {
  2359. return this.localeData().weekdaysMin(this, format);
  2360. });
  2361. addFormatToken('ddd', 0, 0, function (format) {
  2362. return this.localeData().weekdaysShort(this, format);
  2363. });
  2364. addFormatToken('dddd', 0, 0, function (format) {
  2365. return this.localeData().weekdays(this, format);
  2366. });
  2367. addFormatToken('e', 0, 0, 'weekday');
  2368. addFormatToken('E', 0, 0, 'isoWeekday');
  2369. // ALIASES
  2370. addUnitAlias('day', 'd');
  2371. addUnitAlias('weekday', 'e');
  2372. addUnitAlias('isoWeekday', 'E');
  2373. // PRIORITY
  2374. addUnitPriority('day', 11);
  2375. addUnitPriority('weekday', 11);
  2376. addUnitPriority('isoWeekday', 11);
  2377. // PARSING
  2378. addRegexToken('d', match1to2);
  2379. addRegexToken('e', match1to2);
  2380. addRegexToken('E', match1to2);
  2381. addRegexToken('dd', function (isStrict, locale) {
  2382. return locale.weekdaysMinRegex(isStrict);
  2383. });
  2384. addRegexToken('ddd', function (isStrict, locale) {
  2385. return locale.weekdaysShortRegex(isStrict);
  2386. });
  2387. addRegexToken('dddd', function (isStrict, locale) {
  2388. return locale.weekdaysRegex(isStrict);
  2389. });
  2390. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  2391. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  2392. // if we didn't get a weekday name, mark the date as invalid
  2393. if (weekday != null) {
  2394. week.d = weekday;
  2395. } else {
  2396. getParsingFlags(config).invalidWeekday = input;
  2397. }
  2398. });
  2399. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  2400. week[token] = toInt(input);
  2401. });
  2402. // HELPERS
  2403. function parseWeekday(input, locale) {
  2404. if (typeof input !== 'string') {
  2405. return input;
  2406. }
  2407. if (!isNaN(input)) {
  2408. return parseInt(input, 10);
  2409. }
  2410. input = locale.weekdaysParse(input);
  2411. if (typeof input === 'number') {
  2412. return input;
  2413. }
  2414. return null;
  2415. }
  2416. function parseIsoWeekday(input, locale) {
  2417. if (typeof input === 'string') {
  2418. return locale.weekdaysParse(input) % 7 || 7;
  2419. }
  2420. return isNaN(input) ? null : input;
  2421. }
  2422. // LOCALES
  2423. function shiftWeekdays(ws, n) {
  2424. return ws.slice(n, 7).concat(ws.slice(0, n));
  2425. }
  2426. var defaultLocaleWeekdays =
  2427. 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
  2428. defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  2429. defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  2430. defaultWeekdaysRegex = matchWord,
  2431. defaultWeekdaysShortRegex = matchWord,
  2432. defaultWeekdaysMinRegex = matchWord;
  2433. function localeWeekdays(m, format) {
  2434. var weekdays = isArray(this._weekdays)
  2435. ? this._weekdays
  2436. : this._weekdays[
  2437. m && m !== true && this._weekdays.isFormat.test(format)
  2438. ? 'format'
  2439. : 'standalone'
  2440. ];
  2441. return m === true
  2442. ? shiftWeekdays(weekdays, this._week.dow)
  2443. : m
  2444. ? weekdays[m.day()]
  2445. : weekdays;
  2446. }
  2447. function localeWeekdaysShort(m) {
  2448. return m === true
  2449. ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  2450. : m
  2451. ? this._weekdaysShort[m.day()]
  2452. : this._weekdaysShort;
  2453. }
  2454. function localeWeekdaysMin(m) {
  2455. return m === true
  2456. ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  2457. : m
  2458. ? this._weekdaysMin[m.day()]
  2459. : this._weekdaysMin;
  2460. }
  2461. function handleStrictParse$1(weekdayName, format, strict) {
  2462. var i,
  2463. ii,
  2464. mom,
  2465. llc = weekdayName.toLocaleLowerCase();
  2466. if (!this._weekdaysParse) {
  2467. this._weekdaysParse = [];
  2468. this._shortWeekdaysParse = [];
  2469. this._minWeekdaysParse = [];
  2470. for (i = 0; i < 7; ++i) {
  2471. mom = createUTC([2000, 1]).day(i);
  2472. this._minWeekdaysParse[i] = this.weekdaysMin(
  2473. mom,
  2474. ''
  2475. ).toLocaleLowerCase();
  2476. this._shortWeekdaysParse[i] = this.weekdaysShort(
  2477. mom,
  2478. ''
  2479. ).toLocaleLowerCase();
  2480. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  2481. }
  2482. }
  2483. if (strict) {
  2484. if (format === 'dddd') {
  2485. ii = indexOf.call(this._weekdaysParse, llc);
  2486. return ii !== -1 ? ii : null;
  2487. } else if (format === 'ddd') {
  2488. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2489. return ii !== -1 ? ii : null;
  2490. } else {
  2491. ii = indexOf.call(this._minWeekdaysParse, llc);
  2492. return ii !== -1 ? ii : null;
  2493. }
  2494. } else {
  2495. if (format === 'dddd') {
  2496. ii = indexOf.call(this._weekdaysParse, llc);
  2497. if (ii !== -1) {
  2498. return ii;
  2499. }
  2500. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2501. if (ii !== -1) {
  2502. return ii;
  2503. }
  2504. ii = indexOf.call(this._minWeekdaysParse, llc);
  2505. return ii !== -1 ? ii : null;
  2506. } else if (format === 'ddd') {
  2507. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2508. if (ii !== -1) {
  2509. return ii;
  2510. }
  2511. ii = indexOf.call(this._weekdaysParse, llc);
  2512. if (ii !== -1) {
  2513. return ii;
  2514. }
  2515. ii = indexOf.call(this._minWeekdaysParse, llc);
  2516. return ii !== -1 ? ii : null;
  2517. } else {
  2518. ii = indexOf.call(this._minWeekdaysParse, llc);
  2519. if (ii !== -1) {
  2520. return ii;
  2521. }
  2522. ii = indexOf.call(this._weekdaysParse, llc);
  2523. if (ii !== -1) {
  2524. return ii;
  2525. }
  2526. ii = indexOf.call(this._shortWeekdaysParse, llc);
  2527. return ii !== -1 ? ii : null;
  2528. }
  2529. }
  2530. }
  2531. function localeWeekdaysParse(weekdayName, format, strict) {
  2532. var i, mom, regex;
  2533. if (this._weekdaysParseExact) {
  2534. return handleStrictParse$1.call(this, weekdayName, format, strict);
  2535. }
  2536. if (!this._weekdaysParse) {
  2537. this._weekdaysParse = [];
  2538. this._minWeekdaysParse = [];
  2539. this._shortWeekdaysParse = [];
  2540. this._fullWeekdaysParse = [];
  2541. }
  2542. for (i = 0; i < 7; i++) {
  2543. // make the regex if we don't have it already
  2544. mom = createUTC([2000, 1]).day(i);
  2545. if (strict && !this._fullWeekdaysParse[i]) {
  2546. this._fullWeekdaysParse[i] = new RegExp(
  2547. '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
  2548. 'i'
  2549. );
  2550. this._shortWeekdaysParse[i] = new RegExp(
  2551. '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
  2552. 'i'
  2553. );
  2554. this._minWeekdaysParse[i] = new RegExp(
  2555. '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
  2556. 'i'
  2557. );
  2558. }
  2559. if (!this._weekdaysParse[i]) {
  2560. regex =
  2561. '^' +
  2562. this.weekdays(mom, '') +
  2563. '|^' +
  2564. this.weekdaysShort(mom, '') +
  2565. '|^' +
  2566. this.weekdaysMin(mom, '');
  2567. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  2568. }
  2569. // test the regex
  2570. if (
  2571. strict &&
  2572. format === 'dddd' &&
  2573. this._fullWeekdaysParse[i].test(weekdayName)
  2574. ) {
  2575. return i;
  2576. } else if (
  2577. strict &&
  2578. format === 'ddd' &&
  2579. this._shortWeekdaysParse[i].test(weekdayName)
  2580. ) {
  2581. return i;
  2582. } else if (
  2583. strict &&
  2584. format === 'dd' &&
  2585. this._minWeekdaysParse[i].test(weekdayName)
  2586. ) {
  2587. return i;
  2588. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  2589. return i;
  2590. }
  2591. }
  2592. }
  2593. // MOMENTS
  2594. function getSetDayOfWeek(input) {
  2595. if (!this.isValid()) {
  2596. return input != null ? this : NaN;
  2597. }
  2598. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  2599. if (input != null) {
  2600. input = parseWeekday(input, this.localeData());
  2601. return this.add(input - day, 'd');
  2602. } else {
  2603. return day;
  2604. }
  2605. }
  2606. function getSetLocaleDayOfWeek(input) {
  2607. if (!this.isValid()) {
  2608. return input != null ? this : NaN;
  2609. }
  2610. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  2611. return input == null ? weekday : this.add(input - weekday, 'd');
  2612. }
  2613. function getSetISODayOfWeek(input) {
  2614. if (!this.isValid()) {
  2615. return input != null ? this : NaN;
  2616. }
  2617. // behaves the same as moment#day except
  2618. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  2619. // as a setter, sunday should belong to the previous week.
  2620. if (input != null) {
  2621. var weekday = parseIsoWeekday(input, this.localeData());
  2622. return this.day(this.day() % 7 ? weekday : weekday - 7);
  2623. } else {
  2624. return this.day() || 7;
  2625. }
  2626. }
  2627. function weekdaysRegex(isStrict) {
  2628. if (this._weekdaysParseExact) {
  2629. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2630. computeWeekdaysParse.call(this);
  2631. }
  2632. if (isStrict) {
  2633. return this._weekdaysStrictRegex;
  2634. } else {
  2635. return this._weekdaysRegex;
  2636. }
  2637. } else {
  2638. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2639. this._weekdaysRegex = defaultWeekdaysRegex;
  2640. }
  2641. return this._weekdaysStrictRegex && isStrict
  2642. ? this._weekdaysStrictRegex
  2643. : this._weekdaysRegex;
  2644. }
  2645. }
  2646. function weekdaysShortRegex(isStrict) {
  2647. if (this._weekdaysParseExact) {
  2648. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2649. computeWeekdaysParse.call(this);
  2650. }
  2651. if (isStrict) {
  2652. return this._weekdaysShortStrictRegex;
  2653. } else {
  2654. return this._weekdaysShortRegex;
  2655. }
  2656. } else {
  2657. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  2658. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  2659. }
  2660. return this._weekdaysShortStrictRegex && isStrict
  2661. ? this._weekdaysShortStrictRegex
  2662. : this._weekdaysShortRegex;
  2663. }
  2664. }
  2665. function weekdaysMinRegex(isStrict) {
  2666. if (this._weekdaysParseExact) {
  2667. if (!hasOwnProp(this, '_weekdaysRegex')) {
  2668. computeWeekdaysParse.call(this);
  2669. }
  2670. if (isStrict) {
  2671. return this._weekdaysMinStrictRegex;
  2672. } else {
  2673. return this._weekdaysMinRegex;
  2674. }
  2675. } else {
  2676. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  2677. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  2678. }
  2679. return this._weekdaysMinStrictRegex && isStrict
  2680. ? this._weekdaysMinStrictRegex
  2681. : this._weekdaysMinRegex;
  2682. }
  2683. }
  2684. function computeWeekdaysParse() {
  2685. function cmpLenRev(a, b) {
  2686. return b.length - a.length;
  2687. }
  2688. var minPieces = [],
  2689. shortPieces = [],
  2690. longPieces = [],
  2691. mixedPieces = [],
  2692. i,
  2693. mom,
  2694. minp,
  2695. shortp,
  2696. longp;
  2697. for (i = 0; i < 7; i++) {
  2698. // make the regex if we don't have it already
  2699. mom = createUTC([2000, 1]).day(i);
  2700. minp = regexEscape(this.weekdaysMin(mom, ''));
  2701. shortp = regexEscape(this.weekdaysShort(mom, ''));
  2702. longp = regexEscape(this.weekdays(mom, ''));
  2703. minPieces.push(minp);
  2704. shortPieces.push(shortp);
  2705. longPieces.push(longp);
  2706. mixedPieces.push(minp);
  2707. mixedPieces.push(shortp);
  2708. mixedPieces.push(longp);
  2709. }
  2710. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  2711. // will match the longer piece.
  2712. minPieces.sort(cmpLenRev);
  2713. shortPieces.sort(cmpLenRev);
  2714. longPieces.sort(cmpLenRev);
  2715. mixedPieces.sort(cmpLenRev);
  2716. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  2717. this._weekdaysShortRegex = this._weekdaysRegex;
  2718. this._weekdaysMinRegex = this._weekdaysRegex;
  2719. this._weekdaysStrictRegex = new RegExp(
  2720. '^(' + longPieces.join('|') + ')',
  2721. 'i'
  2722. );
  2723. this._weekdaysShortStrictRegex = new RegExp(
  2724. '^(' + shortPieces.join('|') + ')',
  2725. 'i'
  2726. );
  2727. this._weekdaysMinStrictRegex = new RegExp(
  2728. '^(' + minPieces.join('|') + ')',
  2729. 'i'
  2730. );
  2731. }
  2732. // FORMATTING
  2733. function hFormat() {
  2734. return this.hours() % 12 || 12;
  2735. }
  2736. function kFormat() {
  2737. return this.hours() || 24;
  2738. }
  2739. addFormatToken('H', ['HH', 2], 0, 'hour');
  2740. addFormatToken('h', ['hh', 2], 0, hFormat);
  2741. addFormatToken('k', ['kk', 2], 0, kFormat);
  2742. addFormatToken('hmm', 0, 0, function () {
  2743. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  2744. });
  2745. addFormatToken('hmmss', 0, 0, function () {
  2746. return (
  2747. '' +
  2748. hFormat.apply(this) +
  2749. zeroFill(this.minutes(), 2) +
  2750. zeroFill(this.seconds(), 2)
  2751. );
  2752. });
  2753. addFormatToken('Hmm', 0, 0, function () {
  2754. return '' + this.hours() + zeroFill(this.minutes(), 2);
  2755. });
  2756. addFormatToken('Hmmss', 0, 0, function () {
  2757. return (
  2758. '' +
  2759. this.hours() +
  2760. zeroFill(this.minutes(), 2) +
  2761. zeroFill(this.seconds(), 2)
  2762. );
  2763. });
  2764. function meridiem(token, lowercase) {
  2765. addFormatToken(token, 0, 0, function () {
  2766. return this.localeData().meridiem(
  2767. this.hours(),
  2768. this.minutes(),
  2769. lowercase
  2770. );
  2771. });
  2772. }
  2773. meridiem('a', true);
  2774. meridiem('A', false);
  2775. // ALIASES
  2776. addUnitAlias('hour', 'h');
  2777. // PRIORITY
  2778. addUnitPriority('hour', 13);
  2779. // PARSING
  2780. function matchMeridiem(isStrict, locale) {
  2781. return locale._meridiemParse;
  2782. }
  2783. addRegexToken('a', matchMeridiem);
  2784. addRegexToken('A', matchMeridiem);
  2785. addRegexToken('H', match1to2);
  2786. addRegexToken('h', match1to2);
  2787. addRegexToken('k', match1to2);
  2788. addRegexToken('HH', match1to2, match2);
  2789. addRegexToken('hh', match1to2, match2);
  2790. addRegexToken('kk', match1to2, match2);
  2791. addRegexToken('hmm', match3to4);
  2792. addRegexToken('hmmss', match5to6);
  2793. addRegexToken('Hmm', match3to4);
  2794. addRegexToken('Hmmss', match5to6);
  2795. addParseToken(['H', 'HH'], HOUR);
  2796. addParseToken(['k', 'kk'], function (input, array, config) {
  2797. var kInput = toInt(input);
  2798. array[HOUR] = kInput === 24 ? 0 : kInput;
  2799. });
  2800. addParseToken(['a', 'A'], function (input, array, config) {
  2801. config._isPm = config._locale.isPM(input);
  2802. config._meridiem = input;
  2803. });
  2804. addParseToken(['h', 'hh'], function (input, array, config) {
  2805. array[HOUR] = toInt(input);
  2806. getParsingFlags(config).bigHour = true;
  2807. });
  2808. addParseToken('hmm', function (input, array, config) {
  2809. var pos = input.length - 2;
  2810. array[HOUR] = toInt(input.substr(0, pos));
  2811. array[MINUTE] = toInt(input.substr(pos));
  2812. getParsingFlags(config).bigHour = true;
  2813. });
  2814. addParseToken('hmmss', function (input, array, config) {
  2815. var pos1 = input.length - 4,
  2816. pos2 = input.length - 2;
  2817. array[HOUR] = toInt(input.substr(0, pos1));
  2818. array[MINUTE] = toInt(input.substr(pos1, 2));
  2819. array[SECOND] = toInt(input.substr(pos2));
  2820. getParsingFlags(config).bigHour = true;
  2821. });
  2822. addParseToken('Hmm', function (input, array, config) {
  2823. var pos = input.length - 2;
  2824. array[HOUR] = toInt(input.substr(0, pos));
  2825. array[MINUTE] = toInt(input.substr(pos));
  2826. });
  2827. addParseToken('Hmmss', function (input, array, config) {
  2828. var pos1 = input.length - 4,
  2829. pos2 = input.length - 2;
  2830. array[HOUR] = toInt(input.substr(0, pos1));
  2831. array[MINUTE] = toInt(input.substr(pos1, 2));
  2832. array[SECOND] = toInt(input.substr(pos2));
  2833. });
  2834. // LOCALES
  2835. function localeIsPM(input) {
  2836. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  2837. // Using charAt should be more compatible.
  2838. return (input + '').toLowerCase().charAt(0) === 'p';
  2839. }
  2840. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
  2841. // Setting the hour should keep the time, because the user explicitly
  2842. // specified which hour they want. So trying to maintain the same hour (in
  2843. // a new timezone) makes sense. Adding/subtracting hours does not follow
  2844. // this rule.
  2845. getSetHour = makeGetSet('Hours', true);
  2846. function localeMeridiem(hours, minutes, isLower) {
  2847. if (hours > 11) {
  2848. return isLower ? 'pm' : 'PM';
  2849. } else {
  2850. return isLower ? 'am' : 'AM';
  2851. }
  2852. }
  2853. var baseConfig = {
  2854. calendar: defaultCalendar,
  2855. longDateFormat: defaultLongDateFormat,
  2856. invalidDate: defaultInvalidDate,
  2857. ordinal: defaultOrdinal,
  2858. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  2859. relativeTime: defaultRelativeTime,
  2860. months: defaultLocaleMonths,
  2861. monthsShort: defaultLocaleMonthsShort,
  2862. week: defaultLocaleWeek,
  2863. weekdays: defaultLocaleWeekdays,
  2864. weekdaysMin: defaultLocaleWeekdaysMin,
  2865. weekdaysShort: defaultLocaleWeekdaysShort,
  2866. meridiemParse: defaultLocaleMeridiemParse,
  2867. };
  2868. // internal storage for locale config files
  2869. var locales = {},
  2870. localeFamilies = {},
  2871. globalLocale;
  2872. function commonPrefix(arr1, arr2) {
  2873. var i,
  2874. minl = Math.min(arr1.length, arr2.length);
  2875. for (i = 0; i < minl; i += 1) {
  2876. if (arr1[i] !== arr2[i]) {
  2877. return i;
  2878. }
  2879. }
  2880. return minl;
  2881. }
  2882. function normalizeLocale(key) {
  2883. return key ? key.toLowerCase().replace('_', '-') : key;
  2884. }
  2885. // pick the locale from the array
  2886. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  2887. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  2888. function chooseLocale(names) {
  2889. var i = 0,
  2890. j,
  2891. next,
  2892. locale,
  2893. split;
  2894. while (i < names.length) {
  2895. split = normalizeLocale(names[i]).split('-');
  2896. j = split.length;
  2897. next = normalizeLocale(names[i + 1]);
  2898. next = next ? next.split('-') : null;
  2899. while (j > 0) {
  2900. locale = loadLocale(split.slice(0, j).join('-'));
  2901. if (locale) {
  2902. return locale;
  2903. }
  2904. if (
  2905. next &&
  2906. next.length >= j &&
  2907. commonPrefix(split, next) >= j - 1
  2908. ) {
  2909. //the next array item is better than a shallower substring of this one
  2910. break;
  2911. }
  2912. j--;
  2913. }
  2914. i++;
  2915. }
  2916. return globalLocale;
  2917. }
  2918. function isLocaleNameSane(name) {
  2919. // Prevent names that look like filesystem paths, i.e contain '/' or '\'
  2920. return name.match('^[^/\\\\]*$') != null;
  2921. }
  2922. function loadLocale(name) {
  2923. var oldLocale = null,
  2924. aliasedRequire;
  2925. // TODO: Find a better way to register and load all the locales in Node
  2926. if (
  2927. locales[name] === undefined &&
  2928. 'object' !== 'undefined' &&
  2929. module &&
  2930. module.exports &&
  2931. isLocaleNameSane(name)
  2932. ) {
  2933. try {
  2934. oldLocale = globalLocale._abbr;
  2935. aliasedRequire = commonjsRequire;
  2936. aliasedRequire('./locale/' + name);
  2937. getSetGlobalLocale(oldLocale);
  2938. } catch (e) {
  2939. // mark as not found to avoid repeating expensive file require call causing high CPU
  2940. // when trying to find en-US, en_US, en-us for every format call
  2941. locales[name] = null; // null means not found
  2942. }
  2943. }
  2944. return locales[name];
  2945. }
  2946. // This function will load locale and then set the global locale. If
  2947. // no arguments are passed in, it will simply return the current global
  2948. // locale key.
  2949. function getSetGlobalLocale(key, values) {
  2950. var data;
  2951. if (key) {
  2952. if (isUndefined(values)) {
  2953. data = getLocale(key);
  2954. } else {
  2955. data = defineLocale(key, values);
  2956. }
  2957. if (data) {
  2958. // moment.duration._locale = moment._locale = data;
  2959. globalLocale = data;
  2960. } else {
  2961. if (typeof console !== 'undefined' && console.warn) {
  2962. //warn user if arguments are passed but the locale could not be set
  2963. console.warn(
  2964. 'Locale ' + key + ' not found. Did you forget to load it?'
  2965. );
  2966. }
  2967. }
  2968. }
  2969. return globalLocale._abbr;
  2970. }
  2971. function defineLocale(name, config) {
  2972. if (config !== null) {
  2973. var locale,
  2974. parentConfig = baseConfig;
  2975. config.abbr = name;
  2976. if (locales[name] != null) {
  2977. deprecateSimple(
  2978. 'defineLocaleOverride',
  2979. 'use moment.updateLocale(localeName, config) to change ' +
  2980. 'an existing locale. moment.defineLocale(localeName, ' +
  2981. 'config) should only be used for creating a new locale ' +
  2982. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
  2983. );
  2984. parentConfig = locales[name]._config;
  2985. } else if (config.parentLocale != null) {
  2986. if (locales[config.parentLocale] != null) {
  2987. parentConfig = locales[config.parentLocale]._config;
  2988. } else {
  2989. locale = loadLocale(config.parentLocale);
  2990. if (locale != null) {
  2991. parentConfig = locale._config;
  2992. } else {
  2993. if (!localeFamilies[config.parentLocale]) {
  2994. localeFamilies[config.parentLocale] = [];
  2995. }
  2996. localeFamilies[config.parentLocale].push({
  2997. name: name,
  2998. config: config,
  2999. });
  3000. return null;
  3001. }
  3002. }
  3003. }
  3004. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  3005. if (localeFamilies[name]) {
  3006. localeFamilies[name].forEach(function (x) {
  3007. defineLocale(x.name, x.config);
  3008. });
  3009. }
  3010. // backwards compat for now: also set the locale
  3011. // make sure we set the locale AFTER all child locales have been
  3012. // created, so we won't end up with the child locale set.
  3013. getSetGlobalLocale(name);
  3014. return locales[name];
  3015. } else {
  3016. // useful for testing
  3017. delete locales[name];
  3018. return null;
  3019. }
  3020. }
  3021. function updateLocale(name, config) {
  3022. if (config != null) {
  3023. var locale,
  3024. tmpLocale,
  3025. parentConfig = baseConfig;
  3026. if (locales[name] != null && locales[name].parentLocale != null) {
  3027. // Update existing child locale in-place to avoid memory-leaks
  3028. locales[name].set(mergeConfigs(locales[name]._config, config));
  3029. } else {
  3030. // MERGE
  3031. tmpLocale = loadLocale(name);
  3032. if (tmpLocale != null) {
  3033. parentConfig = tmpLocale._config;
  3034. }
  3035. config = mergeConfigs(parentConfig, config);
  3036. if (tmpLocale == null) {
  3037. // updateLocale is called for creating a new locale
  3038. // Set abbr so it will have a name (getters return
  3039. // undefined otherwise).
  3040. config.abbr = name;
  3041. }
  3042. locale = new Locale(config);
  3043. locale.parentLocale = locales[name];
  3044. locales[name] = locale;
  3045. }
  3046. // backwards compat for now: also set the locale
  3047. getSetGlobalLocale(name);
  3048. } else {
  3049. // pass null for config to unupdate, useful for tests
  3050. if (locales[name] != null) {
  3051. if (locales[name].parentLocale != null) {
  3052. locales[name] = locales[name].parentLocale;
  3053. if (name === getSetGlobalLocale()) {
  3054. getSetGlobalLocale(name);
  3055. }
  3056. } else if (locales[name] != null) {
  3057. delete locales[name];
  3058. }
  3059. }
  3060. }
  3061. return locales[name];
  3062. }
  3063. // returns locale data
  3064. function getLocale(key) {
  3065. var locale;
  3066. if (key && key._locale && key._locale._abbr) {
  3067. key = key._locale._abbr;
  3068. }
  3069. if (!key) {
  3070. return globalLocale;
  3071. }
  3072. if (!isArray(key)) {
  3073. //short-circuit everything else
  3074. locale = loadLocale(key);
  3075. if (locale) {
  3076. return locale;
  3077. }
  3078. key = [key];
  3079. }
  3080. return chooseLocale(key);
  3081. }
  3082. function listLocales() {
  3083. return keys(locales);
  3084. }
  3085. function checkOverflow(m) {
  3086. var overflow,
  3087. a = m._a;
  3088. if (a && getParsingFlags(m).overflow === -2) {
  3089. overflow =
  3090. a[MONTH] < 0 || a[MONTH] > 11
  3091. ? MONTH
  3092. : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
  3093. ? DATE
  3094. : a[HOUR] < 0 ||
  3095. a[HOUR] > 24 ||
  3096. (a[HOUR] === 24 &&
  3097. (a[MINUTE] !== 0 ||
  3098. a[SECOND] !== 0 ||
  3099. a[MILLISECOND] !== 0))
  3100. ? HOUR
  3101. : a[MINUTE] < 0 || a[MINUTE] > 59
  3102. ? MINUTE
  3103. : a[SECOND] < 0 || a[SECOND] > 59
  3104. ? SECOND
  3105. : a[MILLISECOND] < 0 || a[MILLISECOND] > 999
  3106. ? MILLISECOND
  3107. : -1;
  3108. if (
  3109. getParsingFlags(m)._overflowDayOfYear &&
  3110. (overflow < YEAR || overflow > DATE)
  3111. ) {
  3112. overflow = DATE;
  3113. }
  3114. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  3115. overflow = WEEK;
  3116. }
  3117. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  3118. overflow = WEEKDAY;
  3119. }
  3120. getParsingFlags(m).overflow = overflow;
  3121. }
  3122. return m;
  3123. }
  3124. // iso 8601 regex
  3125. // 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)
  3126. var extendedIsoRegex =
  3127. /^\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)?)?$/,
  3128. basicIsoRegex =
  3129. /^\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)?)?$/,
  3130. tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
  3131. isoDates = [
  3132. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  3133. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  3134. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  3135. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  3136. ['YYYY-DDD', /\d{4}-\d{3}/],
  3137. ['YYYY-MM', /\d{4}-\d\d/, false],
  3138. ['YYYYYYMMDD', /[+-]\d{10}/],
  3139. ['YYYYMMDD', /\d{8}/],
  3140. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  3141. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  3142. ['YYYYDDD', /\d{7}/],
  3143. ['YYYYMM', /\d{6}/, false],
  3144. ['YYYY', /\d{4}/, false],
  3145. ],
  3146. // iso time formats and regexes
  3147. isoTimes = [
  3148. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  3149. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  3150. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  3151. ['HH:mm', /\d\d:\d\d/],
  3152. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  3153. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  3154. ['HHmmss', /\d\d\d\d\d\d/],
  3155. ['HHmm', /\d\d\d\d/],
  3156. ['HH', /\d\d/],
  3157. ],
  3158. aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
  3159. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  3160. rfc2822 =
  3161. /^(?:(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}))$/,
  3162. obsOffsets = {
  3163. UT: 0,
  3164. GMT: 0,
  3165. EDT: -4 * 60,
  3166. EST: -5 * 60,
  3167. CDT: -5 * 60,
  3168. CST: -6 * 60,
  3169. MDT: -6 * 60,
  3170. MST: -7 * 60,
  3171. PDT: -7 * 60,
  3172. PST: -8 * 60,
  3173. };
  3174. // date from iso format
  3175. function configFromISO(config) {
  3176. var i,
  3177. l,
  3178. string = config._i,
  3179. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  3180. allowTime,
  3181. dateFormat,
  3182. timeFormat,
  3183. tzFormat,
  3184. isoDatesLen = isoDates.length,
  3185. isoTimesLen = isoTimes.length;
  3186. if (match) {
  3187. getParsingFlags(config).iso = true;
  3188. for (i = 0, l = isoDatesLen; i < l; i++) {
  3189. if (isoDates[i][1].exec(match[1])) {
  3190. dateFormat = isoDates[i][0];
  3191. allowTime = isoDates[i][2] !== false;
  3192. break;
  3193. }
  3194. }
  3195. if (dateFormat == null) {
  3196. config._isValid = false;
  3197. return;
  3198. }
  3199. if (match[3]) {
  3200. for (i = 0, l = isoTimesLen; i < l; i++) {
  3201. if (isoTimes[i][1].exec(match[3])) {
  3202. // match[2] should be 'T' or space
  3203. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  3204. break;
  3205. }
  3206. }
  3207. if (timeFormat == null) {
  3208. config._isValid = false;
  3209. return;
  3210. }
  3211. }
  3212. if (!allowTime && timeFormat != null) {
  3213. config._isValid = false;
  3214. return;
  3215. }
  3216. if (match[4]) {
  3217. if (tzRegex.exec(match[4])) {
  3218. tzFormat = 'Z';
  3219. } else {
  3220. config._isValid = false;
  3221. return;
  3222. }
  3223. }
  3224. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  3225. configFromStringAndFormat(config);
  3226. } else {
  3227. config._isValid = false;
  3228. }
  3229. }
  3230. function extractFromRFC2822Strings(
  3231. yearStr,
  3232. monthStr,
  3233. dayStr,
  3234. hourStr,
  3235. minuteStr,
  3236. secondStr
  3237. ) {
  3238. var result = [
  3239. untruncateYear(yearStr),
  3240. defaultLocaleMonthsShort.indexOf(monthStr),
  3241. parseInt(dayStr, 10),
  3242. parseInt(hourStr, 10),
  3243. parseInt(minuteStr, 10),
  3244. ];
  3245. if (secondStr) {
  3246. result.push(parseInt(secondStr, 10));
  3247. }
  3248. return result;
  3249. }
  3250. function untruncateYear(yearStr) {
  3251. var year = parseInt(yearStr, 10);
  3252. if (year <= 49) {
  3253. return 2000 + year;
  3254. } else if (year <= 999) {
  3255. return 1900 + year;
  3256. }
  3257. return year;
  3258. }
  3259. function preprocessRFC2822(s) {
  3260. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  3261. return s
  3262. .replace(/\([^()]*\)|[\n\t]/g, ' ')
  3263. .replace(/(\s\s+)/g, ' ')
  3264. .replace(/^\s\s*/, '')
  3265. .replace(/\s\s*$/, '');
  3266. }
  3267. function checkWeekday(weekdayStr, parsedInput, config) {
  3268. if (weekdayStr) {
  3269. // TODO: Replace the vanilla JS Date object with an independent day-of-week check.
  3270. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  3271. weekdayActual = new Date(
  3272. parsedInput[0],
  3273. parsedInput[1],
  3274. parsedInput[2]
  3275. ).getDay();
  3276. if (weekdayProvided !== weekdayActual) {
  3277. getParsingFlags(config).weekdayMismatch = true;
  3278. config._isValid = false;
  3279. return false;
  3280. }
  3281. }
  3282. return true;
  3283. }
  3284. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  3285. if (obsOffset) {
  3286. return obsOffsets[obsOffset];
  3287. } else if (militaryOffset) {
  3288. // the only allowed military tz is Z
  3289. return 0;
  3290. } else {
  3291. var hm = parseInt(numOffset, 10),
  3292. m = hm % 100,
  3293. h = (hm - m) / 100;
  3294. return h * 60 + m;
  3295. }
  3296. }
  3297. // date and time from ref 2822 format
  3298. function configFromRFC2822(config) {
  3299. var match = rfc2822.exec(preprocessRFC2822(config._i)),
  3300. parsedArray;
  3301. if (match) {
  3302. parsedArray = extractFromRFC2822Strings(
  3303. match[4],
  3304. match[3],
  3305. match[2],
  3306. match[5],
  3307. match[6],
  3308. match[7]
  3309. );
  3310. if (!checkWeekday(match[1], parsedArray, config)) {
  3311. return;
  3312. }
  3313. config._a = parsedArray;
  3314. config._tzm = calculateOffset(match[8], match[9], match[10]);
  3315. config._d = createUTCDate.apply(null, config._a);
  3316. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  3317. getParsingFlags(config).rfc2822 = true;
  3318. } else {
  3319. config._isValid = false;
  3320. }
  3321. }
  3322. // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
  3323. function configFromString(config) {
  3324. var matched = aspNetJsonRegex.exec(config._i);
  3325. if (matched !== null) {
  3326. config._d = new Date(+matched[1]);
  3327. return;
  3328. }
  3329. configFromISO(config);
  3330. if (config._isValid === false) {
  3331. delete config._isValid;
  3332. } else {
  3333. return;
  3334. }
  3335. configFromRFC2822(config);
  3336. if (config._isValid === false) {
  3337. delete config._isValid;
  3338. } else {
  3339. return;
  3340. }
  3341. if (config._strict) {
  3342. config._isValid = false;
  3343. } else {
  3344. // Final attempt, use Input Fallback
  3345. hooks.createFromInputFallback(config);
  3346. }
  3347. }
  3348. hooks.createFromInputFallback = deprecate(
  3349. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  3350. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  3351. 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  3352. function (config) {
  3353. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  3354. }
  3355. );
  3356. // Pick the first defined of two or three arguments.
  3357. function defaults(a, b, c) {
  3358. if (a != null) {
  3359. return a;
  3360. }
  3361. if (b != null) {
  3362. return b;
  3363. }
  3364. return c;
  3365. }
  3366. function currentDateArray(config) {
  3367. // hooks is actually the exported moment object
  3368. var nowValue = new Date(hooks.now());
  3369. if (config._useUTC) {
  3370. return [
  3371. nowValue.getUTCFullYear(),
  3372. nowValue.getUTCMonth(),
  3373. nowValue.getUTCDate(),
  3374. ];
  3375. }
  3376. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  3377. }
  3378. // convert an array to a date.
  3379. // the array should mirror the parameters below
  3380. // note: all values past the year are optional and will default to the lowest possible value.
  3381. // [year, month, day , hour, minute, second, millisecond]
  3382. function configFromArray(config) {
  3383. var i,
  3384. date,
  3385. input = [],
  3386. currentDate,
  3387. expectedWeekday,
  3388. yearToUse;
  3389. if (config._d) {
  3390. return;
  3391. }
  3392. currentDate = currentDateArray(config);
  3393. //compute day of the year from weeks and weekdays
  3394. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  3395. dayOfYearFromWeekInfo(config);
  3396. }
  3397. //if the day of the year is set, figure out what it is
  3398. if (config._dayOfYear != null) {
  3399. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  3400. if (
  3401. config._dayOfYear > daysInYear(yearToUse) ||
  3402. config._dayOfYear === 0
  3403. ) {
  3404. getParsingFlags(config)._overflowDayOfYear = true;
  3405. }
  3406. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  3407. config._a[MONTH] = date.getUTCMonth();
  3408. config._a[DATE] = date.getUTCDate();
  3409. }
  3410. // Default to current date.
  3411. // * if no year, month, day of month are given, default to today
  3412. // * if day of month is given, default month and year
  3413. // * if month is given, default only year
  3414. // * if year is given, don't default anything
  3415. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  3416. config._a[i] = input[i] = currentDate[i];
  3417. }
  3418. // Zero out whatever was not defaulted, including time
  3419. for (; i < 7; i++) {
  3420. config._a[i] = input[i] =
  3421. config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
  3422. }
  3423. // Check for 24:00:00.000
  3424. if (
  3425. config._a[HOUR] === 24 &&
  3426. config._a[MINUTE] === 0 &&
  3427. config._a[SECOND] === 0 &&
  3428. config._a[MILLISECOND] === 0
  3429. ) {
  3430. config._nextDay = true;
  3431. config._a[HOUR] = 0;
  3432. }
  3433. config._d = (config._useUTC ? createUTCDate : createDate).apply(
  3434. null,
  3435. input
  3436. );
  3437. expectedWeekday = config._useUTC
  3438. ? config._d.getUTCDay()
  3439. : config._d.getDay();
  3440. // Apply timezone offset from input. The actual utcOffset can be changed
  3441. // with parseZone.
  3442. if (config._tzm != null) {
  3443. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  3444. }
  3445. if (config._nextDay) {
  3446. config._a[HOUR] = 24;
  3447. }
  3448. // check for mismatching day of week
  3449. if (
  3450. config._w &&
  3451. typeof config._w.d !== 'undefined' &&
  3452. config._w.d !== expectedWeekday
  3453. ) {
  3454. getParsingFlags(config).weekdayMismatch = true;
  3455. }
  3456. }
  3457. function dayOfYearFromWeekInfo(config) {
  3458. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
  3459. w = config._w;
  3460. if (w.GG != null || w.W != null || w.E != null) {
  3461. dow = 1;
  3462. doy = 4;
  3463. // TODO: We need to take the current isoWeekYear, but that depends on
  3464. // how we interpret now (local, utc, fixed offset). So create
  3465. // a now version of current config (take local/utc/offset flags, and
  3466. // create now).
  3467. weekYear = defaults(
  3468. w.GG,
  3469. config._a[YEAR],
  3470. weekOfYear(createLocal(), 1, 4).year
  3471. );
  3472. week = defaults(w.W, 1);
  3473. weekday = defaults(w.E, 1);
  3474. if (weekday < 1 || weekday > 7) {
  3475. weekdayOverflow = true;
  3476. }
  3477. } else {
  3478. dow = config._locale._week.dow;
  3479. doy = config._locale._week.doy;
  3480. curWeek = weekOfYear(createLocal(), dow, doy);
  3481. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  3482. // Default to current week.
  3483. week = defaults(w.w, curWeek.week);
  3484. if (w.d != null) {
  3485. // weekday -- low day numbers are considered next week
  3486. weekday = w.d;
  3487. if (weekday < 0 || weekday > 6) {
  3488. weekdayOverflow = true;
  3489. }
  3490. } else if (w.e != null) {
  3491. // local weekday -- counting starts from beginning of week
  3492. weekday = w.e + dow;
  3493. if (w.e < 0 || w.e > 6) {
  3494. weekdayOverflow = true;
  3495. }
  3496. } else {
  3497. // default to beginning of week
  3498. weekday = dow;
  3499. }
  3500. }
  3501. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  3502. getParsingFlags(config)._overflowWeeks = true;
  3503. } else if (weekdayOverflow != null) {
  3504. getParsingFlags(config)._overflowWeekday = true;
  3505. } else {
  3506. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  3507. config._a[YEAR] = temp.year;
  3508. config._dayOfYear = temp.dayOfYear;
  3509. }
  3510. }
  3511. // constant that refers to the ISO standard
  3512. hooks.ISO_8601 = function () {};
  3513. // constant that refers to the RFC 2822 form
  3514. hooks.RFC_2822 = function () {};
  3515. // date from string and format string
  3516. function configFromStringAndFormat(config) {
  3517. // TODO: Move this to another part of the creation flow to prevent circular deps
  3518. if (config._f === hooks.ISO_8601) {
  3519. configFromISO(config);
  3520. return;
  3521. }
  3522. if (config._f === hooks.RFC_2822) {
  3523. configFromRFC2822(config);
  3524. return;
  3525. }
  3526. config._a = [];
  3527. getParsingFlags(config).empty = true;
  3528. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  3529. var string = '' + config._i,
  3530. i,
  3531. parsedInput,
  3532. tokens,
  3533. token,
  3534. skipped,
  3535. stringLength = string.length,
  3536. totalParsedInputLength = 0,
  3537. era,
  3538. tokenLen;
  3539. tokens =
  3540. expandFormat(config._f, config._locale).match(formattingTokens) || [];
  3541. tokenLen = tokens.length;
  3542. for (i = 0; i < tokenLen; i++) {
  3543. token = tokens[i];
  3544. parsedInput = (string.match(getParseRegexForToken(token, config)) ||
  3545. [])[0];
  3546. if (parsedInput) {
  3547. skipped = string.substr(0, string.indexOf(parsedInput));
  3548. if (skipped.length > 0) {
  3549. getParsingFlags(config).unusedInput.push(skipped);
  3550. }
  3551. string = string.slice(
  3552. string.indexOf(parsedInput) + parsedInput.length
  3553. );
  3554. totalParsedInputLength += parsedInput.length;
  3555. }
  3556. // don't parse if it's not a known token
  3557. if (formatTokenFunctions[token]) {
  3558. if (parsedInput) {
  3559. getParsingFlags(config).empty = false;
  3560. } else {
  3561. getParsingFlags(config).unusedTokens.push(token);
  3562. }
  3563. addTimeToArrayFromToken(token, parsedInput, config);
  3564. } else if (config._strict && !parsedInput) {
  3565. getParsingFlags(config).unusedTokens.push(token);
  3566. }
  3567. }
  3568. // add remaining unparsed input length to the string
  3569. getParsingFlags(config).charsLeftOver =
  3570. stringLength - totalParsedInputLength;
  3571. if (string.length > 0) {
  3572. getParsingFlags(config).unusedInput.push(string);
  3573. }
  3574. // clear _12h flag if hour is <= 12
  3575. if (
  3576. config._a[HOUR] <= 12 &&
  3577. getParsingFlags(config).bigHour === true &&
  3578. config._a[HOUR] > 0
  3579. ) {
  3580. getParsingFlags(config).bigHour = undefined;
  3581. }
  3582. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  3583. getParsingFlags(config).meridiem = config._meridiem;
  3584. // handle meridiem
  3585. config._a[HOUR] = meridiemFixWrap(
  3586. config._locale,
  3587. config._a[HOUR],
  3588. config._meridiem
  3589. );
  3590. // handle era
  3591. era = getParsingFlags(config).era;
  3592. if (era !== null) {
  3593. config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
  3594. }
  3595. configFromArray(config);
  3596. checkOverflow(config);
  3597. }
  3598. function meridiemFixWrap(locale, hour, meridiem) {
  3599. var isPm;
  3600. if (meridiem == null) {
  3601. // nothing to do
  3602. return hour;
  3603. }
  3604. if (locale.meridiemHour != null) {
  3605. return locale.meridiemHour(hour, meridiem);
  3606. } else if (locale.isPM != null) {
  3607. // Fallback
  3608. isPm = locale.isPM(meridiem);
  3609. if (isPm && hour < 12) {
  3610. hour += 12;
  3611. }
  3612. if (!isPm && hour === 12) {
  3613. hour = 0;
  3614. }
  3615. return hour;
  3616. } else {
  3617. // this is not supposed to happen
  3618. return hour;
  3619. }
  3620. }
  3621. // date from string and array of format strings
  3622. function configFromStringAndArray(config) {
  3623. var tempConfig,
  3624. bestMoment,
  3625. scoreToBeat,
  3626. i,
  3627. currentScore,
  3628. validFormatFound,
  3629. bestFormatIsValid = false,
  3630. configfLen = config._f.length;
  3631. if (configfLen === 0) {
  3632. getParsingFlags(config).invalidFormat = true;
  3633. config._d = new Date(NaN);
  3634. return;
  3635. }
  3636. for (i = 0; i < configfLen; i++) {
  3637. currentScore = 0;
  3638. validFormatFound = false;
  3639. tempConfig = copyConfig({}, config);
  3640. if (config._useUTC != null) {
  3641. tempConfig._useUTC = config._useUTC;
  3642. }
  3643. tempConfig._f = config._f[i];
  3644. configFromStringAndFormat(tempConfig);
  3645. if (isValid(tempConfig)) {
  3646. validFormatFound = true;
  3647. }
  3648. // if there is any input that was not parsed add a penalty for that format
  3649. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  3650. //or tokens
  3651. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  3652. getParsingFlags(tempConfig).score = currentScore;
  3653. if (!bestFormatIsValid) {
  3654. if (
  3655. scoreToBeat == null ||
  3656. currentScore < scoreToBeat ||
  3657. validFormatFound
  3658. ) {
  3659. scoreToBeat = currentScore;
  3660. bestMoment = tempConfig;
  3661. if (validFormatFound) {
  3662. bestFormatIsValid = true;
  3663. }
  3664. }
  3665. } else {
  3666. if (currentScore < scoreToBeat) {
  3667. scoreToBeat = currentScore;
  3668. bestMoment = tempConfig;
  3669. }
  3670. }
  3671. }
  3672. extend(config, bestMoment || tempConfig);
  3673. }
  3674. function configFromObject(config) {
  3675. if (config._d) {
  3676. return;
  3677. }
  3678. var i = normalizeObjectUnits(config._i),
  3679. dayOrDate = i.day === undefined ? i.date : i.day;
  3680. config._a = map(
  3681. [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
  3682. function (obj) {
  3683. return obj && parseInt(obj, 10);
  3684. }
  3685. );
  3686. configFromArray(config);
  3687. }
  3688. function createFromConfig(config) {
  3689. var res = new Moment(checkOverflow(prepareConfig(config)));
  3690. if (res._nextDay) {
  3691. // Adding is smart enough around DST
  3692. res.add(1, 'd');
  3693. res._nextDay = undefined;
  3694. }
  3695. return res;
  3696. }
  3697. function prepareConfig(config) {
  3698. var input = config._i,
  3699. format = config._f;
  3700. config._locale = config._locale || getLocale(config._l);
  3701. if (input === null || (format === undefined && input === '')) {
  3702. return createInvalid({ nullInput: true });
  3703. }
  3704. if (typeof input === 'string') {
  3705. config._i = input = config._locale.preparse(input);
  3706. }
  3707. if (isMoment(input)) {
  3708. return new Moment(checkOverflow(input));
  3709. } else if (isDate(input)) {
  3710. config._d = input;
  3711. } else if (isArray(format)) {
  3712. configFromStringAndArray(config);
  3713. } else if (format) {
  3714. configFromStringAndFormat(config);
  3715. } else {
  3716. configFromInput(config);
  3717. }
  3718. if (!isValid(config)) {
  3719. config._d = null;
  3720. }
  3721. return config;
  3722. }
  3723. function configFromInput(config) {
  3724. var input = config._i;
  3725. if (isUndefined(input)) {
  3726. config._d = new Date(hooks.now());
  3727. } else if (isDate(input)) {
  3728. config._d = new Date(input.valueOf());
  3729. } else if (typeof input === 'string') {
  3730. configFromString(config);
  3731. } else if (isArray(input)) {
  3732. config._a = map(input.slice(0), function (obj) {
  3733. return parseInt(obj, 10);
  3734. });
  3735. configFromArray(config);
  3736. } else if (isObject(input)) {
  3737. configFromObject(config);
  3738. } else if (isNumber(input)) {
  3739. // from milliseconds
  3740. config._d = new Date(input);
  3741. } else {
  3742. hooks.createFromInputFallback(config);
  3743. }
  3744. }
  3745. function createLocalOrUTC(input, format, locale, strict, isUTC) {
  3746. var c = {};
  3747. if (format === true || format === false) {
  3748. strict = format;
  3749. format = undefined;
  3750. }
  3751. if (locale === true || locale === false) {
  3752. strict = locale;
  3753. locale = undefined;
  3754. }
  3755. if (
  3756. (isObject(input) && isObjectEmpty(input)) ||
  3757. (isArray(input) && input.length === 0)
  3758. ) {
  3759. input = undefined;
  3760. }
  3761. // object construction must be done this way.
  3762. // https://github.com/moment/moment/issues/1423
  3763. c._isAMomentObject = true;
  3764. c._useUTC = c._isUTC = isUTC;
  3765. c._l = locale;
  3766. c._i = input;
  3767. c._f = format;
  3768. c._strict = strict;
  3769. return createFromConfig(c);
  3770. }
  3771. function createLocal(input, format, locale, strict) {
  3772. return createLocalOrUTC(input, format, locale, strict, false);
  3773. }
  3774. var prototypeMin = deprecate(
  3775. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  3776. function () {
  3777. var other = createLocal.apply(null, arguments);
  3778. if (this.isValid() && other.isValid()) {
  3779. return other < this ? this : other;
  3780. } else {
  3781. return createInvalid();
  3782. }
  3783. }
  3784. ),
  3785. prototypeMax = deprecate(
  3786. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  3787. function () {
  3788. var other = createLocal.apply(null, arguments);
  3789. if (this.isValid() && other.isValid()) {
  3790. return other > this ? this : other;
  3791. } else {
  3792. return createInvalid();
  3793. }
  3794. }
  3795. );
  3796. // Pick a moment m from moments so that m[fn](other) is true for all
  3797. // other. This relies on the function fn to be transitive.
  3798. //
  3799. // moments should either be an array of moment objects or an array, whose
  3800. // first element is an array of moment objects.
  3801. function pickBy(fn, moments) {
  3802. var res, i;
  3803. if (moments.length === 1 && isArray(moments[0])) {
  3804. moments = moments[0];
  3805. }
  3806. if (!moments.length) {
  3807. return createLocal();
  3808. }
  3809. res = moments[0];
  3810. for (i = 1; i < moments.length; ++i) {
  3811. if (!moments[i].isValid() || moments[i][fn](res)) {
  3812. res = moments[i];
  3813. }
  3814. }
  3815. return res;
  3816. }
  3817. // TODO: Use [].sort instead?
  3818. function min() {
  3819. var args = [].slice.call(arguments, 0);
  3820. return pickBy('isBefore', args);
  3821. }
  3822. function max() {
  3823. var args = [].slice.call(arguments, 0);
  3824. return pickBy('isAfter', args);
  3825. }
  3826. var now = function () {
  3827. return Date.now ? Date.now() : +new Date();
  3828. };
  3829. var ordering = [
  3830. 'year',
  3831. 'quarter',
  3832. 'month',
  3833. 'week',
  3834. 'day',
  3835. 'hour',
  3836. 'minute',
  3837. 'second',
  3838. 'millisecond',
  3839. ];
  3840. function isDurationValid(m) {
  3841. var key,
  3842. unitHasDecimal = false,
  3843. i,
  3844. orderLen = ordering.length;
  3845. for (key in m) {
  3846. if (
  3847. hasOwnProp(m, key) &&
  3848. !(
  3849. indexOf.call(ordering, key) !== -1 &&
  3850. (m[key] == null || !isNaN(m[key]))
  3851. )
  3852. ) {
  3853. return false;
  3854. }
  3855. }
  3856. for (i = 0; i < orderLen; ++i) {
  3857. if (m[ordering[i]]) {
  3858. if (unitHasDecimal) {
  3859. return false; // only allow non-integers for smallest unit
  3860. }
  3861. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  3862. unitHasDecimal = true;
  3863. }
  3864. }
  3865. }
  3866. return true;
  3867. }
  3868. function isValid$1() {
  3869. return this._isValid;
  3870. }
  3871. function createInvalid$1() {
  3872. return createDuration(NaN);
  3873. }
  3874. function Duration(duration) {
  3875. var normalizedInput = normalizeObjectUnits(duration),
  3876. years = normalizedInput.year || 0,
  3877. quarters = normalizedInput.quarter || 0,
  3878. months = normalizedInput.month || 0,
  3879. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  3880. days = normalizedInput.day || 0,
  3881. hours = normalizedInput.hour || 0,
  3882. minutes = normalizedInput.minute || 0,
  3883. seconds = normalizedInput.second || 0,
  3884. milliseconds = normalizedInput.millisecond || 0;
  3885. this._isValid = isDurationValid(normalizedInput);
  3886. // representation for dateAddRemove
  3887. this._milliseconds =
  3888. +milliseconds +
  3889. seconds * 1e3 + // 1000
  3890. minutes * 6e4 + // 1000 * 60
  3891. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  3892. // Because of dateAddRemove treats 24 hours as different from a
  3893. // day when working around DST, we need to store them separately
  3894. this._days = +days + weeks * 7;
  3895. // It is impossible to translate months into days without knowing
  3896. // which months you are are talking about, so we have to store
  3897. // it separately.
  3898. this._months = +months + quarters * 3 + years * 12;
  3899. this._data = {};
  3900. this._locale = getLocale();
  3901. this._bubble();
  3902. }
  3903. function isDuration(obj) {
  3904. return obj instanceof Duration;
  3905. }
  3906. function absRound(number) {
  3907. if (number < 0) {
  3908. return Math.round(-1 * number) * -1;
  3909. } else {
  3910. return Math.round(number);
  3911. }
  3912. }
  3913. // compare two arrays, return the number of differences
  3914. function compareArrays(array1, array2, dontConvert) {
  3915. var len = Math.min(array1.length, array2.length),
  3916. lengthDiff = Math.abs(array1.length - array2.length),
  3917. diffs = 0,
  3918. i;
  3919. for (i = 0; i < len; i++) {
  3920. if (
  3921. (toInt(array1[i]) !== toInt(array2[i]))
  3922. ) {
  3923. diffs++;
  3924. }
  3925. }
  3926. return diffs + lengthDiff;
  3927. }
  3928. // FORMATTING
  3929. function offset(token, separator) {
  3930. addFormatToken(token, 0, 0, function () {
  3931. var offset = this.utcOffset(),
  3932. sign = '+';
  3933. if (offset < 0) {
  3934. offset = -offset;
  3935. sign = '-';
  3936. }
  3937. return (
  3938. sign +
  3939. zeroFill(~~(offset / 60), 2) +
  3940. separator +
  3941. zeroFill(~~offset % 60, 2)
  3942. );
  3943. });
  3944. }
  3945. offset('Z', ':');
  3946. offset('ZZ', '');
  3947. // PARSING
  3948. addRegexToken('Z', matchShortOffset);
  3949. addRegexToken('ZZ', matchShortOffset);
  3950. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  3951. config._useUTC = true;
  3952. config._tzm = offsetFromString(matchShortOffset, input);
  3953. });
  3954. // HELPERS
  3955. // timezone chunker
  3956. // '+10:00' > ['10', '00']
  3957. // '-1530' > ['-15', '30']
  3958. var chunkOffset = /([\+\-]|\d\d)/gi;
  3959. function offsetFromString(matcher, string) {
  3960. var matches = (string || '').match(matcher),
  3961. chunk,
  3962. parts,
  3963. minutes;
  3964. if (matches === null) {
  3965. return null;
  3966. }
  3967. chunk = matches[matches.length - 1] || [];
  3968. parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  3969. minutes = +(parts[1] * 60) + toInt(parts[2]);
  3970. return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
  3971. }
  3972. // Return a moment from input, that is local/utc/zone equivalent to model.
  3973. function cloneWithOffset(input, model) {
  3974. var res, diff;
  3975. if (model._isUTC) {
  3976. res = model.clone();
  3977. diff =
  3978. (isMoment(input) || isDate(input)
  3979. ? input.valueOf()
  3980. : createLocal(input).valueOf()) - res.valueOf();
  3981. // Use low-level api, because this fn is low-level api.
  3982. res._d.setTime(res._d.valueOf() + diff);
  3983. hooks.updateOffset(res, false);
  3984. return res;
  3985. } else {
  3986. return createLocal(input).local();
  3987. }
  3988. }
  3989. function getDateOffset(m) {
  3990. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  3991. // https://github.com/moment/moment/pull/1871
  3992. return -Math.round(m._d.getTimezoneOffset());
  3993. }
  3994. // HOOKS
  3995. // This function will be called whenever a moment is mutated.
  3996. // It is intended to keep the offset in sync with the timezone.
  3997. hooks.updateOffset = function () {};
  3998. // MOMENTS
  3999. // keepLocalTime = true means only change the timezone, without
  4000. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  4001. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  4002. // +0200, so we adjust the time as needed, to be valid.
  4003. //
  4004. // Keeping the time actually adds/subtracts (one hour)
  4005. // from the actual represented time. That is why we call updateOffset
  4006. // a second time. In case it wants us to change the offset again
  4007. // _changeInProgress == true case, then we have to adjust, because
  4008. // there is no such time in the given timezone.
  4009. function getSetOffset(input, keepLocalTime, keepMinutes) {
  4010. var offset = this._offset || 0,
  4011. localAdjust;
  4012. if (!this.isValid()) {
  4013. return input != null ? this : NaN;
  4014. }
  4015. if (input != null) {
  4016. if (typeof input === 'string') {
  4017. input = offsetFromString(matchShortOffset, input);
  4018. if (input === null) {
  4019. return this;
  4020. }
  4021. } else if (Math.abs(input) < 16 && !keepMinutes) {
  4022. input = input * 60;
  4023. }
  4024. if (!this._isUTC && keepLocalTime) {
  4025. localAdjust = getDateOffset(this);
  4026. }
  4027. this._offset = input;
  4028. this._isUTC = true;
  4029. if (localAdjust != null) {
  4030. this.add(localAdjust, 'm');
  4031. }
  4032. if (offset !== input) {
  4033. if (!keepLocalTime || this._changeInProgress) {
  4034. addSubtract(
  4035. this,
  4036. createDuration(input - offset, 'm'),
  4037. 1,
  4038. false
  4039. );
  4040. } else if (!this._changeInProgress) {
  4041. this._changeInProgress = true;
  4042. hooks.updateOffset(this, true);
  4043. this._changeInProgress = null;
  4044. }
  4045. }
  4046. return this;
  4047. } else {
  4048. return this._isUTC ? offset : getDateOffset(this);
  4049. }
  4050. }
  4051. function getSetZone(input, keepLocalTime) {
  4052. if (input != null) {
  4053. if (typeof input !== 'string') {
  4054. input = -input;
  4055. }
  4056. this.utcOffset(input, keepLocalTime);
  4057. return this;
  4058. } else {
  4059. return -this.utcOffset();
  4060. }
  4061. }
  4062. function setOffsetToUTC(keepLocalTime) {
  4063. return this.utcOffset(0, keepLocalTime);
  4064. }
  4065. function setOffsetToLocal(keepLocalTime) {
  4066. if (this._isUTC) {
  4067. this.utcOffset(0, keepLocalTime);
  4068. this._isUTC = false;
  4069. if (keepLocalTime) {
  4070. this.subtract(getDateOffset(this), 'm');
  4071. }
  4072. }
  4073. return this;
  4074. }
  4075. function setOffsetToParsedOffset() {
  4076. if (this._tzm != null) {
  4077. this.utcOffset(this._tzm, false, true);
  4078. } else if (typeof this._i === 'string') {
  4079. var tZone = offsetFromString(matchOffset, this._i);
  4080. if (tZone != null) {
  4081. this.utcOffset(tZone);
  4082. } else {
  4083. this.utcOffset(0, true);
  4084. }
  4085. }
  4086. return this;
  4087. }
  4088. function hasAlignedHourOffset(input) {
  4089. if (!this.isValid()) {
  4090. return false;
  4091. }
  4092. input = input ? createLocal(input).utcOffset() : 0;
  4093. return (this.utcOffset() - input) % 60 === 0;
  4094. }
  4095. function isDaylightSavingTime() {
  4096. return (
  4097. this.utcOffset() > this.clone().month(0).utcOffset() ||
  4098. this.utcOffset() > this.clone().month(5).utcOffset()
  4099. );
  4100. }
  4101. function isDaylightSavingTimeShifted() {
  4102. if (!isUndefined(this._isDSTShifted)) {
  4103. return this._isDSTShifted;
  4104. }
  4105. var c = {},
  4106. other;
  4107. copyConfig(c, this);
  4108. c = prepareConfig(c);
  4109. if (c._a) {
  4110. other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  4111. this._isDSTShifted =
  4112. this.isValid() && compareArrays(c._a, other.toArray()) > 0;
  4113. } else {
  4114. this._isDSTShifted = false;
  4115. }
  4116. return this._isDSTShifted;
  4117. }
  4118. function isLocal() {
  4119. return this.isValid() ? !this._isUTC : false;
  4120. }
  4121. function isUtcOffset() {
  4122. return this.isValid() ? this._isUTC : false;
  4123. }
  4124. function isUtc() {
  4125. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  4126. }
  4127. // ASP.NET json date format regex
  4128. var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
  4129. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  4130. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  4131. // and further modified to allow for strings containing both week and day
  4132. isoRegex =
  4133. /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  4134. function createDuration(input, key) {
  4135. var duration = input,
  4136. // matching against regexp is expensive, do it on demand
  4137. match = null,
  4138. sign,
  4139. ret,
  4140. diffRes;
  4141. if (isDuration(input)) {
  4142. duration = {
  4143. ms: input._milliseconds,
  4144. d: input._days,
  4145. M: input._months,
  4146. };
  4147. } else if (isNumber(input) || !isNaN(+input)) {
  4148. duration = {};
  4149. if (key) {
  4150. duration[key] = +input;
  4151. } else {
  4152. duration.milliseconds = +input;
  4153. }
  4154. } else if ((match = aspNetRegex.exec(input))) {
  4155. sign = match[1] === '-' ? -1 : 1;
  4156. duration = {
  4157. y: 0,
  4158. d: toInt(match[DATE]) * sign,
  4159. h: toInt(match[HOUR]) * sign,
  4160. m: toInt(match[MINUTE]) * sign,
  4161. s: toInt(match[SECOND]) * sign,
  4162. ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
  4163. };
  4164. } else if ((match = isoRegex.exec(input))) {
  4165. sign = match[1] === '-' ? -1 : 1;
  4166. duration = {
  4167. y: parseIso(match[2], sign),
  4168. M: parseIso(match[3], sign),
  4169. w: parseIso(match[4], sign),
  4170. d: parseIso(match[5], sign),
  4171. h: parseIso(match[6], sign),
  4172. m: parseIso(match[7], sign),
  4173. s: parseIso(match[8], sign),
  4174. };
  4175. } else if (duration == null) {
  4176. // checks for null or undefined
  4177. duration = {};
  4178. } else if (
  4179. typeof duration === 'object' &&
  4180. ('from' in duration || 'to' in duration)
  4181. ) {
  4182. diffRes = momentsDifference(
  4183. createLocal(duration.from),
  4184. createLocal(duration.to)
  4185. );
  4186. duration = {};
  4187. duration.ms = diffRes.milliseconds;
  4188. duration.M = diffRes.months;
  4189. }
  4190. ret = new Duration(duration);
  4191. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  4192. ret._locale = input._locale;
  4193. }
  4194. if (isDuration(input) && hasOwnProp(input, '_isValid')) {
  4195. ret._isValid = input._isValid;
  4196. }
  4197. return ret;
  4198. }
  4199. createDuration.fn = Duration.prototype;
  4200. createDuration.invalid = createInvalid$1;
  4201. function parseIso(inp, sign) {
  4202. // We'd normally use ~~inp for this, but unfortunately it also
  4203. // converts floats to ints.
  4204. // inp may be undefined, so careful calling replace on it.
  4205. var res = inp && parseFloat(inp.replace(',', '.'));
  4206. // apply sign while we're at it
  4207. return (isNaN(res) ? 0 : res) * sign;
  4208. }
  4209. function positiveMomentsDifference(base, other) {
  4210. var res = {};
  4211. res.months =
  4212. other.month() - base.month() + (other.year() - base.year()) * 12;
  4213. if (base.clone().add(res.months, 'M').isAfter(other)) {
  4214. --res.months;
  4215. }
  4216. res.milliseconds = +other - +base.clone().add(res.months, 'M');
  4217. return res;
  4218. }
  4219. function momentsDifference(base, other) {
  4220. var res;
  4221. if (!(base.isValid() && other.isValid())) {
  4222. return { milliseconds: 0, months: 0 };
  4223. }
  4224. other = cloneWithOffset(other, base);
  4225. if (base.isBefore(other)) {
  4226. res = positiveMomentsDifference(base, other);
  4227. } else {
  4228. res = positiveMomentsDifference(other, base);
  4229. res.milliseconds = -res.milliseconds;
  4230. res.months = -res.months;
  4231. }
  4232. return res;
  4233. }
  4234. // TODO: remove 'name' arg after deprecation is removed
  4235. function createAdder(direction, name) {
  4236. return function (val, period) {
  4237. var dur, tmp;
  4238. //invert the arguments, but complain about it
  4239. if (period !== null && !isNaN(+period)) {
  4240. deprecateSimple(
  4241. name,
  4242. 'moment().' +
  4243. name +
  4244. '(period, number) is deprecated. Please use moment().' +
  4245. name +
  4246. '(number, period). ' +
  4247. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
  4248. );
  4249. tmp = val;
  4250. val = period;
  4251. period = tmp;
  4252. }
  4253. dur = createDuration(val, period);
  4254. addSubtract(this, dur, direction);
  4255. return this;
  4256. };
  4257. }
  4258. function addSubtract(mom, duration, isAdding, updateOffset) {
  4259. var milliseconds = duration._milliseconds,
  4260. days = absRound(duration._days),
  4261. months = absRound(duration._months);
  4262. if (!mom.isValid()) {
  4263. // No op
  4264. return;
  4265. }
  4266. updateOffset = updateOffset == null ? true : updateOffset;
  4267. if (months) {
  4268. setMonth(mom, get(mom, 'Month') + months * isAdding);
  4269. }
  4270. if (days) {
  4271. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  4272. }
  4273. if (milliseconds) {
  4274. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  4275. }
  4276. if (updateOffset) {
  4277. hooks.updateOffset(mom, days || months);
  4278. }
  4279. }
  4280. var add = createAdder(1, 'add'),
  4281. subtract = createAdder(-1, 'subtract');
  4282. function isString(input) {
  4283. return typeof input === 'string' || input instanceof String;
  4284. }
  4285. // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
  4286. function isMomentInput(input) {
  4287. return (
  4288. isMoment(input) ||
  4289. isDate(input) ||
  4290. isString(input) ||
  4291. isNumber(input) ||
  4292. isNumberOrStringArray(input) ||
  4293. isMomentInputObject(input) ||
  4294. input === null ||
  4295. input === undefined
  4296. );
  4297. }
  4298. function isMomentInputObject(input) {
  4299. var objectTest = isObject(input) && !isObjectEmpty(input),
  4300. propertyTest = false,
  4301. properties = [
  4302. 'years',
  4303. 'year',
  4304. 'y',
  4305. 'months',
  4306. 'month',
  4307. 'M',
  4308. 'days',
  4309. 'day',
  4310. 'd',
  4311. 'dates',
  4312. 'date',
  4313. 'D',
  4314. 'hours',
  4315. 'hour',
  4316. 'h',
  4317. 'minutes',
  4318. 'minute',
  4319. 'm',
  4320. 'seconds',
  4321. 'second',
  4322. 's',
  4323. 'milliseconds',
  4324. 'millisecond',
  4325. 'ms',
  4326. ],
  4327. i,
  4328. property,
  4329. propertyLen = properties.length;
  4330. for (i = 0; i < propertyLen; i += 1) {
  4331. property = properties[i];
  4332. propertyTest = propertyTest || hasOwnProp(input, property);
  4333. }
  4334. return objectTest && propertyTest;
  4335. }
  4336. function isNumberOrStringArray(input) {
  4337. var arrayTest = isArray(input),
  4338. dataTypeTest = false;
  4339. if (arrayTest) {
  4340. dataTypeTest =
  4341. input.filter(function (item) {
  4342. return !isNumber(item) && isString(input);
  4343. }).length === 0;
  4344. }
  4345. return arrayTest && dataTypeTest;
  4346. }
  4347. function isCalendarSpec(input) {
  4348. var objectTest = isObject(input) && !isObjectEmpty(input),
  4349. propertyTest = false,
  4350. properties = [
  4351. 'sameDay',
  4352. 'nextDay',
  4353. 'lastDay',
  4354. 'nextWeek',
  4355. 'lastWeek',
  4356. 'sameElse',
  4357. ],
  4358. i,
  4359. property;
  4360. for (i = 0; i < properties.length; i += 1) {
  4361. property = properties[i];
  4362. propertyTest = propertyTest || hasOwnProp(input, property);
  4363. }
  4364. return objectTest && propertyTest;
  4365. }
  4366. function getCalendarFormat(myMoment, now) {
  4367. var diff = myMoment.diff(now, 'days', true);
  4368. return diff < -6
  4369. ? 'sameElse'
  4370. : diff < -1
  4371. ? 'lastWeek'
  4372. : diff < 0
  4373. ? 'lastDay'
  4374. : diff < 1
  4375. ? 'sameDay'
  4376. : diff < 2
  4377. ? 'nextDay'
  4378. : diff < 7
  4379. ? 'nextWeek'
  4380. : 'sameElse';
  4381. }
  4382. function calendar$1(time, formats) {
  4383. // Support for single parameter, formats only overload to the calendar function
  4384. if (arguments.length === 1) {
  4385. if (!arguments[0]) {
  4386. time = undefined;
  4387. formats = undefined;
  4388. } else if (isMomentInput(arguments[0])) {
  4389. time = arguments[0];
  4390. formats = undefined;
  4391. } else if (isCalendarSpec(arguments[0])) {
  4392. formats = arguments[0];
  4393. time = undefined;
  4394. }
  4395. }
  4396. // We want to compare the start of today, vs this.
  4397. // Getting start-of-today depends on whether we're local/utc/offset or not.
  4398. var now = time || createLocal(),
  4399. sod = cloneWithOffset(now, this).startOf('day'),
  4400. format = hooks.calendarFormat(this, sod) || 'sameElse',
  4401. output =
  4402. formats &&
  4403. (isFunction(formats[format])
  4404. ? formats[format].call(this, now)
  4405. : formats[format]);
  4406. return this.format(
  4407. output || this.localeData().calendar(format, this, createLocal(now))
  4408. );
  4409. }
  4410. function clone() {
  4411. return new Moment(this);
  4412. }
  4413. function isAfter(input, units) {
  4414. var localInput = isMoment(input) ? input : createLocal(input);
  4415. if (!(this.isValid() && localInput.isValid())) {
  4416. return false;
  4417. }
  4418. units = normalizeUnits(units) || 'millisecond';
  4419. if (units === 'millisecond') {
  4420. return this.valueOf() > localInput.valueOf();
  4421. } else {
  4422. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  4423. }
  4424. }
  4425. function isBefore(input, units) {
  4426. var localInput = isMoment(input) ? input : createLocal(input);
  4427. if (!(this.isValid() && localInput.isValid())) {
  4428. return false;
  4429. }
  4430. units = normalizeUnits(units) || 'millisecond';
  4431. if (units === 'millisecond') {
  4432. return this.valueOf() < localInput.valueOf();
  4433. } else {
  4434. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  4435. }
  4436. }
  4437. function isBetween(from, to, units, inclusivity) {
  4438. var localFrom = isMoment(from) ? from : createLocal(from),
  4439. localTo = isMoment(to) ? to : createLocal(to);
  4440. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  4441. return false;
  4442. }
  4443. inclusivity = inclusivity || '()';
  4444. return (
  4445. (inclusivity[0] === '('
  4446. ? this.isAfter(localFrom, units)
  4447. : !this.isBefore(localFrom, units)) &&
  4448. (inclusivity[1] === ')'
  4449. ? this.isBefore(localTo, units)
  4450. : !this.isAfter(localTo, units))
  4451. );
  4452. }
  4453. function isSame(input, units) {
  4454. var localInput = isMoment(input) ? input : createLocal(input),
  4455. inputMs;
  4456. if (!(this.isValid() && localInput.isValid())) {
  4457. return false;
  4458. }
  4459. units = normalizeUnits(units) || 'millisecond';
  4460. if (units === 'millisecond') {
  4461. return this.valueOf() === localInput.valueOf();
  4462. } else {
  4463. inputMs = localInput.valueOf();
  4464. return (
  4465. this.clone().startOf(units).valueOf() <= inputMs &&
  4466. inputMs <= this.clone().endOf(units).valueOf()
  4467. );
  4468. }
  4469. }
  4470. function isSameOrAfter(input, units) {
  4471. return this.isSame(input, units) || this.isAfter(input, units);
  4472. }
  4473. function isSameOrBefore(input, units) {
  4474. return this.isSame(input, units) || this.isBefore(input, units);
  4475. }
  4476. function diff(input, units, asFloat) {
  4477. var that, zoneDelta, output;
  4478. if (!this.isValid()) {
  4479. return NaN;
  4480. }
  4481. that = cloneWithOffset(input, this);
  4482. if (!that.isValid()) {
  4483. return NaN;
  4484. }
  4485. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  4486. units = normalizeUnits(units);
  4487. switch (units) {
  4488. case 'year':
  4489. output = monthDiff(this, that) / 12;
  4490. break;
  4491. case 'month':
  4492. output = monthDiff(this, that);
  4493. break;
  4494. case 'quarter':
  4495. output = monthDiff(this, that) / 3;
  4496. break;
  4497. case 'second':
  4498. output = (this - that) / 1e3;
  4499. break; // 1000
  4500. case 'minute':
  4501. output = (this - that) / 6e4;
  4502. break; // 1000 * 60
  4503. case 'hour':
  4504. output = (this - that) / 36e5;
  4505. break; // 1000 * 60 * 60
  4506. case 'day':
  4507. output = (this - that - zoneDelta) / 864e5;
  4508. break; // 1000 * 60 * 60 * 24, negate dst
  4509. case 'week':
  4510. output = (this - that - zoneDelta) / 6048e5;
  4511. break; // 1000 * 60 * 60 * 24 * 7, negate dst
  4512. default:
  4513. output = this - that;
  4514. }
  4515. return asFloat ? output : absFloor(output);
  4516. }
  4517. function monthDiff(a, b) {
  4518. if (a.date() < b.date()) {
  4519. // end-of-month calculations work correct when the start month has more
  4520. // days than the end month.
  4521. return -monthDiff(b, a);
  4522. }
  4523. // difference in months
  4524. var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
  4525. // b is in (anchor - 1 month, anchor + 1 month)
  4526. anchor = a.clone().add(wholeMonthDiff, 'months'),
  4527. anchor2,
  4528. adjust;
  4529. if (b - anchor < 0) {
  4530. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  4531. // linear across the month
  4532. adjust = (b - anchor) / (anchor - anchor2);
  4533. } else {
  4534. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  4535. // linear across the month
  4536. adjust = (b - anchor) / (anchor2 - anchor);
  4537. }
  4538. //check for negative zero, return zero if negative zero
  4539. return -(wholeMonthDiff + adjust) || 0;
  4540. }
  4541. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  4542. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  4543. function toString() {
  4544. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  4545. }
  4546. function toISOString(keepOffset) {
  4547. if (!this.isValid()) {
  4548. return null;
  4549. }
  4550. var utc = keepOffset !== true,
  4551. m = utc ? this.clone().utc() : this;
  4552. if (m.year() < 0 || m.year() > 9999) {
  4553. return formatMoment(
  4554. m,
  4555. utc
  4556. ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
  4557. : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
  4558. );
  4559. }
  4560. if (isFunction(Date.prototype.toISOString)) {
  4561. // native implementation is ~50x faster, use it when we can
  4562. if (utc) {
  4563. return this.toDate().toISOString();
  4564. } else {
  4565. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
  4566. .toISOString()
  4567. .replace('Z', formatMoment(m, 'Z'));
  4568. }
  4569. }
  4570. return formatMoment(
  4571. m,
  4572. utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
  4573. );
  4574. }
  4575. /**
  4576. * Return a human readable representation of a moment that can
  4577. * also be evaluated to get a new moment which is the same
  4578. *
  4579. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  4580. */
  4581. function inspect() {
  4582. if (!this.isValid()) {
  4583. return 'moment.invalid(/* ' + this._i + ' */)';
  4584. }
  4585. var func = 'moment',
  4586. zone = '',
  4587. prefix,
  4588. year,
  4589. datetime,
  4590. suffix;
  4591. if (!this.isLocal()) {
  4592. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  4593. zone = 'Z';
  4594. }
  4595. prefix = '[' + func + '("]';
  4596. year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
  4597. datetime = '-MM-DD[T]HH:mm:ss.SSS';
  4598. suffix = zone + '[")]';
  4599. return this.format(prefix + year + datetime + suffix);
  4600. }
  4601. function format(inputString) {
  4602. if (!inputString) {
  4603. inputString = this.isUtc()
  4604. ? hooks.defaultFormatUtc
  4605. : hooks.defaultFormat;
  4606. }
  4607. var output = formatMoment(this, inputString);
  4608. return this.localeData().postformat(output);
  4609. }
  4610. function from(time, withoutSuffix) {
  4611. if (
  4612. this.isValid() &&
  4613. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  4614. ) {
  4615. return createDuration({ to: this, from: time })
  4616. .locale(this.locale())
  4617. .humanize(!withoutSuffix);
  4618. } else {
  4619. return this.localeData().invalidDate();
  4620. }
  4621. }
  4622. function fromNow(withoutSuffix) {
  4623. return this.from(createLocal(), withoutSuffix);
  4624. }
  4625. function to(time, withoutSuffix) {
  4626. if (
  4627. this.isValid() &&
  4628. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  4629. ) {
  4630. return createDuration({ from: this, to: time })
  4631. .locale(this.locale())
  4632. .humanize(!withoutSuffix);
  4633. } else {
  4634. return this.localeData().invalidDate();
  4635. }
  4636. }
  4637. function toNow(withoutSuffix) {
  4638. return this.to(createLocal(), withoutSuffix);
  4639. }
  4640. // If passed a locale key, it will set the locale for this
  4641. // instance. Otherwise, it will return the locale configuration
  4642. // variables for this instance.
  4643. function locale(key) {
  4644. var newLocaleData;
  4645. if (key === undefined) {
  4646. return this._locale._abbr;
  4647. } else {
  4648. newLocaleData = getLocale(key);
  4649. if (newLocaleData != null) {
  4650. this._locale = newLocaleData;
  4651. }
  4652. return this;
  4653. }
  4654. }
  4655. var lang = deprecate(
  4656. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  4657. function (key) {
  4658. if (key === undefined) {
  4659. return this.localeData();
  4660. } else {
  4661. return this.locale(key);
  4662. }
  4663. }
  4664. );
  4665. function localeData() {
  4666. return this._locale;
  4667. }
  4668. var MS_PER_SECOND = 1000,
  4669. MS_PER_MINUTE = 60 * MS_PER_SECOND,
  4670. MS_PER_HOUR = 60 * MS_PER_MINUTE,
  4671. MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  4672. // actual modulo - handles negative numbers (for dates before 1970):
  4673. function mod$1(dividend, divisor) {
  4674. return ((dividend % divisor) + divisor) % divisor;
  4675. }
  4676. function localStartOfDate(y, m, d) {
  4677. // the date constructor remaps years 0-99 to 1900-1999
  4678. if (y < 100 && y >= 0) {
  4679. // preserve leap years using a full 400 year cycle, then reset
  4680. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  4681. } else {
  4682. return new Date(y, m, d).valueOf();
  4683. }
  4684. }
  4685. function utcStartOfDate(y, m, d) {
  4686. // Date.UTC remaps years 0-99 to 1900-1999
  4687. if (y < 100 && y >= 0) {
  4688. // preserve leap years using a full 400 year cycle, then reset
  4689. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  4690. } else {
  4691. return Date.UTC(y, m, d);
  4692. }
  4693. }
  4694. function startOf(units) {
  4695. var time, startOfDate;
  4696. units = normalizeUnits(units);
  4697. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  4698. return this;
  4699. }
  4700. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  4701. switch (units) {
  4702. case 'year':
  4703. time = startOfDate(this.year(), 0, 1);
  4704. break;
  4705. case 'quarter':
  4706. time = startOfDate(
  4707. this.year(),
  4708. this.month() - (this.month() % 3),
  4709. 1
  4710. );
  4711. break;
  4712. case 'month':
  4713. time = startOfDate(this.year(), this.month(), 1);
  4714. break;
  4715. case 'week':
  4716. time = startOfDate(
  4717. this.year(),
  4718. this.month(),
  4719. this.date() - this.weekday()
  4720. );
  4721. break;
  4722. case 'isoWeek':
  4723. time = startOfDate(
  4724. this.year(),
  4725. this.month(),
  4726. this.date() - (this.isoWeekday() - 1)
  4727. );
  4728. break;
  4729. case 'day':
  4730. case 'date':
  4731. time = startOfDate(this.year(), this.month(), this.date());
  4732. break;
  4733. case 'hour':
  4734. time = this._d.valueOf();
  4735. time -= mod$1(
  4736. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  4737. MS_PER_HOUR
  4738. );
  4739. break;
  4740. case 'minute':
  4741. time = this._d.valueOf();
  4742. time -= mod$1(time, MS_PER_MINUTE);
  4743. break;
  4744. case 'second':
  4745. time = this._d.valueOf();
  4746. time -= mod$1(time, MS_PER_SECOND);
  4747. break;
  4748. }
  4749. this._d.setTime(time);
  4750. hooks.updateOffset(this, true);
  4751. return this;
  4752. }
  4753. function endOf(units) {
  4754. var time, startOfDate;
  4755. units = normalizeUnits(units);
  4756. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  4757. return this;
  4758. }
  4759. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  4760. switch (units) {
  4761. case 'year':
  4762. time = startOfDate(this.year() + 1, 0, 1) - 1;
  4763. break;
  4764. case 'quarter':
  4765. time =
  4766. startOfDate(
  4767. this.year(),
  4768. this.month() - (this.month() % 3) + 3,
  4769. 1
  4770. ) - 1;
  4771. break;
  4772. case 'month':
  4773. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  4774. break;
  4775. case 'week':
  4776. time =
  4777. startOfDate(
  4778. this.year(),
  4779. this.month(),
  4780. this.date() - this.weekday() + 7
  4781. ) - 1;
  4782. break;
  4783. case 'isoWeek':
  4784. time =
  4785. startOfDate(
  4786. this.year(),
  4787. this.month(),
  4788. this.date() - (this.isoWeekday() - 1) + 7
  4789. ) - 1;
  4790. break;
  4791. case 'day':
  4792. case 'date':
  4793. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  4794. break;
  4795. case 'hour':
  4796. time = this._d.valueOf();
  4797. time +=
  4798. MS_PER_HOUR -
  4799. mod$1(
  4800. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  4801. MS_PER_HOUR
  4802. ) -
  4803. 1;
  4804. break;
  4805. case 'minute':
  4806. time = this._d.valueOf();
  4807. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  4808. break;
  4809. case 'second':
  4810. time = this._d.valueOf();
  4811. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  4812. break;
  4813. }
  4814. this._d.setTime(time);
  4815. hooks.updateOffset(this, true);
  4816. return this;
  4817. }
  4818. function valueOf() {
  4819. return this._d.valueOf() - (this._offset || 0) * 60000;
  4820. }
  4821. function unix() {
  4822. return Math.floor(this.valueOf() / 1000);
  4823. }
  4824. function toDate() {
  4825. return new Date(this.valueOf());
  4826. }
  4827. function toArray() {
  4828. var m = this;
  4829. return [
  4830. m.year(),
  4831. m.month(),
  4832. m.date(),
  4833. m.hour(),
  4834. m.minute(),
  4835. m.second(),
  4836. m.millisecond(),
  4837. ];
  4838. }
  4839. function toObject() {
  4840. var m = this;
  4841. return {
  4842. years: m.year(),
  4843. months: m.month(),
  4844. date: m.date(),
  4845. hours: m.hours(),
  4846. minutes: m.minutes(),
  4847. seconds: m.seconds(),
  4848. milliseconds: m.milliseconds(),
  4849. };
  4850. }
  4851. function toJSON() {
  4852. // new Date(NaN).toJSON() === null
  4853. return this.isValid() ? this.toISOString() : null;
  4854. }
  4855. function isValid$2() {
  4856. return isValid(this);
  4857. }
  4858. function parsingFlags() {
  4859. return extend({}, getParsingFlags(this));
  4860. }
  4861. function invalidAt() {
  4862. return getParsingFlags(this).overflow;
  4863. }
  4864. function creationData() {
  4865. return {
  4866. input: this._i,
  4867. format: this._f,
  4868. locale: this._locale,
  4869. isUTC: this._isUTC,
  4870. strict: this._strict,
  4871. };
  4872. }
  4873. addFormatToken('N', 0, 0, 'eraAbbr');
  4874. addFormatToken('NN', 0, 0, 'eraAbbr');
  4875. addFormatToken('NNN', 0, 0, 'eraAbbr');
  4876. addFormatToken('NNNN', 0, 0, 'eraName');
  4877. addFormatToken('NNNNN', 0, 0, 'eraNarrow');
  4878. addFormatToken('y', ['y', 1], 'yo', 'eraYear');
  4879. addFormatToken('y', ['yy', 2], 0, 'eraYear');
  4880. addFormatToken('y', ['yyy', 3], 0, 'eraYear');
  4881. addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
  4882. addRegexToken('N', matchEraAbbr);
  4883. addRegexToken('NN', matchEraAbbr);
  4884. addRegexToken('NNN', matchEraAbbr);
  4885. addRegexToken('NNNN', matchEraName);
  4886. addRegexToken('NNNNN', matchEraNarrow);
  4887. addParseToken(
  4888. ['N', 'NN', 'NNN', 'NNNN', 'NNNNN'],
  4889. function (input, array, config, token) {
  4890. var era = config._locale.erasParse(input, token, config._strict);
  4891. if (era) {
  4892. getParsingFlags(config).era = era;
  4893. } else {
  4894. getParsingFlags(config).invalidEra = input;
  4895. }
  4896. }
  4897. );
  4898. addRegexToken('y', matchUnsigned);
  4899. addRegexToken('yy', matchUnsigned);
  4900. addRegexToken('yyy', matchUnsigned);
  4901. addRegexToken('yyyy', matchUnsigned);
  4902. addRegexToken('yo', matchEraYearOrdinal);
  4903. addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
  4904. addParseToken(['yo'], function (input, array, config, token) {
  4905. var match;
  4906. if (config._locale._eraYearOrdinalRegex) {
  4907. match = input.match(config._locale._eraYearOrdinalRegex);
  4908. }
  4909. if (config._locale.eraYearOrdinalParse) {
  4910. array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
  4911. } else {
  4912. array[YEAR] = parseInt(input, 10);
  4913. }
  4914. });
  4915. function localeEras(m, format) {
  4916. var i,
  4917. l,
  4918. date,
  4919. eras = this._eras || getLocale('en')._eras;
  4920. for (i = 0, l = eras.length; i < l; ++i) {
  4921. switch (typeof eras[i].since) {
  4922. case 'string':
  4923. // truncate time
  4924. date = hooks(eras[i].since).startOf('day');
  4925. eras[i].since = date.valueOf();
  4926. break;
  4927. }
  4928. switch (typeof eras[i].until) {
  4929. case 'undefined':
  4930. eras[i].until = +Infinity;
  4931. break;
  4932. case 'string':
  4933. // truncate time
  4934. date = hooks(eras[i].until).startOf('day').valueOf();
  4935. eras[i].until = date.valueOf();
  4936. break;
  4937. }
  4938. }
  4939. return eras;
  4940. }
  4941. function localeErasParse(eraName, format, strict) {
  4942. var i,
  4943. l,
  4944. eras = this.eras(),
  4945. name,
  4946. abbr,
  4947. narrow;
  4948. eraName = eraName.toUpperCase();
  4949. for (i = 0, l = eras.length; i < l; ++i) {
  4950. name = eras[i].name.toUpperCase();
  4951. abbr = eras[i].abbr.toUpperCase();
  4952. narrow = eras[i].narrow.toUpperCase();
  4953. if (strict) {
  4954. switch (format) {
  4955. case 'N':
  4956. case 'NN':
  4957. case 'NNN':
  4958. if (abbr === eraName) {
  4959. return eras[i];
  4960. }
  4961. break;
  4962. case 'NNNN':
  4963. if (name === eraName) {
  4964. return eras[i];
  4965. }
  4966. break;
  4967. case 'NNNNN':
  4968. if (narrow === eraName) {
  4969. return eras[i];
  4970. }
  4971. break;
  4972. }
  4973. } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
  4974. return eras[i];
  4975. }
  4976. }
  4977. }
  4978. function localeErasConvertYear(era, year) {
  4979. var dir = era.since <= era.until ? 1 : -1;
  4980. if (year === undefined) {
  4981. return hooks(era.since).year();
  4982. } else {
  4983. return hooks(era.since).year() + (year - era.offset) * dir;
  4984. }
  4985. }
  4986. function getEraName() {
  4987. var i,
  4988. l,
  4989. val,
  4990. eras = this.localeData().eras();
  4991. for (i = 0, l = eras.length; i < l; ++i) {
  4992. // truncate time
  4993. val = this.clone().startOf('day').valueOf();
  4994. if (eras[i].since <= val && val <= eras[i].until) {
  4995. return eras[i].name;
  4996. }
  4997. if (eras[i].until <= val && val <= eras[i].since) {
  4998. return eras[i].name;
  4999. }
  5000. }
  5001. return '';
  5002. }
  5003. function getEraNarrow() {
  5004. var i,
  5005. l,
  5006. val,
  5007. eras = this.localeData().eras();
  5008. for (i = 0, l = eras.length; i < l; ++i) {
  5009. // truncate time
  5010. val = this.clone().startOf('day').valueOf();
  5011. if (eras[i].since <= val && val <= eras[i].until) {
  5012. return eras[i].narrow;
  5013. }
  5014. if (eras[i].until <= val && val <= eras[i].since) {
  5015. return eras[i].narrow;
  5016. }
  5017. }
  5018. return '';
  5019. }
  5020. function getEraAbbr() {
  5021. var i,
  5022. l,
  5023. val,
  5024. eras = this.localeData().eras();
  5025. for (i = 0, l = eras.length; i < l; ++i) {
  5026. // truncate time
  5027. val = this.clone().startOf('day').valueOf();
  5028. if (eras[i].since <= val && val <= eras[i].until) {
  5029. return eras[i].abbr;
  5030. }
  5031. if (eras[i].until <= val && val <= eras[i].since) {
  5032. return eras[i].abbr;
  5033. }
  5034. }
  5035. return '';
  5036. }
  5037. function getEraYear() {
  5038. var i,
  5039. l,
  5040. dir,
  5041. val,
  5042. eras = this.localeData().eras();
  5043. for (i = 0, l = eras.length; i < l; ++i) {
  5044. dir = eras[i].since <= eras[i].until ? 1 : -1;
  5045. // truncate time
  5046. val = this.clone().startOf('day').valueOf();
  5047. if (
  5048. (eras[i].since <= val && val <= eras[i].until) ||
  5049. (eras[i].until <= val && val <= eras[i].since)
  5050. ) {
  5051. return (
  5052. (this.year() - hooks(eras[i].since).year()) * dir +
  5053. eras[i].offset
  5054. );
  5055. }
  5056. }
  5057. return this.year();
  5058. }
  5059. function erasNameRegex(isStrict) {
  5060. if (!hasOwnProp(this, '_erasNameRegex')) {
  5061. computeErasParse.call(this);
  5062. }
  5063. return isStrict ? this._erasNameRegex : this._erasRegex;
  5064. }
  5065. function erasAbbrRegex(isStrict) {
  5066. if (!hasOwnProp(this, '_erasAbbrRegex')) {
  5067. computeErasParse.call(this);
  5068. }
  5069. return isStrict ? this._erasAbbrRegex : this._erasRegex;
  5070. }
  5071. function erasNarrowRegex(isStrict) {
  5072. if (!hasOwnProp(this, '_erasNarrowRegex')) {
  5073. computeErasParse.call(this);
  5074. }
  5075. return isStrict ? this._erasNarrowRegex : this._erasRegex;
  5076. }
  5077. function matchEraAbbr(isStrict, locale) {
  5078. return locale.erasAbbrRegex(isStrict);
  5079. }
  5080. function matchEraName(isStrict, locale) {
  5081. return locale.erasNameRegex(isStrict);
  5082. }
  5083. function matchEraNarrow(isStrict, locale) {
  5084. return locale.erasNarrowRegex(isStrict);
  5085. }
  5086. function matchEraYearOrdinal(isStrict, locale) {
  5087. return locale._eraYearOrdinalRegex || matchUnsigned;
  5088. }
  5089. function computeErasParse() {
  5090. var abbrPieces = [],
  5091. namePieces = [],
  5092. narrowPieces = [],
  5093. mixedPieces = [],
  5094. i,
  5095. l,
  5096. eras = this.eras();
  5097. for (i = 0, l = eras.length; i < l; ++i) {
  5098. namePieces.push(regexEscape(eras[i].name));
  5099. abbrPieces.push(regexEscape(eras[i].abbr));
  5100. narrowPieces.push(regexEscape(eras[i].narrow));
  5101. mixedPieces.push(regexEscape(eras[i].name));
  5102. mixedPieces.push(regexEscape(eras[i].abbr));
  5103. mixedPieces.push(regexEscape(eras[i].narrow));
  5104. }
  5105. this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  5106. this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
  5107. this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
  5108. this._erasNarrowRegex = new RegExp(
  5109. '^(' + narrowPieces.join('|') + ')',
  5110. 'i'
  5111. );
  5112. }
  5113. // FORMATTING
  5114. addFormatToken(0, ['gg', 2], 0, function () {
  5115. return this.weekYear() % 100;
  5116. });
  5117. addFormatToken(0, ['GG', 2], 0, function () {
  5118. return this.isoWeekYear() % 100;
  5119. });
  5120. function addWeekYearFormatToken(token, getter) {
  5121. addFormatToken(0, [token, token.length], 0, getter);
  5122. }
  5123. addWeekYearFormatToken('gggg', 'weekYear');
  5124. addWeekYearFormatToken('ggggg', 'weekYear');
  5125. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  5126. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  5127. // ALIASES
  5128. addUnitAlias('weekYear', 'gg');
  5129. addUnitAlias('isoWeekYear', 'GG');
  5130. // PRIORITY
  5131. addUnitPriority('weekYear', 1);
  5132. addUnitPriority('isoWeekYear', 1);
  5133. // PARSING
  5134. addRegexToken('G', matchSigned);
  5135. addRegexToken('g', matchSigned);
  5136. addRegexToken('GG', match1to2, match2);
  5137. addRegexToken('gg', match1to2, match2);
  5138. addRegexToken('GGGG', match1to4, match4);
  5139. addRegexToken('gggg', match1to4, match4);
  5140. addRegexToken('GGGGG', match1to6, match6);
  5141. addRegexToken('ggggg', match1to6, match6);
  5142. addWeekParseToken(
  5143. ['gggg', 'ggggg', 'GGGG', 'GGGGG'],
  5144. function (input, week, config, token) {
  5145. week[token.substr(0, 2)] = toInt(input);
  5146. }
  5147. );
  5148. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  5149. week[token] = hooks.parseTwoDigitYear(input);
  5150. });
  5151. // MOMENTS
  5152. function getSetWeekYear(input) {
  5153. return getSetWeekYearHelper.call(
  5154. this,
  5155. input,
  5156. this.week(),
  5157. this.weekday(),
  5158. this.localeData()._week.dow,
  5159. this.localeData()._week.doy
  5160. );
  5161. }
  5162. function getSetISOWeekYear(input) {
  5163. return getSetWeekYearHelper.call(
  5164. this,
  5165. input,
  5166. this.isoWeek(),
  5167. this.isoWeekday(),
  5168. 1,
  5169. 4
  5170. );
  5171. }
  5172. function getISOWeeksInYear() {
  5173. return weeksInYear(this.year(), 1, 4);
  5174. }
  5175. function getISOWeeksInISOWeekYear() {
  5176. return weeksInYear(this.isoWeekYear(), 1, 4);
  5177. }
  5178. function getWeeksInYear() {
  5179. var weekInfo = this.localeData()._week;
  5180. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  5181. }
  5182. function getWeeksInWeekYear() {
  5183. var weekInfo = this.localeData()._week;
  5184. return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
  5185. }
  5186. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  5187. var weeksTarget;
  5188. if (input == null) {
  5189. return weekOfYear(this, dow, doy).year;
  5190. } else {
  5191. weeksTarget = weeksInYear(input, dow, doy);
  5192. if (week > weeksTarget) {
  5193. week = weeksTarget;
  5194. }
  5195. return setWeekAll.call(this, input, week, weekday, dow, doy);
  5196. }
  5197. }
  5198. function setWeekAll(weekYear, week, weekday, dow, doy) {
  5199. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  5200. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  5201. this.year(date.getUTCFullYear());
  5202. this.month(date.getUTCMonth());
  5203. this.date(date.getUTCDate());
  5204. return this;
  5205. }
  5206. // FORMATTING
  5207. addFormatToken('Q', 0, 'Qo', 'quarter');
  5208. // ALIASES
  5209. addUnitAlias('quarter', 'Q');
  5210. // PRIORITY
  5211. addUnitPriority('quarter', 7);
  5212. // PARSING
  5213. addRegexToken('Q', match1);
  5214. addParseToken('Q', function (input, array) {
  5215. array[MONTH] = (toInt(input) - 1) * 3;
  5216. });
  5217. // MOMENTS
  5218. function getSetQuarter(input) {
  5219. return input == null
  5220. ? Math.ceil((this.month() + 1) / 3)
  5221. : this.month((input - 1) * 3 + (this.month() % 3));
  5222. }
  5223. // FORMATTING
  5224. addFormatToken('D', ['DD', 2], 'Do', 'date');
  5225. // ALIASES
  5226. addUnitAlias('date', 'D');
  5227. // PRIORITY
  5228. addUnitPriority('date', 9);
  5229. // PARSING
  5230. addRegexToken('D', match1to2);
  5231. addRegexToken('DD', match1to2, match2);
  5232. addRegexToken('Do', function (isStrict, locale) {
  5233. // TODO: Remove "ordinalParse" fallback in next major release.
  5234. return isStrict
  5235. ? locale._dayOfMonthOrdinalParse || locale._ordinalParse
  5236. : locale._dayOfMonthOrdinalParseLenient;
  5237. });
  5238. addParseToken(['D', 'DD'], DATE);
  5239. addParseToken('Do', function (input, array) {
  5240. array[DATE] = toInt(input.match(match1to2)[0]);
  5241. });
  5242. // MOMENTS
  5243. var getSetDayOfMonth = makeGetSet('Date', true);
  5244. // FORMATTING
  5245. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  5246. // ALIASES
  5247. addUnitAlias('dayOfYear', 'DDD');
  5248. // PRIORITY
  5249. addUnitPriority('dayOfYear', 4);
  5250. // PARSING
  5251. addRegexToken('DDD', match1to3);
  5252. addRegexToken('DDDD', match3);
  5253. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  5254. config._dayOfYear = toInt(input);
  5255. });
  5256. // HELPERS
  5257. // MOMENTS
  5258. function getSetDayOfYear(input) {
  5259. var dayOfYear =
  5260. Math.round(
  5261. (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
  5262. ) + 1;
  5263. return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
  5264. }
  5265. // FORMATTING
  5266. addFormatToken('m', ['mm', 2], 0, 'minute');
  5267. // ALIASES
  5268. addUnitAlias('minute', 'm');
  5269. // PRIORITY
  5270. addUnitPriority('minute', 14);
  5271. // PARSING
  5272. addRegexToken('m', match1to2);
  5273. addRegexToken('mm', match1to2, match2);
  5274. addParseToken(['m', 'mm'], MINUTE);
  5275. // MOMENTS
  5276. var getSetMinute = makeGetSet('Minutes', false);
  5277. // FORMATTING
  5278. addFormatToken('s', ['ss', 2], 0, 'second');
  5279. // ALIASES
  5280. addUnitAlias('second', 's');
  5281. // PRIORITY
  5282. addUnitPriority('second', 15);
  5283. // PARSING
  5284. addRegexToken('s', match1to2);
  5285. addRegexToken('ss', match1to2, match2);
  5286. addParseToken(['s', 'ss'], SECOND);
  5287. // MOMENTS
  5288. var getSetSecond = makeGetSet('Seconds', false);
  5289. // FORMATTING
  5290. addFormatToken('S', 0, 0, function () {
  5291. return ~~(this.millisecond() / 100);
  5292. });
  5293. addFormatToken(0, ['SS', 2], 0, function () {
  5294. return ~~(this.millisecond() / 10);
  5295. });
  5296. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  5297. addFormatToken(0, ['SSSS', 4], 0, function () {
  5298. return this.millisecond() * 10;
  5299. });
  5300. addFormatToken(0, ['SSSSS', 5], 0, function () {
  5301. return this.millisecond() * 100;
  5302. });
  5303. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  5304. return this.millisecond() * 1000;
  5305. });
  5306. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  5307. return this.millisecond() * 10000;
  5308. });
  5309. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  5310. return this.millisecond() * 100000;
  5311. });
  5312. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  5313. return this.millisecond() * 1000000;
  5314. });
  5315. // ALIASES
  5316. addUnitAlias('millisecond', 'ms');
  5317. // PRIORITY
  5318. addUnitPriority('millisecond', 16);
  5319. // PARSING
  5320. addRegexToken('S', match1to3, match1);
  5321. addRegexToken('SS', match1to3, match2);
  5322. addRegexToken('SSS', match1to3, match3);
  5323. var token, getSetMillisecond;
  5324. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  5325. addRegexToken(token, matchUnsigned);
  5326. }
  5327. function parseMs(input, array) {
  5328. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  5329. }
  5330. for (token = 'S'; token.length <= 9; token += 'S') {
  5331. addParseToken(token, parseMs);
  5332. }
  5333. getSetMillisecond = makeGetSet('Milliseconds', false);
  5334. // FORMATTING
  5335. addFormatToken('z', 0, 0, 'zoneAbbr');
  5336. addFormatToken('zz', 0, 0, 'zoneName');
  5337. // MOMENTS
  5338. function getZoneAbbr() {
  5339. return this._isUTC ? 'UTC' : '';
  5340. }
  5341. function getZoneName() {
  5342. return this._isUTC ? 'Coordinated Universal Time' : '';
  5343. }
  5344. var proto = Moment.prototype;
  5345. proto.add = add;
  5346. proto.calendar = calendar$1;
  5347. proto.clone = clone;
  5348. proto.diff = diff;
  5349. proto.endOf = endOf;
  5350. proto.format = format;
  5351. proto.from = from;
  5352. proto.fromNow = fromNow;
  5353. proto.to = to;
  5354. proto.toNow = toNow;
  5355. proto.get = stringGet;
  5356. proto.invalidAt = invalidAt;
  5357. proto.isAfter = isAfter;
  5358. proto.isBefore = isBefore;
  5359. proto.isBetween = isBetween;
  5360. proto.isSame = isSame;
  5361. proto.isSameOrAfter = isSameOrAfter;
  5362. proto.isSameOrBefore = isSameOrBefore;
  5363. proto.isValid = isValid$2;
  5364. proto.lang = lang;
  5365. proto.locale = locale;
  5366. proto.localeData = localeData;
  5367. proto.max = prototypeMax;
  5368. proto.min = prototypeMin;
  5369. proto.parsingFlags = parsingFlags;
  5370. proto.set = stringSet;
  5371. proto.startOf = startOf;
  5372. proto.subtract = subtract;
  5373. proto.toArray = toArray;
  5374. proto.toObject = toObject;
  5375. proto.toDate = toDate;
  5376. proto.toISOString = toISOString;
  5377. proto.inspect = inspect;
  5378. if (typeof Symbol !== 'undefined' && Symbol.for != null) {
  5379. proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
  5380. return 'Moment<' + this.format() + '>';
  5381. };
  5382. }
  5383. proto.toJSON = toJSON;
  5384. proto.toString = toString;
  5385. proto.unix = unix;
  5386. proto.valueOf = valueOf;
  5387. proto.creationData = creationData;
  5388. proto.eraName = getEraName;
  5389. proto.eraNarrow = getEraNarrow;
  5390. proto.eraAbbr = getEraAbbr;
  5391. proto.eraYear = getEraYear;
  5392. proto.year = getSetYear;
  5393. proto.isLeapYear = getIsLeapYear;
  5394. proto.weekYear = getSetWeekYear;
  5395. proto.isoWeekYear = getSetISOWeekYear;
  5396. proto.quarter = proto.quarters = getSetQuarter;
  5397. proto.month = getSetMonth;
  5398. proto.daysInMonth = getDaysInMonth;
  5399. proto.week = proto.weeks = getSetWeek;
  5400. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  5401. proto.weeksInYear = getWeeksInYear;
  5402. proto.weeksInWeekYear = getWeeksInWeekYear;
  5403. proto.isoWeeksInYear = getISOWeeksInYear;
  5404. proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
  5405. proto.date = getSetDayOfMonth;
  5406. proto.day = proto.days = getSetDayOfWeek;
  5407. proto.weekday = getSetLocaleDayOfWeek;
  5408. proto.isoWeekday = getSetISODayOfWeek;
  5409. proto.dayOfYear = getSetDayOfYear;
  5410. proto.hour = proto.hours = getSetHour;
  5411. proto.minute = proto.minutes = getSetMinute;
  5412. proto.second = proto.seconds = getSetSecond;
  5413. proto.millisecond = proto.milliseconds = getSetMillisecond;
  5414. proto.utcOffset = getSetOffset;
  5415. proto.utc = setOffsetToUTC;
  5416. proto.local = setOffsetToLocal;
  5417. proto.parseZone = setOffsetToParsedOffset;
  5418. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  5419. proto.isDST = isDaylightSavingTime;
  5420. proto.isLocal = isLocal;
  5421. proto.isUtcOffset = isUtcOffset;
  5422. proto.isUtc = isUtc;
  5423. proto.isUTC = isUtc;
  5424. proto.zoneAbbr = getZoneAbbr;
  5425. proto.zoneName = getZoneName;
  5426. proto.dates = deprecate(
  5427. 'dates accessor is deprecated. Use date instead.',
  5428. getSetDayOfMonth
  5429. );
  5430. proto.months = deprecate(
  5431. 'months accessor is deprecated. Use month instead',
  5432. getSetMonth
  5433. );
  5434. proto.years = deprecate(
  5435. 'years accessor is deprecated. Use year instead',
  5436. getSetYear
  5437. );
  5438. proto.zone = deprecate(
  5439. 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
  5440. getSetZone
  5441. );
  5442. proto.isDSTShifted = deprecate(
  5443. 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
  5444. isDaylightSavingTimeShifted
  5445. );
  5446. function createUnix(input) {
  5447. return createLocal(input * 1000);
  5448. }
  5449. function createInZone() {
  5450. return createLocal.apply(null, arguments).parseZone();
  5451. }
  5452. function preParsePostFormat(string) {
  5453. return string;
  5454. }
  5455. var proto$1 = Locale.prototype;
  5456. proto$1.calendar = calendar;
  5457. proto$1.longDateFormat = longDateFormat;
  5458. proto$1.invalidDate = invalidDate;
  5459. proto$1.ordinal = ordinal;
  5460. proto$1.preparse = preParsePostFormat;
  5461. proto$1.postformat = preParsePostFormat;
  5462. proto$1.relativeTime = relativeTime;
  5463. proto$1.pastFuture = pastFuture;
  5464. proto$1.set = set;
  5465. proto$1.eras = localeEras;
  5466. proto$1.erasParse = localeErasParse;
  5467. proto$1.erasConvertYear = localeErasConvertYear;
  5468. proto$1.erasAbbrRegex = erasAbbrRegex;
  5469. proto$1.erasNameRegex = erasNameRegex;
  5470. proto$1.erasNarrowRegex = erasNarrowRegex;
  5471. proto$1.months = localeMonths;
  5472. proto$1.monthsShort = localeMonthsShort;
  5473. proto$1.monthsParse = localeMonthsParse;
  5474. proto$1.monthsRegex = monthsRegex;
  5475. proto$1.monthsShortRegex = monthsShortRegex;
  5476. proto$1.week = localeWeek;
  5477. proto$1.firstDayOfYear = localeFirstDayOfYear;
  5478. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  5479. proto$1.weekdays = localeWeekdays;
  5480. proto$1.weekdaysMin = localeWeekdaysMin;
  5481. proto$1.weekdaysShort = localeWeekdaysShort;
  5482. proto$1.weekdaysParse = localeWeekdaysParse;
  5483. proto$1.weekdaysRegex = weekdaysRegex;
  5484. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  5485. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  5486. proto$1.isPM = localeIsPM;
  5487. proto$1.meridiem = localeMeridiem;
  5488. function get$1(format, index, field, setter) {
  5489. var locale = getLocale(),
  5490. utc = createUTC().set(setter, index);
  5491. return locale[field](utc, format);
  5492. }
  5493. function listMonthsImpl(format, index, field) {
  5494. if (isNumber(format)) {
  5495. index = format;
  5496. format = undefined;
  5497. }
  5498. format = format || '';
  5499. if (index != null) {
  5500. return get$1(format, index, field, 'month');
  5501. }
  5502. var i,
  5503. out = [];
  5504. for (i = 0; i < 12; i++) {
  5505. out[i] = get$1(format, i, field, 'month');
  5506. }
  5507. return out;
  5508. }
  5509. // ()
  5510. // (5)
  5511. // (fmt, 5)
  5512. // (fmt)
  5513. // (true)
  5514. // (true, 5)
  5515. // (true, fmt, 5)
  5516. // (true, fmt)
  5517. function listWeekdaysImpl(localeSorted, format, index, field) {
  5518. if (typeof localeSorted === 'boolean') {
  5519. if (isNumber(format)) {
  5520. index = format;
  5521. format = undefined;
  5522. }
  5523. format = format || '';
  5524. } else {
  5525. format = localeSorted;
  5526. index = format;
  5527. localeSorted = false;
  5528. if (isNumber(format)) {
  5529. index = format;
  5530. format = undefined;
  5531. }
  5532. format = format || '';
  5533. }
  5534. var locale = getLocale(),
  5535. shift = localeSorted ? locale._week.dow : 0,
  5536. i,
  5537. out = [];
  5538. if (index != null) {
  5539. return get$1(format, (index + shift) % 7, field, 'day');
  5540. }
  5541. for (i = 0; i < 7; i++) {
  5542. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  5543. }
  5544. return out;
  5545. }
  5546. function listMonths(format, index) {
  5547. return listMonthsImpl(format, index, 'months');
  5548. }
  5549. function listMonthsShort(format, index) {
  5550. return listMonthsImpl(format, index, 'monthsShort');
  5551. }
  5552. function listWeekdays(localeSorted, format, index) {
  5553. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  5554. }
  5555. function listWeekdaysShort(localeSorted, format, index) {
  5556. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  5557. }
  5558. function listWeekdaysMin(localeSorted, format, index) {
  5559. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  5560. }
  5561. getSetGlobalLocale('en', {
  5562. eras: [
  5563. {
  5564. since: '0001-01-01',
  5565. until: +Infinity,
  5566. offset: 1,
  5567. name: 'Anno Domini',
  5568. narrow: 'AD',
  5569. abbr: 'AD',
  5570. },
  5571. {
  5572. since: '0000-12-31',
  5573. until: -Infinity,
  5574. offset: 1,
  5575. name: 'Before Christ',
  5576. narrow: 'BC',
  5577. abbr: 'BC',
  5578. },
  5579. ],
  5580. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  5581. ordinal: function (number) {
  5582. var b = number % 10,
  5583. output =
  5584. toInt((number % 100) / 10) === 1
  5585. ? 'th'
  5586. : b === 1
  5587. ? 'st'
  5588. : b === 2
  5589. ? 'nd'
  5590. : b === 3
  5591. ? 'rd'
  5592. : 'th';
  5593. return number + output;
  5594. },
  5595. });
  5596. // Side effect imports
  5597. hooks.lang = deprecate(
  5598. 'moment.lang is deprecated. Use moment.locale instead.',
  5599. getSetGlobalLocale
  5600. );
  5601. hooks.langData = deprecate(
  5602. 'moment.langData is deprecated. Use moment.localeData instead.',
  5603. getLocale
  5604. );
  5605. var mathAbs = Math.abs;
  5606. function abs() {
  5607. var data = this._data;
  5608. this._milliseconds = mathAbs(this._milliseconds);
  5609. this._days = mathAbs(this._days);
  5610. this._months = mathAbs(this._months);
  5611. data.milliseconds = mathAbs(data.milliseconds);
  5612. data.seconds = mathAbs(data.seconds);
  5613. data.minutes = mathAbs(data.minutes);
  5614. data.hours = mathAbs(data.hours);
  5615. data.months = mathAbs(data.months);
  5616. data.years = mathAbs(data.years);
  5617. return this;
  5618. }
  5619. function addSubtract$1(duration, input, value, direction) {
  5620. var other = createDuration(input, value);
  5621. duration._milliseconds += direction * other._milliseconds;
  5622. duration._days += direction * other._days;
  5623. duration._months += direction * other._months;
  5624. return duration._bubble();
  5625. }
  5626. // supports only 2.0-style add(1, 's') or add(duration)
  5627. function add$1(input, value) {
  5628. return addSubtract$1(this, input, value, 1);
  5629. }
  5630. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  5631. function subtract$1(input, value) {
  5632. return addSubtract$1(this, input, value, -1);
  5633. }
  5634. function absCeil(number) {
  5635. if (number < 0) {
  5636. return Math.floor(number);
  5637. } else {
  5638. return Math.ceil(number);
  5639. }
  5640. }
  5641. function bubble() {
  5642. var milliseconds = this._milliseconds,
  5643. days = this._days,
  5644. months = this._months,
  5645. data = this._data,
  5646. seconds,
  5647. minutes,
  5648. hours,
  5649. years,
  5650. monthsFromDays;
  5651. // if we have a mix of positive and negative values, bubble down first
  5652. // check: https://github.com/moment/moment/issues/2166
  5653. if (
  5654. !(
  5655. (milliseconds >= 0 && days >= 0 && months >= 0) ||
  5656. (milliseconds <= 0 && days <= 0 && months <= 0)
  5657. )
  5658. ) {
  5659. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  5660. days = 0;
  5661. months = 0;
  5662. }
  5663. // The following code bubbles up values, see the tests for
  5664. // examples of what that means.
  5665. data.milliseconds = milliseconds % 1000;
  5666. seconds = absFloor(milliseconds / 1000);
  5667. data.seconds = seconds % 60;
  5668. minutes = absFloor(seconds / 60);
  5669. data.minutes = minutes % 60;
  5670. hours = absFloor(minutes / 60);
  5671. data.hours = hours % 24;
  5672. days += absFloor(hours / 24);
  5673. // convert days to months
  5674. monthsFromDays = absFloor(daysToMonths(days));
  5675. months += monthsFromDays;
  5676. days -= absCeil(monthsToDays(monthsFromDays));
  5677. // 12 months -> 1 year
  5678. years = absFloor(months / 12);
  5679. months %= 12;
  5680. data.days = days;
  5681. data.months = months;
  5682. data.years = years;
  5683. return this;
  5684. }
  5685. function daysToMonths(days) {
  5686. // 400 years have 146097 days (taking into account leap year rules)
  5687. // 400 years have 12 months === 4800
  5688. return (days * 4800) / 146097;
  5689. }
  5690. function monthsToDays(months) {
  5691. // the reverse of daysToMonths
  5692. return (months * 146097) / 4800;
  5693. }
  5694. function as(units) {
  5695. if (!this.isValid()) {
  5696. return NaN;
  5697. }
  5698. var days,
  5699. months,
  5700. milliseconds = this._milliseconds;
  5701. units = normalizeUnits(units);
  5702. if (units === 'month' || units === 'quarter' || units === 'year') {
  5703. days = this._days + milliseconds / 864e5;
  5704. months = this._months + daysToMonths(days);
  5705. switch (units) {
  5706. case 'month':
  5707. return months;
  5708. case 'quarter':
  5709. return months / 3;
  5710. case 'year':
  5711. return months / 12;
  5712. }
  5713. } else {
  5714. // handle milliseconds separately because of floating point math errors (issue #1867)
  5715. days = this._days + Math.round(monthsToDays(this._months));
  5716. switch (units) {
  5717. case 'week':
  5718. return days / 7 + milliseconds / 6048e5;
  5719. case 'day':
  5720. return days + milliseconds / 864e5;
  5721. case 'hour':
  5722. return days * 24 + milliseconds / 36e5;
  5723. case 'minute':
  5724. return days * 1440 + milliseconds / 6e4;
  5725. case 'second':
  5726. return days * 86400 + milliseconds / 1000;
  5727. // Math.floor prevents floating point math errors here
  5728. case 'millisecond':
  5729. return Math.floor(days * 864e5) + milliseconds;
  5730. default:
  5731. throw new Error('Unknown unit ' + units);
  5732. }
  5733. }
  5734. }
  5735. // TODO: Use this.as('ms')?
  5736. function valueOf$1() {
  5737. if (!this.isValid()) {
  5738. return NaN;
  5739. }
  5740. return (
  5741. this._milliseconds +
  5742. this._days * 864e5 +
  5743. (this._months % 12) * 2592e6 +
  5744. toInt(this._months / 12) * 31536e6
  5745. );
  5746. }
  5747. function makeAs(alias) {
  5748. return function () {
  5749. return this.as(alias);
  5750. };
  5751. }
  5752. var asMilliseconds = makeAs('ms'),
  5753. asSeconds = makeAs('s'),
  5754. asMinutes = makeAs('m'),
  5755. asHours = makeAs('h'),
  5756. asDays = makeAs('d'),
  5757. asWeeks = makeAs('w'),
  5758. asMonths = makeAs('M'),
  5759. asQuarters = makeAs('Q'),
  5760. asYears = makeAs('y');
  5761. function clone$1() {
  5762. return createDuration(this);
  5763. }
  5764. function get$2(units) {
  5765. units = normalizeUnits(units);
  5766. return this.isValid() ? this[units + 's']() : NaN;
  5767. }
  5768. function makeGetter(name) {
  5769. return function () {
  5770. return this.isValid() ? this._data[name] : NaN;
  5771. };
  5772. }
  5773. var milliseconds = makeGetter('milliseconds'),
  5774. seconds = makeGetter('seconds'),
  5775. minutes = makeGetter('minutes'),
  5776. hours = makeGetter('hours'),
  5777. days = makeGetter('days'),
  5778. months = makeGetter('months'),
  5779. years = makeGetter('years');
  5780. function weeks() {
  5781. return absFloor(this.days() / 7);
  5782. }
  5783. var round = Math.round,
  5784. thresholds = {
  5785. ss: 44, // a few seconds to seconds
  5786. s: 45, // seconds to minute
  5787. m: 45, // minutes to hour
  5788. h: 22, // hours to day
  5789. d: 26, // days to month/week
  5790. w: null, // weeks to month
  5791. M: 11, // months to year
  5792. };
  5793. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  5794. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  5795. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  5796. }
  5797. function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
  5798. var duration = createDuration(posNegDuration).abs(),
  5799. seconds = round(duration.as('s')),
  5800. minutes = round(duration.as('m')),
  5801. hours = round(duration.as('h')),
  5802. days = round(duration.as('d')),
  5803. months = round(duration.as('M')),
  5804. weeks = round(duration.as('w')),
  5805. years = round(duration.as('y')),
  5806. a =
  5807. (seconds <= thresholds.ss && ['s', seconds]) ||
  5808. (seconds < thresholds.s && ['ss', seconds]) ||
  5809. (minutes <= 1 && ['m']) ||
  5810. (minutes < thresholds.m && ['mm', minutes]) ||
  5811. (hours <= 1 && ['h']) ||
  5812. (hours < thresholds.h && ['hh', hours]) ||
  5813. (days <= 1 && ['d']) ||
  5814. (days < thresholds.d && ['dd', days]);
  5815. if (thresholds.w != null) {
  5816. a =
  5817. a ||
  5818. (weeks <= 1 && ['w']) ||
  5819. (weeks < thresholds.w && ['ww', weeks]);
  5820. }
  5821. a = a ||
  5822. (months <= 1 && ['M']) ||
  5823. (months < thresholds.M && ['MM', months]) ||
  5824. (years <= 1 && ['y']) || ['yy', years];
  5825. a[2] = withoutSuffix;
  5826. a[3] = +posNegDuration > 0;
  5827. a[4] = locale;
  5828. return substituteTimeAgo.apply(null, a);
  5829. }
  5830. // This function allows you to set the rounding function for relative time strings
  5831. function getSetRelativeTimeRounding(roundingFunction) {
  5832. if (roundingFunction === undefined) {
  5833. return round;
  5834. }
  5835. if (typeof roundingFunction === 'function') {
  5836. round = roundingFunction;
  5837. return true;
  5838. }
  5839. return false;
  5840. }
  5841. // This function allows you to set a threshold for relative time strings
  5842. function getSetRelativeTimeThreshold(threshold, limit) {
  5843. if (thresholds[threshold] === undefined) {
  5844. return false;
  5845. }
  5846. if (limit === undefined) {
  5847. return thresholds[threshold];
  5848. }
  5849. thresholds[threshold] = limit;
  5850. if (threshold === 's') {
  5851. thresholds.ss = limit - 1;
  5852. }
  5853. return true;
  5854. }
  5855. function humanize(argWithSuffix, argThresholds) {
  5856. if (!this.isValid()) {
  5857. return this.localeData().invalidDate();
  5858. }
  5859. var withSuffix = false,
  5860. th = thresholds,
  5861. locale,
  5862. output;
  5863. if (typeof argWithSuffix === 'object') {
  5864. argThresholds = argWithSuffix;
  5865. argWithSuffix = false;
  5866. }
  5867. if (typeof argWithSuffix === 'boolean') {
  5868. withSuffix = argWithSuffix;
  5869. }
  5870. if (typeof argThresholds === 'object') {
  5871. th = Object.assign({}, thresholds, argThresholds);
  5872. if (argThresholds.s != null && argThresholds.ss == null) {
  5873. th.ss = argThresholds.s - 1;
  5874. }
  5875. }
  5876. locale = this.localeData();
  5877. output = relativeTime$1(this, !withSuffix, th, locale);
  5878. if (withSuffix) {
  5879. output = locale.pastFuture(+this, output);
  5880. }
  5881. return locale.postformat(output);
  5882. }
  5883. var abs$1 = Math.abs;
  5884. function sign(x) {
  5885. return (x > 0) - (x < 0) || +x;
  5886. }
  5887. function toISOString$1() {
  5888. // for ISO strings we do not use the normal bubbling rules:
  5889. // * milliseconds bubble up until they become hours
  5890. // * days do not bubble at all
  5891. // * months bubble up until they become years
  5892. // This is because there is no context-free conversion between hours and days
  5893. // (think of clock changes)
  5894. // and also not between days and months (28-31 days per month)
  5895. if (!this.isValid()) {
  5896. return this.localeData().invalidDate();
  5897. }
  5898. var seconds = abs$1(this._milliseconds) / 1000,
  5899. days = abs$1(this._days),
  5900. months = abs$1(this._months),
  5901. minutes,
  5902. hours,
  5903. years,
  5904. s,
  5905. total = this.asSeconds(),
  5906. totalSign,
  5907. ymSign,
  5908. daysSign,
  5909. hmsSign;
  5910. if (!total) {
  5911. // this is the same as C#'s (Noda) and python (isodate)...
  5912. // but not other JS (goog.date)
  5913. return 'P0D';
  5914. }
  5915. // 3600 seconds -> 60 minutes -> 1 hour
  5916. minutes = absFloor(seconds / 60);
  5917. hours = absFloor(minutes / 60);
  5918. seconds %= 60;
  5919. minutes %= 60;
  5920. // 12 months -> 1 year
  5921. years = absFloor(months / 12);
  5922. months %= 12;
  5923. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  5924. s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  5925. totalSign = total < 0 ? '-' : '';
  5926. ymSign = sign(this._months) !== sign(total) ? '-' : '';
  5927. daysSign = sign(this._days) !== sign(total) ? '-' : '';
  5928. hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  5929. return (
  5930. totalSign +
  5931. 'P' +
  5932. (years ? ymSign + years + 'Y' : '') +
  5933. (months ? ymSign + months + 'M' : '') +
  5934. (days ? daysSign + days + 'D' : '') +
  5935. (hours || minutes || seconds ? 'T' : '') +
  5936. (hours ? hmsSign + hours + 'H' : '') +
  5937. (minutes ? hmsSign + minutes + 'M' : '') +
  5938. (seconds ? hmsSign + s + 'S' : '')
  5939. );
  5940. }
  5941. var proto$2 = Duration.prototype;
  5942. proto$2.isValid = isValid$1;
  5943. proto$2.abs = abs;
  5944. proto$2.add = add$1;
  5945. proto$2.subtract = subtract$1;
  5946. proto$2.as = as;
  5947. proto$2.asMilliseconds = asMilliseconds;
  5948. proto$2.asSeconds = asSeconds;
  5949. proto$2.asMinutes = asMinutes;
  5950. proto$2.asHours = asHours;
  5951. proto$2.asDays = asDays;
  5952. proto$2.asWeeks = asWeeks;
  5953. proto$2.asMonths = asMonths;
  5954. proto$2.asQuarters = asQuarters;
  5955. proto$2.asYears = asYears;
  5956. proto$2.valueOf = valueOf$1;
  5957. proto$2._bubble = bubble;
  5958. proto$2.clone = clone$1;
  5959. proto$2.get = get$2;
  5960. proto$2.milliseconds = milliseconds;
  5961. proto$2.seconds = seconds;
  5962. proto$2.minutes = minutes;
  5963. proto$2.hours = hours;
  5964. proto$2.days = days;
  5965. proto$2.weeks = weeks;
  5966. proto$2.months = months;
  5967. proto$2.years = years;
  5968. proto$2.humanize = humanize;
  5969. proto$2.toISOString = toISOString$1;
  5970. proto$2.toString = toISOString$1;
  5971. proto$2.toJSON = toISOString$1;
  5972. proto$2.locale = locale;
  5973. proto$2.localeData = localeData;
  5974. proto$2.toIsoString = deprecate(
  5975. 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
  5976. toISOString$1
  5977. );
  5978. proto$2.lang = lang;
  5979. // FORMATTING
  5980. addFormatToken('X', 0, 0, 'unix');
  5981. addFormatToken('x', 0, 0, 'valueOf');
  5982. // PARSING
  5983. addRegexToken('x', matchSigned);
  5984. addRegexToken('X', matchTimestamp);
  5985. addParseToken('X', function (input, array, config) {
  5986. config._d = new Date(parseFloat(input) * 1000);
  5987. });
  5988. addParseToken('x', function (input, array, config) {
  5989. config._d = new Date(toInt(input));
  5990. });
  5991. //! moment.js
  5992. hooks.version = '2.29.4';
  5993. setHookCallback(createLocal);
  5994. hooks.fn = proto;
  5995. hooks.min = min;
  5996. hooks.max = max;
  5997. hooks.now = now;
  5998. hooks.utc = createUTC;
  5999. hooks.unix = createUnix;
  6000. hooks.months = listMonths;
  6001. hooks.isDate = isDate;
  6002. hooks.locale = getSetGlobalLocale;
  6003. hooks.invalid = createInvalid;
  6004. hooks.duration = createDuration;
  6005. hooks.isMoment = isMoment;
  6006. hooks.weekdays = listWeekdays;
  6007. hooks.parseZone = createInZone;
  6008. hooks.localeData = getLocale;
  6009. hooks.isDuration = isDuration;
  6010. hooks.monthsShort = listMonthsShort;
  6011. hooks.weekdaysMin = listWeekdaysMin;
  6012. hooks.defineLocale = defineLocale;
  6013. hooks.updateLocale = updateLocale;
  6014. hooks.locales = listLocales;
  6015. hooks.weekdaysShort = listWeekdaysShort;
  6016. hooks.normalizeUnits = normalizeUnits;
  6017. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  6018. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  6019. hooks.calendarFormat = getCalendarFormat;
  6020. hooks.prototype = proto;
  6021. // currently HTML5 input type only supports 24-hour formats
  6022. hooks.HTML5_FMT = {
  6023. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  6024. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  6025. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  6026. DATE: 'YYYY-MM-DD', // <input type="date" />
  6027. TIME: 'HH:mm', // <input type="time" />
  6028. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  6029. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  6030. WEEK: 'GGGG-[W]WW', // <input type="week" />
  6031. MONTH: 'YYYY-MM', // <input type="month" />
  6032. };
  6033. return hooks;
  6034. })));
  6035. } (moment$1));
  6036. return moment$1.exports;
  6037. }
  6038. /*!
  6039. * Chart.js v2.9.4
  6040. * https://www.chartjs.org
  6041. * (c) 2020 Chart.js Contributors
  6042. * Released under the MIT License
  6043. */
  6044. var Chart$1 = Chart$2.exports;
  6045. var hasRequiredChart;
  6046. function requireChart () {
  6047. if (hasRequiredChart) return Chart$2.exports;
  6048. hasRequiredChart = 1;
  6049. (function (module, exports) {
  6050. (function (global, factory) {
  6051. module.exports = factory(function() { try { return requireMoment(); } catch(e) { } }()) ;
  6052. }(Chart$1, (function (moment) {
  6053. moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;
  6054. function createCommonjsModule(fn, module) {
  6055. return module = { exports: {} }, fn(module, module.exports), module.exports;
  6056. }
  6057. function getCjsExportFromNamespace (n) {
  6058. return n && n['default'] || n;
  6059. }
  6060. var colorName = {
  6061. "aliceblue": [240, 248, 255],
  6062. "antiquewhite": [250, 235, 215],
  6063. "aqua": [0, 255, 255],
  6064. "aquamarine": [127, 255, 212],
  6065. "azure": [240, 255, 255],
  6066. "beige": [245, 245, 220],
  6067. "bisque": [255, 228, 196],
  6068. "black": [0, 0, 0],
  6069. "blanchedalmond": [255, 235, 205],
  6070. "blue": [0, 0, 255],
  6071. "blueviolet": [138, 43, 226],
  6072. "brown": [165, 42, 42],
  6073. "burlywood": [222, 184, 135],
  6074. "cadetblue": [95, 158, 160],
  6075. "chartreuse": [127, 255, 0],
  6076. "chocolate": [210, 105, 30],
  6077. "coral": [255, 127, 80],
  6078. "cornflowerblue": [100, 149, 237],
  6079. "cornsilk": [255, 248, 220],
  6080. "crimson": [220, 20, 60],
  6081. "cyan": [0, 255, 255],
  6082. "darkblue": [0, 0, 139],
  6083. "darkcyan": [0, 139, 139],
  6084. "darkgoldenrod": [184, 134, 11],
  6085. "darkgray": [169, 169, 169],
  6086. "darkgreen": [0, 100, 0],
  6087. "darkgrey": [169, 169, 169],
  6088. "darkkhaki": [189, 183, 107],
  6089. "darkmagenta": [139, 0, 139],
  6090. "darkolivegreen": [85, 107, 47],
  6091. "darkorange": [255, 140, 0],
  6092. "darkorchid": [153, 50, 204],
  6093. "darkred": [139, 0, 0],
  6094. "darksalmon": [233, 150, 122],
  6095. "darkseagreen": [143, 188, 143],
  6096. "darkslateblue": [72, 61, 139],
  6097. "darkslategray": [47, 79, 79],
  6098. "darkslategrey": [47, 79, 79],
  6099. "darkturquoise": [0, 206, 209],
  6100. "darkviolet": [148, 0, 211],
  6101. "deeppink": [255, 20, 147],
  6102. "deepskyblue": [0, 191, 255],
  6103. "dimgray": [105, 105, 105],
  6104. "dimgrey": [105, 105, 105],
  6105. "dodgerblue": [30, 144, 255],
  6106. "firebrick": [178, 34, 34],
  6107. "floralwhite": [255, 250, 240],
  6108. "forestgreen": [34, 139, 34],
  6109. "fuchsia": [255, 0, 255],
  6110. "gainsboro": [220, 220, 220],
  6111. "ghostwhite": [248, 248, 255],
  6112. "gold": [255, 215, 0],
  6113. "goldenrod": [218, 165, 32],
  6114. "gray": [128, 128, 128],
  6115. "green": [0, 128, 0],
  6116. "greenyellow": [173, 255, 47],
  6117. "grey": [128, 128, 128],
  6118. "honeydew": [240, 255, 240],
  6119. "hotpink": [255, 105, 180],
  6120. "indianred": [205, 92, 92],
  6121. "indigo": [75, 0, 130],
  6122. "ivory": [255, 255, 240],
  6123. "khaki": [240, 230, 140],
  6124. "lavender": [230, 230, 250],
  6125. "lavenderblush": [255, 240, 245],
  6126. "lawngreen": [124, 252, 0],
  6127. "lemonchiffon": [255, 250, 205],
  6128. "lightblue": [173, 216, 230],
  6129. "lightcoral": [240, 128, 128],
  6130. "lightcyan": [224, 255, 255],
  6131. "lightgoldenrodyellow": [250, 250, 210],
  6132. "lightgray": [211, 211, 211],
  6133. "lightgreen": [144, 238, 144],
  6134. "lightgrey": [211, 211, 211],
  6135. "lightpink": [255, 182, 193],
  6136. "lightsalmon": [255, 160, 122],
  6137. "lightseagreen": [32, 178, 170],
  6138. "lightskyblue": [135, 206, 250],
  6139. "lightslategray": [119, 136, 153],
  6140. "lightslategrey": [119, 136, 153],
  6141. "lightsteelblue": [176, 196, 222],
  6142. "lightyellow": [255, 255, 224],
  6143. "lime": [0, 255, 0],
  6144. "limegreen": [50, 205, 50],
  6145. "linen": [250, 240, 230],
  6146. "magenta": [255, 0, 255],
  6147. "maroon": [128, 0, 0],
  6148. "mediumaquamarine": [102, 205, 170],
  6149. "mediumblue": [0, 0, 205],
  6150. "mediumorchid": [186, 85, 211],
  6151. "mediumpurple": [147, 112, 219],
  6152. "mediumseagreen": [60, 179, 113],
  6153. "mediumslateblue": [123, 104, 238],
  6154. "mediumspringgreen": [0, 250, 154],
  6155. "mediumturquoise": [72, 209, 204],
  6156. "mediumvioletred": [199, 21, 133],
  6157. "midnightblue": [25, 25, 112],
  6158. "mintcream": [245, 255, 250],
  6159. "mistyrose": [255, 228, 225],
  6160. "moccasin": [255, 228, 181],
  6161. "navajowhite": [255, 222, 173],
  6162. "navy": [0, 0, 128],
  6163. "oldlace": [253, 245, 230],
  6164. "olive": [128, 128, 0],
  6165. "olivedrab": [107, 142, 35],
  6166. "orange": [255, 165, 0],
  6167. "orangered": [255, 69, 0],
  6168. "orchid": [218, 112, 214],
  6169. "palegoldenrod": [238, 232, 170],
  6170. "palegreen": [152, 251, 152],
  6171. "paleturquoise": [175, 238, 238],
  6172. "palevioletred": [219, 112, 147],
  6173. "papayawhip": [255, 239, 213],
  6174. "peachpuff": [255, 218, 185],
  6175. "peru": [205, 133, 63],
  6176. "pink": [255, 192, 203],
  6177. "plum": [221, 160, 221],
  6178. "powderblue": [176, 224, 230],
  6179. "purple": [128, 0, 128],
  6180. "rebeccapurple": [102, 51, 153],
  6181. "red": [255, 0, 0],
  6182. "rosybrown": [188, 143, 143],
  6183. "royalblue": [65, 105, 225],
  6184. "saddlebrown": [139, 69, 19],
  6185. "salmon": [250, 128, 114],
  6186. "sandybrown": [244, 164, 96],
  6187. "seagreen": [46, 139, 87],
  6188. "seashell": [255, 245, 238],
  6189. "sienna": [160, 82, 45],
  6190. "silver": [192, 192, 192],
  6191. "skyblue": [135, 206, 235],
  6192. "slateblue": [106, 90, 205],
  6193. "slategray": [112, 128, 144],
  6194. "slategrey": [112, 128, 144],
  6195. "snow": [255, 250, 250],
  6196. "springgreen": [0, 255, 127],
  6197. "steelblue": [70, 130, 180],
  6198. "tan": [210, 180, 140],
  6199. "teal": [0, 128, 128],
  6200. "thistle": [216, 191, 216],
  6201. "tomato": [255, 99, 71],
  6202. "turquoise": [64, 224, 208],
  6203. "violet": [238, 130, 238],
  6204. "wheat": [245, 222, 179],
  6205. "white": [255, 255, 255],
  6206. "whitesmoke": [245, 245, 245],
  6207. "yellow": [255, 255, 0],
  6208. "yellowgreen": [154, 205, 50]
  6209. };
  6210. var conversions = createCommonjsModule(function (module) {
  6211. /* MIT license */
  6212. // NOTE: conversions should only return primitive values (i.e. arrays, or
  6213. // values that give correct `typeof` results).
  6214. // do not use box values types (i.e. Number(), String(), etc.)
  6215. var reverseKeywords = {};
  6216. for (var key in colorName) {
  6217. if (colorName.hasOwnProperty(key)) {
  6218. reverseKeywords[colorName[key]] = key;
  6219. }
  6220. }
  6221. var convert = module.exports = {
  6222. rgb: {channels: 3, labels: 'rgb'},
  6223. hsl: {channels: 3, labels: 'hsl'},
  6224. hsv: {channels: 3, labels: 'hsv'},
  6225. hwb: {channels: 3, labels: 'hwb'},
  6226. cmyk: {channels: 4, labels: 'cmyk'},
  6227. xyz: {channels: 3, labels: 'xyz'},
  6228. lab: {channels: 3, labels: 'lab'},
  6229. lch: {channels: 3, labels: 'lch'},
  6230. hex: {channels: 1, labels: ['hex']},
  6231. keyword: {channels: 1, labels: ['keyword']},
  6232. ansi16: {channels: 1, labels: ['ansi16']},
  6233. ansi256: {channels: 1, labels: ['ansi256']},
  6234. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  6235. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  6236. gray: {channels: 1, labels: ['gray']}
  6237. };
  6238. // hide .channels and .labels properties
  6239. for (var model in convert) {
  6240. if (convert.hasOwnProperty(model)) {
  6241. if (!('channels' in convert[model])) {
  6242. throw new Error('missing channels property: ' + model);
  6243. }
  6244. if (!('labels' in convert[model])) {
  6245. throw new Error('missing channel labels property: ' + model);
  6246. }
  6247. if (convert[model].labels.length !== convert[model].channels) {
  6248. throw new Error('channel and label counts mismatch: ' + model);
  6249. }
  6250. var channels = convert[model].channels;
  6251. var labels = convert[model].labels;
  6252. delete convert[model].channels;
  6253. delete convert[model].labels;
  6254. Object.defineProperty(convert[model], 'channels', {value: channels});
  6255. Object.defineProperty(convert[model], 'labels', {value: labels});
  6256. }
  6257. }
  6258. convert.rgb.hsl = function (rgb) {
  6259. var r = rgb[0] / 255;
  6260. var g = rgb[1] / 255;
  6261. var b = rgb[2] / 255;
  6262. var min = Math.min(r, g, b);
  6263. var max = Math.max(r, g, b);
  6264. var delta = max - min;
  6265. var h;
  6266. var s;
  6267. var l;
  6268. if (max === min) {
  6269. h = 0;
  6270. } else if (r === max) {
  6271. h = (g - b) / delta;
  6272. } else if (g === max) {
  6273. h = 2 + (b - r) / delta;
  6274. } else if (b === max) {
  6275. h = 4 + (r - g) / delta;
  6276. }
  6277. h = Math.min(h * 60, 360);
  6278. if (h < 0) {
  6279. h += 360;
  6280. }
  6281. l = (min + max) / 2;
  6282. if (max === min) {
  6283. s = 0;
  6284. } else if (l <= 0.5) {
  6285. s = delta / (max + min);
  6286. } else {
  6287. s = delta / (2 - max - min);
  6288. }
  6289. return [h, s * 100, l * 100];
  6290. };
  6291. convert.rgb.hsv = function (rgb) {
  6292. var rdif;
  6293. var gdif;
  6294. var bdif;
  6295. var h;
  6296. var s;
  6297. var r = rgb[0] / 255;
  6298. var g = rgb[1] / 255;
  6299. var b = rgb[2] / 255;
  6300. var v = Math.max(r, g, b);
  6301. var diff = v - Math.min(r, g, b);
  6302. var diffc = function (c) {
  6303. return (v - c) / 6 / diff + 1 / 2;
  6304. };
  6305. if (diff === 0) {
  6306. h = s = 0;
  6307. } else {
  6308. s = diff / v;
  6309. rdif = diffc(r);
  6310. gdif = diffc(g);
  6311. bdif = diffc(b);
  6312. if (r === v) {
  6313. h = bdif - gdif;
  6314. } else if (g === v) {
  6315. h = (1 / 3) + rdif - bdif;
  6316. } else if (b === v) {
  6317. h = (2 / 3) + gdif - rdif;
  6318. }
  6319. if (h < 0) {
  6320. h += 1;
  6321. } else if (h > 1) {
  6322. h -= 1;
  6323. }
  6324. }
  6325. return [
  6326. h * 360,
  6327. s * 100,
  6328. v * 100
  6329. ];
  6330. };
  6331. convert.rgb.hwb = function (rgb) {
  6332. var r = rgb[0];
  6333. var g = rgb[1];
  6334. var b = rgb[2];
  6335. var h = convert.rgb.hsl(rgb)[0];
  6336. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  6337. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  6338. return [h, w * 100, b * 100];
  6339. };
  6340. convert.rgb.cmyk = function (rgb) {
  6341. var r = rgb[0] / 255;
  6342. var g = rgb[1] / 255;
  6343. var b = rgb[2] / 255;
  6344. var c;
  6345. var m;
  6346. var y;
  6347. var k;
  6348. k = Math.min(1 - r, 1 - g, 1 - b);
  6349. c = (1 - r - k) / (1 - k) || 0;
  6350. m = (1 - g - k) / (1 - k) || 0;
  6351. y = (1 - b - k) / (1 - k) || 0;
  6352. return [c * 100, m * 100, y * 100, k * 100];
  6353. };
  6354. /**
  6355. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  6356. * */
  6357. function comparativeDistance(x, y) {
  6358. return (
  6359. Math.pow(x[0] - y[0], 2) +
  6360. Math.pow(x[1] - y[1], 2) +
  6361. Math.pow(x[2] - y[2], 2)
  6362. );
  6363. }
  6364. convert.rgb.keyword = function (rgb) {
  6365. var reversed = reverseKeywords[rgb];
  6366. if (reversed) {
  6367. return reversed;
  6368. }
  6369. var currentClosestDistance = Infinity;
  6370. var currentClosestKeyword;
  6371. for (var keyword in colorName) {
  6372. if (colorName.hasOwnProperty(keyword)) {
  6373. var value = colorName[keyword];
  6374. // Compute comparative distance
  6375. var distance = comparativeDistance(rgb, value);
  6376. // Check if its less, if so set as closest
  6377. if (distance < currentClosestDistance) {
  6378. currentClosestDistance = distance;
  6379. currentClosestKeyword = keyword;
  6380. }
  6381. }
  6382. }
  6383. return currentClosestKeyword;
  6384. };
  6385. convert.keyword.rgb = function (keyword) {
  6386. return colorName[keyword];
  6387. };
  6388. convert.rgb.xyz = function (rgb) {
  6389. var r = rgb[0] / 255;
  6390. var g = rgb[1] / 255;
  6391. var b = rgb[2] / 255;
  6392. // assume sRGB
  6393. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  6394. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  6395. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  6396. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  6397. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  6398. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  6399. return [x * 100, y * 100, z * 100];
  6400. };
  6401. convert.rgb.lab = function (rgb) {
  6402. var xyz = convert.rgb.xyz(rgb);
  6403. var x = xyz[0];
  6404. var y = xyz[1];
  6405. var z = xyz[2];
  6406. var l;
  6407. var a;
  6408. var b;
  6409. x /= 95.047;
  6410. y /= 100;
  6411. z /= 108.883;
  6412. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  6413. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  6414. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  6415. l = (116 * y) - 16;
  6416. a = 500 * (x - y);
  6417. b = 200 * (y - z);
  6418. return [l, a, b];
  6419. };
  6420. convert.hsl.rgb = function (hsl) {
  6421. var h = hsl[0] / 360;
  6422. var s = hsl[1] / 100;
  6423. var l = hsl[2] / 100;
  6424. var t1;
  6425. var t2;
  6426. var t3;
  6427. var rgb;
  6428. var val;
  6429. if (s === 0) {
  6430. val = l * 255;
  6431. return [val, val, val];
  6432. }
  6433. if (l < 0.5) {
  6434. t2 = l * (1 + s);
  6435. } else {
  6436. t2 = l + s - l * s;
  6437. }
  6438. t1 = 2 * l - t2;
  6439. rgb = [0, 0, 0];
  6440. for (var i = 0; i < 3; i++) {
  6441. t3 = h + 1 / 3 * -(i - 1);
  6442. if (t3 < 0) {
  6443. t3++;
  6444. }
  6445. if (t3 > 1) {
  6446. t3--;
  6447. }
  6448. if (6 * t3 < 1) {
  6449. val = t1 + (t2 - t1) * 6 * t3;
  6450. } else if (2 * t3 < 1) {
  6451. val = t2;
  6452. } else if (3 * t3 < 2) {
  6453. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  6454. } else {
  6455. val = t1;
  6456. }
  6457. rgb[i] = val * 255;
  6458. }
  6459. return rgb;
  6460. };
  6461. convert.hsl.hsv = function (hsl) {
  6462. var h = hsl[0];
  6463. var s = hsl[1] / 100;
  6464. var l = hsl[2] / 100;
  6465. var smin = s;
  6466. var lmin = Math.max(l, 0.01);
  6467. var sv;
  6468. var v;
  6469. l *= 2;
  6470. s *= (l <= 1) ? l : 2 - l;
  6471. smin *= lmin <= 1 ? lmin : 2 - lmin;
  6472. v = (l + s) / 2;
  6473. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  6474. return [h, sv * 100, v * 100];
  6475. };
  6476. convert.hsv.rgb = function (hsv) {
  6477. var h = hsv[0] / 60;
  6478. var s = hsv[1] / 100;
  6479. var v = hsv[2] / 100;
  6480. var hi = Math.floor(h) % 6;
  6481. var f = h - Math.floor(h);
  6482. var p = 255 * v * (1 - s);
  6483. var q = 255 * v * (1 - (s * f));
  6484. var t = 255 * v * (1 - (s * (1 - f)));
  6485. v *= 255;
  6486. switch (hi) {
  6487. case 0:
  6488. return [v, t, p];
  6489. case 1:
  6490. return [q, v, p];
  6491. case 2:
  6492. return [p, v, t];
  6493. case 3:
  6494. return [p, q, v];
  6495. case 4:
  6496. return [t, p, v];
  6497. case 5:
  6498. return [v, p, q];
  6499. }
  6500. };
  6501. convert.hsv.hsl = function (hsv) {
  6502. var h = hsv[0];
  6503. var s = hsv[1] / 100;
  6504. var v = hsv[2] / 100;
  6505. var vmin = Math.max(v, 0.01);
  6506. var lmin;
  6507. var sl;
  6508. var l;
  6509. l = (2 - s) * v;
  6510. lmin = (2 - s) * vmin;
  6511. sl = s * vmin;
  6512. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  6513. sl = sl || 0;
  6514. l /= 2;
  6515. return [h, sl * 100, l * 100];
  6516. };
  6517. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  6518. convert.hwb.rgb = function (hwb) {
  6519. var h = hwb[0] / 360;
  6520. var wh = hwb[1] / 100;
  6521. var bl = hwb[2] / 100;
  6522. var ratio = wh + bl;
  6523. var i;
  6524. var v;
  6525. var f;
  6526. var n;
  6527. // wh + bl cant be > 1
  6528. if (ratio > 1) {
  6529. wh /= ratio;
  6530. bl /= ratio;
  6531. }
  6532. i = Math.floor(6 * h);
  6533. v = 1 - bl;
  6534. f = 6 * h - i;
  6535. if ((i & 0x01) !== 0) {
  6536. f = 1 - f;
  6537. }
  6538. n = wh + f * (v - wh); // linear interpolation
  6539. var r;
  6540. var g;
  6541. var b;
  6542. switch (i) {
  6543. default:
  6544. case 6:
  6545. case 0: r = v; g = n; b = wh; break;
  6546. case 1: r = n; g = v; b = wh; break;
  6547. case 2: r = wh; g = v; b = n; break;
  6548. case 3: r = wh; g = n; b = v; break;
  6549. case 4: r = n; g = wh; b = v; break;
  6550. case 5: r = v; g = wh; b = n; break;
  6551. }
  6552. return [r * 255, g * 255, b * 255];
  6553. };
  6554. convert.cmyk.rgb = function (cmyk) {
  6555. var c = cmyk[0] / 100;
  6556. var m = cmyk[1] / 100;
  6557. var y = cmyk[2] / 100;
  6558. var k = cmyk[3] / 100;
  6559. var r;
  6560. var g;
  6561. var b;
  6562. r = 1 - Math.min(1, c * (1 - k) + k);
  6563. g = 1 - Math.min(1, m * (1 - k) + k);
  6564. b = 1 - Math.min(1, y * (1 - k) + k);
  6565. return [r * 255, g * 255, b * 255];
  6566. };
  6567. convert.xyz.rgb = function (xyz) {
  6568. var x = xyz[0] / 100;
  6569. var y = xyz[1] / 100;
  6570. var z = xyz[2] / 100;
  6571. var r;
  6572. var g;
  6573. var b;
  6574. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  6575. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  6576. b = (x * 0.0557) + (y * -0.204) + (z * 1.0570);
  6577. // assume sRGB
  6578. r = r > 0.0031308
  6579. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  6580. : r * 12.92;
  6581. g = g > 0.0031308
  6582. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  6583. : g * 12.92;
  6584. b = b > 0.0031308
  6585. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  6586. : b * 12.92;
  6587. r = Math.min(Math.max(0, r), 1);
  6588. g = Math.min(Math.max(0, g), 1);
  6589. b = Math.min(Math.max(0, b), 1);
  6590. return [r * 255, g * 255, b * 255];
  6591. };
  6592. convert.xyz.lab = function (xyz) {
  6593. var x = xyz[0];
  6594. var y = xyz[1];
  6595. var z = xyz[2];
  6596. var l;
  6597. var a;
  6598. var b;
  6599. x /= 95.047;
  6600. y /= 100;
  6601. z /= 108.883;
  6602. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  6603. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  6604. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  6605. l = (116 * y) - 16;
  6606. a = 500 * (x - y);
  6607. b = 200 * (y - z);
  6608. return [l, a, b];
  6609. };
  6610. convert.lab.xyz = function (lab) {
  6611. var l = lab[0];
  6612. var a = lab[1];
  6613. var b = lab[2];
  6614. var x;
  6615. var y;
  6616. var z;
  6617. y = (l + 16) / 116;
  6618. x = a / 500 + y;
  6619. z = y - b / 200;
  6620. var y2 = Math.pow(y, 3);
  6621. var x2 = Math.pow(x, 3);
  6622. var z2 = Math.pow(z, 3);
  6623. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  6624. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  6625. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  6626. x *= 95.047;
  6627. y *= 100;
  6628. z *= 108.883;
  6629. return [x, y, z];
  6630. };
  6631. convert.lab.lch = function (lab) {
  6632. var l = lab[0];
  6633. var a = lab[1];
  6634. var b = lab[2];
  6635. var hr;
  6636. var h;
  6637. var c;
  6638. hr = Math.atan2(b, a);
  6639. h = hr * 360 / 2 / Math.PI;
  6640. if (h < 0) {
  6641. h += 360;
  6642. }
  6643. c = Math.sqrt(a * a + b * b);
  6644. return [l, c, h];
  6645. };
  6646. convert.lch.lab = function (lch) {
  6647. var l = lch[0];
  6648. var c = lch[1];
  6649. var h = lch[2];
  6650. var a;
  6651. var b;
  6652. var hr;
  6653. hr = h / 360 * 2 * Math.PI;
  6654. a = c * Math.cos(hr);
  6655. b = c * Math.sin(hr);
  6656. return [l, a, b];
  6657. };
  6658. convert.rgb.ansi16 = function (args) {
  6659. var r = args[0];
  6660. var g = args[1];
  6661. var b = args[2];
  6662. var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  6663. value = Math.round(value / 50);
  6664. if (value === 0) {
  6665. return 30;
  6666. }
  6667. var ansi = 30
  6668. + ((Math.round(b / 255) << 2)
  6669. | (Math.round(g / 255) << 1)
  6670. | Math.round(r / 255));
  6671. if (value === 2) {
  6672. ansi += 60;
  6673. }
  6674. return ansi;
  6675. };
  6676. convert.hsv.ansi16 = function (args) {
  6677. // optimization here; we already know the value and don't need to get
  6678. // it converted for us.
  6679. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  6680. };
  6681. convert.rgb.ansi256 = function (args) {
  6682. var r = args[0];
  6683. var g = args[1];
  6684. var b = args[2];
  6685. // we use the extended greyscale palette here, with the exception of
  6686. // black and white. normal palette only has 4 greyscale shades.
  6687. if (r === g && g === b) {
  6688. if (r < 8) {
  6689. return 16;
  6690. }
  6691. if (r > 248) {
  6692. return 231;
  6693. }
  6694. return Math.round(((r - 8) / 247) * 24) + 232;
  6695. }
  6696. var ansi = 16
  6697. + (36 * Math.round(r / 255 * 5))
  6698. + (6 * Math.round(g / 255 * 5))
  6699. + Math.round(b / 255 * 5);
  6700. return ansi;
  6701. };
  6702. convert.ansi16.rgb = function (args) {
  6703. var color = args % 10;
  6704. // handle greyscale
  6705. if (color === 0 || color === 7) {
  6706. if (args > 50) {
  6707. color += 3.5;
  6708. }
  6709. color = color / 10.5 * 255;
  6710. return [color, color, color];
  6711. }
  6712. var mult = (~~(args > 50) + 1) * 0.5;
  6713. var r = ((color & 1) * mult) * 255;
  6714. var g = (((color >> 1) & 1) * mult) * 255;
  6715. var b = (((color >> 2) & 1) * mult) * 255;
  6716. return [r, g, b];
  6717. };
  6718. convert.ansi256.rgb = function (args) {
  6719. // handle greyscale
  6720. if (args >= 232) {
  6721. var c = (args - 232) * 10 + 8;
  6722. return [c, c, c];
  6723. }
  6724. args -= 16;
  6725. var rem;
  6726. var r = Math.floor(args / 36) / 5 * 255;
  6727. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  6728. var b = (rem % 6) / 5 * 255;
  6729. return [r, g, b];
  6730. };
  6731. convert.rgb.hex = function (args) {
  6732. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  6733. + ((Math.round(args[1]) & 0xFF) << 8)
  6734. + (Math.round(args[2]) & 0xFF);
  6735. var string = integer.toString(16).toUpperCase();
  6736. return '000000'.substring(string.length) + string;
  6737. };
  6738. convert.hex.rgb = function (args) {
  6739. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  6740. if (!match) {
  6741. return [0, 0, 0];
  6742. }
  6743. var colorString = match[0];
  6744. if (match[0].length === 3) {
  6745. colorString = colorString.split('').map(function (char) {
  6746. return char + char;
  6747. }).join('');
  6748. }
  6749. var integer = parseInt(colorString, 16);
  6750. var r = (integer >> 16) & 0xFF;
  6751. var g = (integer >> 8) & 0xFF;
  6752. var b = integer & 0xFF;
  6753. return [r, g, b];
  6754. };
  6755. convert.rgb.hcg = function (rgb) {
  6756. var r = rgb[0] / 255;
  6757. var g = rgb[1] / 255;
  6758. var b = rgb[2] / 255;
  6759. var max = Math.max(Math.max(r, g), b);
  6760. var min = Math.min(Math.min(r, g), b);
  6761. var chroma = (max - min);
  6762. var grayscale;
  6763. var hue;
  6764. if (chroma < 1) {
  6765. grayscale = min / (1 - chroma);
  6766. } else {
  6767. grayscale = 0;
  6768. }
  6769. if (chroma <= 0) {
  6770. hue = 0;
  6771. } else
  6772. if (max === r) {
  6773. hue = ((g - b) / chroma) % 6;
  6774. } else
  6775. if (max === g) {
  6776. hue = 2 + (b - r) / chroma;
  6777. } else {
  6778. hue = 4 + (r - g) / chroma + 4;
  6779. }
  6780. hue /= 6;
  6781. hue %= 1;
  6782. return [hue * 360, chroma * 100, grayscale * 100];
  6783. };
  6784. convert.hsl.hcg = function (hsl) {
  6785. var s = hsl[1] / 100;
  6786. var l = hsl[2] / 100;
  6787. var c = 1;
  6788. var f = 0;
  6789. if (l < 0.5) {
  6790. c = 2.0 * s * l;
  6791. } else {
  6792. c = 2.0 * s * (1.0 - l);
  6793. }
  6794. if (c < 1.0) {
  6795. f = (l - 0.5 * c) / (1.0 - c);
  6796. }
  6797. return [hsl[0], c * 100, f * 100];
  6798. };
  6799. convert.hsv.hcg = function (hsv) {
  6800. var s = hsv[1] / 100;
  6801. var v = hsv[2] / 100;
  6802. var c = s * v;
  6803. var f = 0;
  6804. if (c < 1.0) {
  6805. f = (v - c) / (1 - c);
  6806. }
  6807. return [hsv[0], c * 100, f * 100];
  6808. };
  6809. convert.hcg.rgb = function (hcg) {
  6810. var h = hcg[0] / 360;
  6811. var c = hcg[1] / 100;
  6812. var g = hcg[2] / 100;
  6813. if (c === 0.0) {
  6814. return [g * 255, g * 255, g * 255];
  6815. }
  6816. var pure = [0, 0, 0];
  6817. var hi = (h % 1) * 6;
  6818. var v = hi % 1;
  6819. var w = 1 - v;
  6820. var mg = 0;
  6821. switch (Math.floor(hi)) {
  6822. case 0:
  6823. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  6824. case 1:
  6825. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  6826. case 2:
  6827. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  6828. case 3:
  6829. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  6830. case 4:
  6831. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  6832. default:
  6833. pure[0] = 1; pure[1] = 0; pure[2] = w;
  6834. }
  6835. mg = (1.0 - c) * g;
  6836. return [
  6837. (c * pure[0] + mg) * 255,
  6838. (c * pure[1] + mg) * 255,
  6839. (c * pure[2] + mg) * 255
  6840. ];
  6841. };
  6842. convert.hcg.hsv = function (hcg) {
  6843. var c = hcg[1] / 100;
  6844. var g = hcg[2] / 100;
  6845. var v = c + g * (1.0 - c);
  6846. var f = 0;
  6847. if (v > 0.0) {
  6848. f = c / v;
  6849. }
  6850. return [hcg[0], f * 100, v * 100];
  6851. };
  6852. convert.hcg.hsl = function (hcg) {
  6853. var c = hcg[1] / 100;
  6854. var g = hcg[2] / 100;
  6855. var l = g * (1.0 - c) + 0.5 * c;
  6856. var s = 0;
  6857. if (l > 0.0 && l < 0.5) {
  6858. s = c / (2 * l);
  6859. } else
  6860. if (l >= 0.5 && l < 1.0) {
  6861. s = c / (2 * (1 - l));
  6862. }
  6863. return [hcg[0], s * 100, l * 100];
  6864. };
  6865. convert.hcg.hwb = function (hcg) {
  6866. var c = hcg[1] / 100;
  6867. var g = hcg[2] / 100;
  6868. var v = c + g * (1.0 - c);
  6869. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  6870. };
  6871. convert.hwb.hcg = function (hwb) {
  6872. var w = hwb[1] / 100;
  6873. var b = hwb[2] / 100;
  6874. var v = 1 - b;
  6875. var c = v - w;
  6876. var g = 0;
  6877. if (c < 1) {
  6878. g = (v - c) / (1 - c);
  6879. }
  6880. return [hwb[0], c * 100, g * 100];
  6881. };
  6882. convert.apple.rgb = function (apple) {
  6883. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  6884. };
  6885. convert.rgb.apple = function (rgb) {
  6886. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  6887. };
  6888. convert.gray.rgb = function (args) {
  6889. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  6890. };
  6891. convert.gray.hsl = convert.gray.hsv = function (args) {
  6892. return [0, 0, args[0]];
  6893. };
  6894. convert.gray.hwb = function (gray) {
  6895. return [0, 100, gray[0]];
  6896. };
  6897. convert.gray.cmyk = function (gray) {
  6898. return [0, 0, 0, gray[0]];
  6899. };
  6900. convert.gray.lab = function (gray) {
  6901. return [gray[0], 0, 0];
  6902. };
  6903. convert.gray.hex = function (gray) {
  6904. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  6905. var integer = (val << 16) + (val << 8) + val;
  6906. var string = integer.toString(16).toUpperCase();
  6907. return '000000'.substring(string.length) + string;
  6908. };
  6909. convert.rgb.gray = function (rgb) {
  6910. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  6911. return [val / 255 * 100];
  6912. };
  6913. });
  6914. conversions.rgb;
  6915. conversions.hsl;
  6916. conversions.hsv;
  6917. conversions.hwb;
  6918. conversions.cmyk;
  6919. conversions.xyz;
  6920. conversions.lab;
  6921. conversions.lch;
  6922. conversions.hex;
  6923. conversions.keyword;
  6924. conversions.ansi16;
  6925. conversions.ansi256;
  6926. conversions.hcg;
  6927. conversions.apple;
  6928. conversions.gray;
  6929. /*
  6930. this function routes a model to all other models.
  6931. all functions that are routed have a property `.conversion` attached
  6932. to the returned synthetic function. This property is an array
  6933. of strings, each with the steps in between the 'from' and 'to'
  6934. color models (inclusive).
  6935. conversions that are not possible simply are not included.
  6936. */
  6937. function buildGraph() {
  6938. var graph = {};
  6939. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  6940. var models = Object.keys(conversions);
  6941. for (var len = models.length, i = 0; i < len; i++) {
  6942. graph[models[i]] = {
  6943. // http://jsperf.com/1-vs-infinity
  6944. // micro-opt, but this is simple.
  6945. distance: -1,
  6946. parent: null
  6947. };
  6948. }
  6949. return graph;
  6950. }
  6951. // https://en.wikipedia.org/wiki/Breadth-first_search
  6952. function deriveBFS(fromModel) {
  6953. var graph = buildGraph();
  6954. var queue = [fromModel]; // unshift -> queue -> pop
  6955. graph[fromModel].distance = 0;
  6956. while (queue.length) {
  6957. var current = queue.pop();
  6958. var adjacents = Object.keys(conversions[current]);
  6959. for (var len = adjacents.length, i = 0; i < len; i++) {
  6960. var adjacent = adjacents[i];
  6961. var node = graph[adjacent];
  6962. if (node.distance === -1) {
  6963. node.distance = graph[current].distance + 1;
  6964. node.parent = current;
  6965. queue.unshift(adjacent);
  6966. }
  6967. }
  6968. }
  6969. return graph;
  6970. }
  6971. function link(from, to) {
  6972. return function (args) {
  6973. return to(from(args));
  6974. };
  6975. }
  6976. function wrapConversion(toModel, graph) {
  6977. var path = [graph[toModel].parent, toModel];
  6978. var fn = conversions[graph[toModel].parent][toModel];
  6979. var cur = graph[toModel].parent;
  6980. while (graph[cur].parent) {
  6981. path.unshift(graph[cur].parent);
  6982. fn = link(conversions[graph[cur].parent][cur], fn);
  6983. cur = graph[cur].parent;
  6984. }
  6985. fn.conversion = path;
  6986. return fn;
  6987. }
  6988. var route = function (fromModel) {
  6989. var graph = deriveBFS(fromModel);
  6990. var conversion = {};
  6991. var models = Object.keys(graph);
  6992. for (var len = models.length, i = 0; i < len; i++) {
  6993. var toModel = models[i];
  6994. var node = graph[toModel];
  6995. if (node.parent === null) {
  6996. // no possible conversion, or this node is the source model.
  6997. continue;
  6998. }
  6999. conversion[toModel] = wrapConversion(toModel, graph);
  7000. }
  7001. return conversion;
  7002. };
  7003. var convert = {};
  7004. var models = Object.keys(conversions);
  7005. function wrapRaw(fn) {
  7006. var wrappedFn = function (args) {
  7007. if (args === undefined || args === null) {
  7008. return args;
  7009. }
  7010. if (arguments.length > 1) {
  7011. args = Array.prototype.slice.call(arguments);
  7012. }
  7013. return fn(args);
  7014. };
  7015. // preserve .conversion property if there is one
  7016. if ('conversion' in fn) {
  7017. wrappedFn.conversion = fn.conversion;
  7018. }
  7019. return wrappedFn;
  7020. }
  7021. function wrapRounded(fn) {
  7022. var wrappedFn = function (args) {
  7023. if (args === undefined || args === null) {
  7024. return args;
  7025. }
  7026. if (arguments.length > 1) {
  7027. args = Array.prototype.slice.call(arguments);
  7028. }
  7029. var result = fn(args);
  7030. // we're assuming the result is an array here.
  7031. // see notice in conversions.js; don't use box types
  7032. // in conversion functions.
  7033. if (typeof result === 'object') {
  7034. for (var len = result.length, i = 0; i < len; i++) {
  7035. result[i] = Math.round(result[i]);
  7036. }
  7037. }
  7038. return result;
  7039. };
  7040. // preserve .conversion property if there is one
  7041. if ('conversion' in fn) {
  7042. wrappedFn.conversion = fn.conversion;
  7043. }
  7044. return wrappedFn;
  7045. }
  7046. models.forEach(function (fromModel) {
  7047. convert[fromModel] = {};
  7048. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  7049. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  7050. var routes = route(fromModel);
  7051. var routeModels = Object.keys(routes);
  7052. routeModels.forEach(function (toModel) {
  7053. var fn = routes[toModel];
  7054. convert[fromModel][toModel] = wrapRounded(fn);
  7055. convert[fromModel][toModel].raw = wrapRaw(fn);
  7056. });
  7057. });
  7058. var colorConvert = convert;
  7059. var colorName$1 = {
  7060. "aliceblue": [240, 248, 255],
  7061. "antiquewhite": [250, 235, 215],
  7062. "aqua": [0, 255, 255],
  7063. "aquamarine": [127, 255, 212],
  7064. "azure": [240, 255, 255],
  7065. "beige": [245, 245, 220],
  7066. "bisque": [255, 228, 196],
  7067. "black": [0, 0, 0],
  7068. "blanchedalmond": [255, 235, 205],
  7069. "blue": [0, 0, 255],
  7070. "blueviolet": [138, 43, 226],
  7071. "brown": [165, 42, 42],
  7072. "burlywood": [222, 184, 135],
  7073. "cadetblue": [95, 158, 160],
  7074. "chartreuse": [127, 255, 0],
  7075. "chocolate": [210, 105, 30],
  7076. "coral": [255, 127, 80],
  7077. "cornflowerblue": [100, 149, 237],
  7078. "cornsilk": [255, 248, 220],
  7079. "crimson": [220, 20, 60],
  7080. "cyan": [0, 255, 255],
  7081. "darkblue": [0, 0, 139],
  7082. "darkcyan": [0, 139, 139],
  7083. "darkgoldenrod": [184, 134, 11],
  7084. "darkgray": [169, 169, 169],
  7085. "darkgreen": [0, 100, 0],
  7086. "darkgrey": [169, 169, 169],
  7087. "darkkhaki": [189, 183, 107],
  7088. "darkmagenta": [139, 0, 139],
  7089. "darkolivegreen": [85, 107, 47],
  7090. "darkorange": [255, 140, 0],
  7091. "darkorchid": [153, 50, 204],
  7092. "darkred": [139, 0, 0],
  7093. "darksalmon": [233, 150, 122],
  7094. "darkseagreen": [143, 188, 143],
  7095. "darkslateblue": [72, 61, 139],
  7096. "darkslategray": [47, 79, 79],
  7097. "darkslategrey": [47, 79, 79],
  7098. "darkturquoise": [0, 206, 209],
  7099. "darkviolet": [148, 0, 211],
  7100. "deeppink": [255, 20, 147],
  7101. "deepskyblue": [0, 191, 255],
  7102. "dimgray": [105, 105, 105],
  7103. "dimgrey": [105, 105, 105],
  7104. "dodgerblue": [30, 144, 255],
  7105. "firebrick": [178, 34, 34],
  7106. "floralwhite": [255, 250, 240],
  7107. "forestgreen": [34, 139, 34],
  7108. "fuchsia": [255, 0, 255],
  7109. "gainsboro": [220, 220, 220],
  7110. "ghostwhite": [248, 248, 255],
  7111. "gold": [255, 215, 0],
  7112. "goldenrod": [218, 165, 32],
  7113. "gray": [128, 128, 128],
  7114. "green": [0, 128, 0],
  7115. "greenyellow": [173, 255, 47],
  7116. "grey": [128, 128, 128],
  7117. "honeydew": [240, 255, 240],
  7118. "hotpink": [255, 105, 180],
  7119. "indianred": [205, 92, 92],
  7120. "indigo": [75, 0, 130],
  7121. "ivory": [255, 255, 240],
  7122. "khaki": [240, 230, 140],
  7123. "lavender": [230, 230, 250],
  7124. "lavenderblush": [255, 240, 245],
  7125. "lawngreen": [124, 252, 0],
  7126. "lemonchiffon": [255, 250, 205],
  7127. "lightblue": [173, 216, 230],
  7128. "lightcoral": [240, 128, 128],
  7129. "lightcyan": [224, 255, 255],
  7130. "lightgoldenrodyellow": [250, 250, 210],
  7131. "lightgray": [211, 211, 211],
  7132. "lightgreen": [144, 238, 144],
  7133. "lightgrey": [211, 211, 211],
  7134. "lightpink": [255, 182, 193],
  7135. "lightsalmon": [255, 160, 122],
  7136. "lightseagreen": [32, 178, 170],
  7137. "lightskyblue": [135, 206, 250],
  7138. "lightslategray": [119, 136, 153],
  7139. "lightslategrey": [119, 136, 153],
  7140. "lightsteelblue": [176, 196, 222],
  7141. "lightyellow": [255, 255, 224],
  7142. "lime": [0, 255, 0],
  7143. "limegreen": [50, 205, 50],
  7144. "linen": [250, 240, 230],
  7145. "magenta": [255, 0, 255],
  7146. "maroon": [128, 0, 0],
  7147. "mediumaquamarine": [102, 205, 170],
  7148. "mediumblue": [0, 0, 205],
  7149. "mediumorchid": [186, 85, 211],
  7150. "mediumpurple": [147, 112, 219],
  7151. "mediumseagreen": [60, 179, 113],
  7152. "mediumslateblue": [123, 104, 238],
  7153. "mediumspringgreen": [0, 250, 154],
  7154. "mediumturquoise": [72, 209, 204],
  7155. "mediumvioletred": [199, 21, 133],
  7156. "midnightblue": [25, 25, 112],
  7157. "mintcream": [245, 255, 250],
  7158. "mistyrose": [255, 228, 225],
  7159. "moccasin": [255, 228, 181],
  7160. "navajowhite": [255, 222, 173],
  7161. "navy": [0, 0, 128],
  7162. "oldlace": [253, 245, 230],
  7163. "olive": [128, 128, 0],
  7164. "olivedrab": [107, 142, 35],
  7165. "orange": [255, 165, 0],
  7166. "orangered": [255, 69, 0],
  7167. "orchid": [218, 112, 214],
  7168. "palegoldenrod": [238, 232, 170],
  7169. "palegreen": [152, 251, 152],
  7170. "paleturquoise": [175, 238, 238],
  7171. "palevioletred": [219, 112, 147],
  7172. "papayawhip": [255, 239, 213],
  7173. "peachpuff": [255, 218, 185],
  7174. "peru": [205, 133, 63],
  7175. "pink": [255, 192, 203],
  7176. "plum": [221, 160, 221],
  7177. "powderblue": [176, 224, 230],
  7178. "purple": [128, 0, 128],
  7179. "rebeccapurple": [102, 51, 153],
  7180. "red": [255, 0, 0],
  7181. "rosybrown": [188, 143, 143],
  7182. "royalblue": [65, 105, 225],
  7183. "saddlebrown": [139, 69, 19],
  7184. "salmon": [250, 128, 114],
  7185. "sandybrown": [244, 164, 96],
  7186. "seagreen": [46, 139, 87],
  7187. "seashell": [255, 245, 238],
  7188. "sienna": [160, 82, 45],
  7189. "silver": [192, 192, 192],
  7190. "skyblue": [135, 206, 235],
  7191. "slateblue": [106, 90, 205],
  7192. "slategray": [112, 128, 144],
  7193. "slategrey": [112, 128, 144],
  7194. "snow": [255, 250, 250],
  7195. "springgreen": [0, 255, 127],
  7196. "steelblue": [70, 130, 180],
  7197. "tan": [210, 180, 140],
  7198. "teal": [0, 128, 128],
  7199. "thistle": [216, 191, 216],
  7200. "tomato": [255, 99, 71],
  7201. "turquoise": [64, 224, 208],
  7202. "violet": [238, 130, 238],
  7203. "wheat": [245, 222, 179],
  7204. "white": [255, 255, 255],
  7205. "whitesmoke": [245, 245, 245],
  7206. "yellow": [255, 255, 0],
  7207. "yellowgreen": [154, 205, 50]
  7208. };
  7209. /* MIT license */
  7210. var colorString = {
  7211. getRgba: getRgba,
  7212. getHsla: getHsla,
  7213. getRgb: getRgb,
  7214. getHsl: getHsl,
  7215. getHwb: getHwb,
  7216. getAlpha: getAlpha,
  7217. hexString: hexString,
  7218. rgbString: rgbString,
  7219. rgbaString: rgbaString,
  7220. percentString: percentString,
  7221. percentaString: percentaString,
  7222. hslString: hslString,
  7223. hslaString: hslaString,
  7224. hwbString: hwbString,
  7225. keyword: keyword
  7226. };
  7227. function getRgba(string) {
  7228. if (!string) {
  7229. return;
  7230. }
  7231. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  7232. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  7233. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  7234. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  7235. keyword = /(\w+)/;
  7236. var rgb = [0, 0, 0],
  7237. a = 1,
  7238. match = string.match(abbr),
  7239. hexAlpha = "";
  7240. if (match) {
  7241. match = match[1];
  7242. hexAlpha = match[3];
  7243. for (var i = 0; i < rgb.length; i++) {
  7244. rgb[i] = parseInt(match[i] + match[i], 16);
  7245. }
  7246. if (hexAlpha) {
  7247. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  7248. }
  7249. }
  7250. else if (match = string.match(hex)) {
  7251. hexAlpha = match[2];
  7252. match = match[1];
  7253. for (var i = 0; i < rgb.length; i++) {
  7254. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  7255. }
  7256. if (hexAlpha) {
  7257. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  7258. }
  7259. }
  7260. else if (match = string.match(rgba)) {
  7261. for (var i = 0; i < rgb.length; i++) {
  7262. rgb[i] = parseInt(match[i + 1]);
  7263. }
  7264. a = parseFloat(match[4]);
  7265. }
  7266. else if (match = string.match(per)) {
  7267. for (var i = 0; i < rgb.length; i++) {
  7268. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  7269. }
  7270. a = parseFloat(match[4]);
  7271. }
  7272. else if (match = string.match(keyword)) {
  7273. if (match[1] == "transparent") {
  7274. return [0, 0, 0, 0];
  7275. }
  7276. rgb = colorName$1[match[1]];
  7277. if (!rgb) {
  7278. return;
  7279. }
  7280. }
  7281. for (var i = 0; i < rgb.length; i++) {
  7282. rgb[i] = scale(rgb[i], 0, 255);
  7283. }
  7284. if (!a && a != 0) {
  7285. a = 1;
  7286. }
  7287. else {
  7288. a = scale(a, 0, 1);
  7289. }
  7290. rgb[3] = a;
  7291. return rgb;
  7292. }
  7293. function getHsla(string) {
  7294. if (!string) {
  7295. return;
  7296. }
  7297. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  7298. var match = string.match(hsl);
  7299. if (match) {
  7300. var alpha = parseFloat(match[4]);
  7301. var h = scale(parseInt(match[1]), 0, 360),
  7302. s = scale(parseFloat(match[2]), 0, 100),
  7303. l = scale(parseFloat(match[3]), 0, 100),
  7304. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  7305. return [h, s, l, a];
  7306. }
  7307. }
  7308. function getHwb(string) {
  7309. if (!string) {
  7310. return;
  7311. }
  7312. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  7313. var match = string.match(hwb);
  7314. if (match) {
  7315. var alpha = parseFloat(match[4]);
  7316. var h = scale(parseInt(match[1]), 0, 360),
  7317. w = scale(parseFloat(match[2]), 0, 100),
  7318. b = scale(parseFloat(match[3]), 0, 100),
  7319. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  7320. return [h, w, b, a];
  7321. }
  7322. }
  7323. function getRgb(string) {
  7324. var rgba = getRgba(string);
  7325. return rgba && rgba.slice(0, 3);
  7326. }
  7327. function getHsl(string) {
  7328. var hsla = getHsla(string);
  7329. return hsla && hsla.slice(0, 3);
  7330. }
  7331. function getAlpha(string) {
  7332. var vals = getRgba(string);
  7333. if (vals) {
  7334. return vals[3];
  7335. }
  7336. else if (vals = getHsla(string)) {
  7337. return vals[3];
  7338. }
  7339. else if (vals = getHwb(string)) {
  7340. return vals[3];
  7341. }
  7342. }
  7343. // generators
  7344. function hexString(rgba, a) {
  7345. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  7346. return "#" + hexDouble(rgba[0])
  7347. + hexDouble(rgba[1])
  7348. + hexDouble(rgba[2])
  7349. + (
  7350. (a >= 0 && a < 1)
  7351. ? hexDouble(Math.round(a * 255))
  7352. : ""
  7353. );
  7354. }
  7355. function rgbString(rgba, alpha) {
  7356. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  7357. return rgbaString(rgba, alpha);
  7358. }
  7359. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  7360. }
  7361. function rgbaString(rgba, alpha) {
  7362. if (alpha === undefined) {
  7363. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  7364. }
  7365. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  7366. + ", " + alpha + ")";
  7367. }
  7368. function percentString(rgba, alpha) {
  7369. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  7370. return percentaString(rgba, alpha);
  7371. }
  7372. var r = Math.round(rgba[0]/255 * 100),
  7373. g = Math.round(rgba[1]/255 * 100),
  7374. b = Math.round(rgba[2]/255 * 100);
  7375. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  7376. }
  7377. function percentaString(rgba, alpha) {
  7378. var r = Math.round(rgba[0]/255 * 100),
  7379. g = Math.round(rgba[1]/255 * 100),
  7380. b = Math.round(rgba[2]/255 * 100);
  7381. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  7382. }
  7383. function hslString(hsla, alpha) {
  7384. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  7385. return hslaString(hsla, alpha);
  7386. }
  7387. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  7388. }
  7389. function hslaString(hsla, alpha) {
  7390. if (alpha === undefined) {
  7391. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  7392. }
  7393. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  7394. + alpha + ")";
  7395. }
  7396. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  7397. // (hwb have alpha optional & 1 is default value)
  7398. function hwbString(hwb, alpha) {
  7399. if (alpha === undefined) {
  7400. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  7401. }
  7402. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  7403. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  7404. }
  7405. function keyword(rgb) {
  7406. return reverseNames[rgb.slice(0, 3)];
  7407. }
  7408. // helpers
  7409. function scale(num, min, max) {
  7410. return Math.min(Math.max(min, num), max);
  7411. }
  7412. function hexDouble(num) {
  7413. var str = num.toString(16).toUpperCase();
  7414. return (str.length < 2) ? "0" + str : str;
  7415. }
  7416. //create a list of reverse color names
  7417. var reverseNames = {};
  7418. for (var name in colorName$1) {
  7419. reverseNames[colorName$1[name]] = name;
  7420. }
  7421. /* MIT license */
  7422. var Color = function (obj) {
  7423. if (obj instanceof Color) {
  7424. return obj;
  7425. }
  7426. if (!(this instanceof Color)) {
  7427. return new Color(obj);
  7428. }
  7429. this.valid = false;
  7430. this.values = {
  7431. rgb: [0, 0, 0],
  7432. hsl: [0, 0, 0],
  7433. hsv: [0, 0, 0],
  7434. hwb: [0, 0, 0],
  7435. cmyk: [0, 0, 0, 0],
  7436. alpha: 1
  7437. };
  7438. // parse Color() argument
  7439. var vals;
  7440. if (typeof obj === 'string') {
  7441. vals = colorString.getRgba(obj);
  7442. if (vals) {
  7443. this.setValues('rgb', vals);
  7444. } else if (vals = colorString.getHsla(obj)) {
  7445. this.setValues('hsl', vals);
  7446. } else if (vals = colorString.getHwb(obj)) {
  7447. this.setValues('hwb', vals);
  7448. }
  7449. } else if (typeof obj === 'object') {
  7450. vals = obj;
  7451. if (vals.r !== undefined || vals.red !== undefined) {
  7452. this.setValues('rgb', vals);
  7453. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  7454. this.setValues('hsl', vals);
  7455. } else if (vals.v !== undefined || vals.value !== undefined) {
  7456. this.setValues('hsv', vals);
  7457. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  7458. this.setValues('hwb', vals);
  7459. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  7460. this.setValues('cmyk', vals);
  7461. }
  7462. }
  7463. };
  7464. Color.prototype = {
  7465. isValid: function () {
  7466. return this.valid;
  7467. },
  7468. rgb: function () {
  7469. return this.setSpace('rgb', arguments);
  7470. },
  7471. hsl: function () {
  7472. return this.setSpace('hsl', arguments);
  7473. },
  7474. hsv: function () {
  7475. return this.setSpace('hsv', arguments);
  7476. },
  7477. hwb: function () {
  7478. return this.setSpace('hwb', arguments);
  7479. },
  7480. cmyk: function () {
  7481. return this.setSpace('cmyk', arguments);
  7482. },
  7483. rgbArray: function () {
  7484. return this.values.rgb;
  7485. },
  7486. hslArray: function () {
  7487. return this.values.hsl;
  7488. },
  7489. hsvArray: function () {
  7490. return this.values.hsv;
  7491. },
  7492. hwbArray: function () {
  7493. var values = this.values;
  7494. if (values.alpha !== 1) {
  7495. return values.hwb.concat([values.alpha]);
  7496. }
  7497. return values.hwb;
  7498. },
  7499. cmykArray: function () {
  7500. return this.values.cmyk;
  7501. },
  7502. rgbaArray: function () {
  7503. var values = this.values;
  7504. return values.rgb.concat([values.alpha]);
  7505. },
  7506. hslaArray: function () {
  7507. var values = this.values;
  7508. return values.hsl.concat([values.alpha]);
  7509. },
  7510. alpha: function (val) {
  7511. if (val === undefined) {
  7512. return this.values.alpha;
  7513. }
  7514. this.setValues('alpha', val);
  7515. return this;
  7516. },
  7517. red: function (val) {
  7518. return this.setChannel('rgb', 0, val);
  7519. },
  7520. green: function (val) {
  7521. return this.setChannel('rgb', 1, val);
  7522. },
  7523. blue: function (val) {
  7524. return this.setChannel('rgb', 2, val);
  7525. },
  7526. hue: function (val) {
  7527. if (val) {
  7528. val %= 360;
  7529. val = val < 0 ? 360 + val : val;
  7530. }
  7531. return this.setChannel('hsl', 0, val);
  7532. },
  7533. saturation: function (val) {
  7534. return this.setChannel('hsl', 1, val);
  7535. },
  7536. lightness: function (val) {
  7537. return this.setChannel('hsl', 2, val);
  7538. },
  7539. saturationv: function (val) {
  7540. return this.setChannel('hsv', 1, val);
  7541. },
  7542. whiteness: function (val) {
  7543. return this.setChannel('hwb', 1, val);
  7544. },
  7545. blackness: function (val) {
  7546. return this.setChannel('hwb', 2, val);
  7547. },
  7548. value: function (val) {
  7549. return this.setChannel('hsv', 2, val);
  7550. },
  7551. cyan: function (val) {
  7552. return this.setChannel('cmyk', 0, val);
  7553. },
  7554. magenta: function (val) {
  7555. return this.setChannel('cmyk', 1, val);
  7556. },
  7557. yellow: function (val) {
  7558. return this.setChannel('cmyk', 2, val);
  7559. },
  7560. black: function (val) {
  7561. return this.setChannel('cmyk', 3, val);
  7562. },
  7563. hexString: function () {
  7564. return colorString.hexString(this.values.rgb);
  7565. },
  7566. rgbString: function () {
  7567. return colorString.rgbString(this.values.rgb, this.values.alpha);
  7568. },
  7569. rgbaString: function () {
  7570. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  7571. },
  7572. percentString: function () {
  7573. return colorString.percentString(this.values.rgb, this.values.alpha);
  7574. },
  7575. hslString: function () {
  7576. return colorString.hslString(this.values.hsl, this.values.alpha);
  7577. },
  7578. hslaString: function () {
  7579. return colorString.hslaString(this.values.hsl, this.values.alpha);
  7580. },
  7581. hwbString: function () {
  7582. return colorString.hwbString(this.values.hwb, this.values.alpha);
  7583. },
  7584. keyword: function () {
  7585. return colorString.keyword(this.values.rgb, this.values.alpha);
  7586. },
  7587. rgbNumber: function () {
  7588. var rgb = this.values.rgb;
  7589. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  7590. },
  7591. luminosity: function () {
  7592. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  7593. var rgb = this.values.rgb;
  7594. var lum = [];
  7595. for (var i = 0; i < rgb.length; i++) {
  7596. var chan = rgb[i] / 255;
  7597. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  7598. }
  7599. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  7600. },
  7601. contrast: function (color2) {
  7602. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  7603. var lum1 = this.luminosity();
  7604. var lum2 = color2.luminosity();
  7605. if (lum1 > lum2) {
  7606. return (lum1 + 0.05) / (lum2 + 0.05);
  7607. }
  7608. return (lum2 + 0.05) / (lum1 + 0.05);
  7609. },
  7610. level: function (color2) {
  7611. var contrastRatio = this.contrast(color2);
  7612. if (contrastRatio >= 7.1) {
  7613. return 'AAA';
  7614. }
  7615. return (contrastRatio >= 4.5) ? 'AA' : '';
  7616. },
  7617. dark: function () {
  7618. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  7619. var rgb = this.values.rgb;
  7620. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  7621. return yiq < 128;
  7622. },
  7623. light: function () {
  7624. return !this.dark();
  7625. },
  7626. negate: function () {
  7627. var rgb = [];
  7628. for (var i = 0; i < 3; i++) {
  7629. rgb[i] = 255 - this.values.rgb[i];
  7630. }
  7631. this.setValues('rgb', rgb);
  7632. return this;
  7633. },
  7634. lighten: function (ratio) {
  7635. var hsl = this.values.hsl;
  7636. hsl[2] += hsl[2] * ratio;
  7637. this.setValues('hsl', hsl);
  7638. return this;
  7639. },
  7640. darken: function (ratio) {
  7641. var hsl = this.values.hsl;
  7642. hsl[2] -= hsl[2] * ratio;
  7643. this.setValues('hsl', hsl);
  7644. return this;
  7645. },
  7646. saturate: function (ratio) {
  7647. var hsl = this.values.hsl;
  7648. hsl[1] += hsl[1] * ratio;
  7649. this.setValues('hsl', hsl);
  7650. return this;
  7651. },
  7652. desaturate: function (ratio) {
  7653. var hsl = this.values.hsl;
  7654. hsl[1] -= hsl[1] * ratio;
  7655. this.setValues('hsl', hsl);
  7656. return this;
  7657. },
  7658. whiten: function (ratio) {
  7659. var hwb = this.values.hwb;
  7660. hwb[1] += hwb[1] * ratio;
  7661. this.setValues('hwb', hwb);
  7662. return this;
  7663. },
  7664. blacken: function (ratio) {
  7665. var hwb = this.values.hwb;
  7666. hwb[2] += hwb[2] * ratio;
  7667. this.setValues('hwb', hwb);
  7668. return this;
  7669. },
  7670. greyscale: function () {
  7671. var rgb = this.values.rgb;
  7672. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  7673. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  7674. this.setValues('rgb', [val, val, val]);
  7675. return this;
  7676. },
  7677. clearer: function (ratio) {
  7678. var alpha = this.values.alpha;
  7679. this.setValues('alpha', alpha - (alpha * ratio));
  7680. return this;
  7681. },
  7682. opaquer: function (ratio) {
  7683. var alpha = this.values.alpha;
  7684. this.setValues('alpha', alpha + (alpha * ratio));
  7685. return this;
  7686. },
  7687. rotate: function (degrees) {
  7688. var hsl = this.values.hsl;
  7689. var hue = (hsl[0] + degrees) % 360;
  7690. hsl[0] = hue < 0 ? 360 + hue : hue;
  7691. this.setValues('hsl', hsl);
  7692. return this;
  7693. },
  7694. /**
  7695. * Ported from sass implementation in C
  7696. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  7697. */
  7698. mix: function (mixinColor, weight) {
  7699. var color1 = this;
  7700. var color2 = mixinColor;
  7701. var p = weight === undefined ? 0.5 : weight;
  7702. var w = 2 * p - 1;
  7703. var a = color1.alpha() - color2.alpha();
  7704. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  7705. var w2 = 1 - w1;
  7706. return this
  7707. .rgb(
  7708. w1 * color1.red() + w2 * color2.red(),
  7709. w1 * color1.green() + w2 * color2.green(),
  7710. w1 * color1.blue() + w2 * color2.blue()
  7711. )
  7712. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  7713. },
  7714. toJSON: function () {
  7715. return this.rgb();
  7716. },
  7717. clone: function () {
  7718. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  7719. // making the final build way to big to embed in Chart.js. So let's do it manually,
  7720. // assuming that values to clone are 1 dimension arrays containing only numbers,
  7721. // except 'alpha' which is a number.
  7722. var result = new Color();
  7723. var source = this.values;
  7724. var target = result.values;
  7725. var value, type;
  7726. for (var prop in source) {
  7727. if (source.hasOwnProperty(prop)) {
  7728. value = source[prop];
  7729. type = ({}).toString.call(value);
  7730. if (type === '[object Array]') {
  7731. target[prop] = value.slice(0);
  7732. } else if (type === '[object Number]') {
  7733. target[prop] = value;
  7734. } else {
  7735. console.error('unexpected color value:', value);
  7736. }
  7737. }
  7738. }
  7739. return result;
  7740. }
  7741. };
  7742. Color.prototype.spaces = {
  7743. rgb: ['red', 'green', 'blue'],
  7744. hsl: ['hue', 'saturation', 'lightness'],
  7745. hsv: ['hue', 'saturation', 'value'],
  7746. hwb: ['hue', 'whiteness', 'blackness'],
  7747. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  7748. };
  7749. Color.prototype.maxes = {
  7750. rgb: [255, 255, 255],
  7751. hsl: [360, 100, 100],
  7752. hsv: [360, 100, 100],
  7753. hwb: [360, 100, 100],
  7754. cmyk: [100, 100, 100, 100]
  7755. };
  7756. Color.prototype.getValues = function (space) {
  7757. var values = this.values;
  7758. var vals = {};
  7759. for (var i = 0; i < space.length; i++) {
  7760. vals[space.charAt(i)] = values[space][i];
  7761. }
  7762. if (values.alpha !== 1) {
  7763. vals.a = values.alpha;
  7764. }
  7765. // {r: 255, g: 255, b: 255, a: 0.4}
  7766. return vals;
  7767. };
  7768. Color.prototype.setValues = function (space, vals) {
  7769. var values = this.values;
  7770. var spaces = this.spaces;
  7771. var maxes = this.maxes;
  7772. var alpha = 1;
  7773. var i;
  7774. this.valid = true;
  7775. if (space === 'alpha') {
  7776. alpha = vals;
  7777. } else if (vals.length) {
  7778. // [10, 10, 10]
  7779. values[space] = vals.slice(0, space.length);
  7780. alpha = vals[space.length];
  7781. } else if (vals[space.charAt(0)] !== undefined) {
  7782. // {r: 10, g: 10, b: 10}
  7783. for (i = 0; i < space.length; i++) {
  7784. values[space][i] = vals[space.charAt(i)];
  7785. }
  7786. alpha = vals.a;
  7787. } else if (vals[spaces[space][0]] !== undefined) {
  7788. // {red: 10, green: 10, blue: 10}
  7789. var chans = spaces[space];
  7790. for (i = 0; i < space.length; i++) {
  7791. values[space][i] = vals[chans[i]];
  7792. }
  7793. alpha = vals.alpha;
  7794. }
  7795. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  7796. if (space === 'alpha') {
  7797. return false;
  7798. }
  7799. var capped;
  7800. // cap values of the space prior converting all values
  7801. for (i = 0; i < space.length; i++) {
  7802. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  7803. values[space][i] = Math.round(capped);
  7804. }
  7805. // convert to all the other color spaces
  7806. for (var sname in spaces) {
  7807. if (sname !== space) {
  7808. values[sname] = colorConvert[space][sname](values[space]);
  7809. }
  7810. }
  7811. return true;
  7812. };
  7813. Color.prototype.setSpace = function (space, args) {
  7814. var vals = args[0];
  7815. if (vals === undefined) {
  7816. // color.rgb()
  7817. return this.getValues(space);
  7818. }
  7819. // color.rgb(10, 10, 10)
  7820. if (typeof vals === 'number') {
  7821. vals = Array.prototype.slice.call(args);
  7822. }
  7823. this.setValues(space, vals);
  7824. return this;
  7825. };
  7826. Color.prototype.setChannel = function (space, index, val) {
  7827. var svalues = this.values[space];
  7828. if (val === undefined) {
  7829. // color.red()
  7830. return svalues[index];
  7831. } else if (val === svalues[index]) {
  7832. // color.red(color.red())
  7833. return this;
  7834. }
  7835. // color.red(100)
  7836. svalues[index] = val;
  7837. this.setValues(space, svalues);
  7838. return this;
  7839. };
  7840. if (typeof window !== 'undefined') {
  7841. window.Color = Color;
  7842. }
  7843. var chartjsColor = Color;
  7844. function isValidKey(key) {
  7845. return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;
  7846. }
  7847. /**
  7848. * @namespace Chart.helpers
  7849. */
  7850. var helpers = {
  7851. /**
  7852. * An empty function that can be used, for example, for optional callback.
  7853. */
  7854. noop: function() {},
  7855. /**
  7856. * Returns a unique id, sequentially generated from a global variable.
  7857. * @returns {number}
  7858. * @function
  7859. */
  7860. uid: (function() {
  7861. var id = 0;
  7862. return function() {
  7863. return id++;
  7864. };
  7865. }()),
  7866. /**
  7867. * Returns true if `value` is neither null nor undefined, else returns false.
  7868. * @param {*} value - The value to test.
  7869. * @returns {boolean}
  7870. * @since 2.7.0
  7871. */
  7872. isNullOrUndef: function(value) {
  7873. return value === null || typeof value === 'undefined';
  7874. },
  7875. /**
  7876. * Returns true if `value` is an array (including typed arrays), else returns false.
  7877. * @param {*} value - The value to test.
  7878. * @returns {boolean}
  7879. * @function
  7880. */
  7881. isArray: function(value) {
  7882. if (Array.isArray && Array.isArray(value)) {
  7883. return true;
  7884. }
  7885. var type = Object.prototype.toString.call(value);
  7886. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  7887. return true;
  7888. }
  7889. return false;
  7890. },
  7891. /**
  7892. * Returns true if `value` is an object (excluding null), else returns false.
  7893. * @param {*} value - The value to test.
  7894. * @returns {boolean}
  7895. * @since 2.7.0
  7896. */
  7897. isObject: function(value) {
  7898. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  7899. },
  7900. /**
  7901. * Returns true if `value` is a finite number, else returns false
  7902. * @param {*} value - The value to test.
  7903. * @returns {boolean}
  7904. */
  7905. isFinite: function(value) {
  7906. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  7907. },
  7908. /**
  7909. * Returns `value` if defined, else returns `defaultValue`.
  7910. * @param {*} value - The value to return if defined.
  7911. * @param {*} defaultValue - The value to return if `value` is undefined.
  7912. * @returns {*}
  7913. */
  7914. valueOrDefault: function(value, defaultValue) {
  7915. return typeof value === 'undefined' ? defaultValue : value;
  7916. },
  7917. /**
  7918. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  7919. * @param {Array} value - The array to lookup for value at `index`.
  7920. * @param {number} index - The index in `value` to lookup for value.
  7921. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  7922. * @returns {*}
  7923. */
  7924. valueAtIndexOrDefault: function(value, index, defaultValue) {
  7925. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  7926. },
  7927. /**
  7928. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  7929. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  7930. * @param {function} fn - The function to call.
  7931. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  7932. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  7933. * @returns {*}
  7934. */
  7935. callback: function(fn, args, thisArg) {
  7936. if (fn && typeof fn.call === 'function') {
  7937. return fn.apply(thisArg, args);
  7938. }
  7939. },
  7940. /**
  7941. * Note(SB) for performance sake, this method should only be used when loopable type
  7942. * is unknown or in none intensive code (not called often and small loopable). Else
  7943. * it's preferable to use a regular for() loop and save extra function calls.
  7944. * @param {object|Array} loopable - The object or array to be iterated.
  7945. * @param {function} fn - The function to call for each item.
  7946. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  7947. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  7948. */
  7949. each: function(loopable, fn, thisArg, reverse) {
  7950. var i, len, keys;
  7951. if (helpers.isArray(loopable)) {
  7952. len = loopable.length;
  7953. if (reverse) {
  7954. for (i = len - 1; i >= 0; i--) {
  7955. fn.call(thisArg, loopable[i], i);
  7956. }
  7957. } else {
  7958. for (i = 0; i < len; i++) {
  7959. fn.call(thisArg, loopable[i], i);
  7960. }
  7961. }
  7962. } else if (helpers.isObject(loopable)) {
  7963. keys = Object.keys(loopable);
  7964. len = keys.length;
  7965. for (i = 0; i < len; i++) {
  7966. fn.call(thisArg, loopable[keys[i]], keys[i]);
  7967. }
  7968. }
  7969. },
  7970. /**
  7971. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  7972. * @see https://stackoverflow.com/a/14853974
  7973. * @param {Array} a0 - The array to compare
  7974. * @param {Array} a1 - The array to compare
  7975. * @returns {boolean}
  7976. */
  7977. arrayEquals: function(a0, a1) {
  7978. var i, ilen, v0, v1;
  7979. if (!a0 || !a1 || a0.length !== a1.length) {
  7980. return false;
  7981. }
  7982. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  7983. v0 = a0[i];
  7984. v1 = a1[i];
  7985. if (v0 instanceof Array && v1 instanceof Array) {
  7986. if (!helpers.arrayEquals(v0, v1)) {
  7987. return false;
  7988. }
  7989. } else if (v0 !== v1) {
  7990. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  7991. return false;
  7992. }
  7993. }
  7994. return true;
  7995. },
  7996. /**
  7997. * Returns a deep copy of `source` without keeping references on objects and arrays.
  7998. * @param {*} source - The value to clone.
  7999. * @returns {*}
  8000. */
  8001. clone: function(source) {
  8002. if (helpers.isArray(source)) {
  8003. return source.map(helpers.clone);
  8004. }
  8005. if (helpers.isObject(source)) {
  8006. var target = Object.create(source);
  8007. var keys = Object.keys(source);
  8008. var klen = keys.length;
  8009. var k = 0;
  8010. for (; k < klen; ++k) {
  8011. target[keys[k]] = helpers.clone(source[keys[k]]);
  8012. }
  8013. return target;
  8014. }
  8015. return source;
  8016. },
  8017. /**
  8018. * The default merger when Chart.helpers.merge is called without merger option.
  8019. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  8020. * @private
  8021. */
  8022. _merger: function(key, target, source, options) {
  8023. if (!isValidKey(key)) {
  8024. // We want to ensure we do not copy prototypes over
  8025. // as this can pollute global namespaces
  8026. return;
  8027. }
  8028. var tval = target[key];
  8029. var sval = source[key];
  8030. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  8031. helpers.merge(tval, sval, options);
  8032. } else {
  8033. target[key] = helpers.clone(sval);
  8034. }
  8035. },
  8036. /**
  8037. * Merges source[key] in target[key] only if target[key] is undefined.
  8038. * @private
  8039. */
  8040. _mergerIf: function(key, target, source) {
  8041. if (!isValidKey(key)) {
  8042. // We want to ensure we do not copy prototypes over
  8043. // as this can pollute global namespaces
  8044. return;
  8045. }
  8046. var tval = target[key];
  8047. var sval = source[key];
  8048. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  8049. helpers.mergeIf(tval, sval);
  8050. } else if (!target.hasOwnProperty(key)) {
  8051. target[key] = helpers.clone(sval);
  8052. }
  8053. },
  8054. /**
  8055. * Recursively deep copies `source` properties into `target` with the given `options`.
  8056. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  8057. * @param {object} target - The target object in which all sources are merged into.
  8058. * @param {object|object[]} source - Object(s) to merge into `target`.
  8059. * @param {object} [options] - Merging options:
  8060. * @param {function} [options.merger] - The merge method (key, target, source, options)
  8061. * @returns {object} The `target` object.
  8062. */
  8063. merge: function(target, source, options) {
  8064. var sources = helpers.isArray(source) ? source : [source];
  8065. var ilen = sources.length;
  8066. var merge, i, keys, klen, k;
  8067. if (!helpers.isObject(target)) {
  8068. return target;
  8069. }
  8070. options = options || {};
  8071. merge = options.merger || helpers._merger;
  8072. for (i = 0; i < ilen; ++i) {
  8073. source = sources[i];
  8074. if (!helpers.isObject(source)) {
  8075. continue;
  8076. }
  8077. keys = Object.keys(source);
  8078. for (k = 0, klen = keys.length; k < klen; ++k) {
  8079. merge(keys[k], target, source, options);
  8080. }
  8081. }
  8082. return target;
  8083. },
  8084. /**
  8085. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  8086. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  8087. * @param {object} target - The target object in which all sources are merged into.
  8088. * @param {object|object[]} source - Object(s) to merge into `target`.
  8089. * @returns {object} The `target` object.
  8090. */
  8091. mergeIf: function(target, source) {
  8092. return helpers.merge(target, source, {merger: helpers._mergerIf});
  8093. },
  8094. /**
  8095. * Applies the contents of two or more objects together into the first object.
  8096. * @param {object} target - The target object in which all objects are merged into.
  8097. * @param {object} arg1 - Object containing additional properties to merge in target.
  8098. * @param {object} argN - Additional objects containing properties to merge in target.
  8099. * @returns {object} The `target` object.
  8100. */
  8101. extend: Object.assign || function(target) {
  8102. return helpers.merge(target, [].slice.call(arguments, 1), {
  8103. merger: function(key, dst, src) {
  8104. dst[key] = src[key];
  8105. }
  8106. });
  8107. },
  8108. /**
  8109. * Basic javascript inheritance based on the model created in Backbone.js
  8110. */
  8111. inherits: function(extensions) {
  8112. var me = this;
  8113. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  8114. return me.apply(this, arguments);
  8115. };
  8116. var Surrogate = function() {
  8117. this.constructor = ChartElement;
  8118. };
  8119. Surrogate.prototype = me.prototype;
  8120. ChartElement.prototype = new Surrogate();
  8121. ChartElement.extend = helpers.inherits;
  8122. if (extensions) {
  8123. helpers.extend(ChartElement.prototype, extensions);
  8124. }
  8125. ChartElement.__super__ = me.prototype;
  8126. return ChartElement;
  8127. },
  8128. _deprecated: function(scope, value, previous, current) {
  8129. if (value !== undefined) {
  8130. console.warn(scope + ': "' + previous +
  8131. '" is deprecated. Please use "' + current + '" instead');
  8132. }
  8133. }
  8134. };
  8135. var helpers_core = helpers;
  8136. // DEPRECATIONS
  8137. /**
  8138. * Provided for backward compatibility, use Chart.helpers.callback instead.
  8139. * @function Chart.helpers.callCallback
  8140. * @deprecated since version 2.6.0
  8141. * @todo remove at version 3
  8142. * @private
  8143. */
  8144. helpers.callCallback = helpers.callback;
  8145. /**
  8146. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  8147. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  8148. * @function Chart.helpers.indexOf
  8149. * @deprecated since version 2.7.0
  8150. * @todo remove at version 3
  8151. * @private
  8152. */
  8153. helpers.indexOf = function(array, item, fromIndex) {
  8154. return Array.prototype.indexOf.call(array, item, fromIndex);
  8155. };
  8156. /**
  8157. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  8158. * @function Chart.helpers.getValueOrDefault
  8159. * @deprecated since version 2.7.0
  8160. * @todo remove at version 3
  8161. * @private
  8162. */
  8163. helpers.getValueOrDefault = helpers.valueOrDefault;
  8164. /**
  8165. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  8166. * @function Chart.helpers.getValueAtIndexOrDefault
  8167. * @deprecated since version 2.7.0
  8168. * @todo remove at version 3
  8169. * @private
  8170. */
  8171. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  8172. /**
  8173. * Easing functions adapted from Robert Penner's easing equations.
  8174. * @namespace Chart.helpers.easingEffects
  8175. * @see http://www.robertpenner.com/easing/
  8176. */
  8177. var effects = {
  8178. linear: function(t) {
  8179. return t;
  8180. },
  8181. easeInQuad: function(t) {
  8182. return t * t;
  8183. },
  8184. easeOutQuad: function(t) {
  8185. return -t * (t - 2);
  8186. },
  8187. easeInOutQuad: function(t) {
  8188. if ((t /= 0.5) < 1) {
  8189. return 0.5 * t * t;
  8190. }
  8191. return -0.5 * ((--t) * (t - 2) - 1);
  8192. },
  8193. easeInCubic: function(t) {
  8194. return t * t * t;
  8195. },
  8196. easeOutCubic: function(t) {
  8197. return (t = t - 1) * t * t + 1;
  8198. },
  8199. easeInOutCubic: function(t) {
  8200. if ((t /= 0.5) < 1) {
  8201. return 0.5 * t * t * t;
  8202. }
  8203. return 0.5 * ((t -= 2) * t * t + 2);
  8204. },
  8205. easeInQuart: function(t) {
  8206. return t * t * t * t;
  8207. },
  8208. easeOutQuart: function(t) {
  8209. return -((t = t - 1) * t * t * t - 1);
  8210. },
  8211. easeInOutQuart: function(t) {
  8212. if ((t /= 0.5) < 1) {
  8213. return 0.5 * t * t * t * t;
  8214. }
  8215. return -0.5 * ((t -= 2) * t * t * t - 2);
  8216. },
  8217. easeInQuint: function(t) {
  8218. return t * t * t * t * t;
  8219. },
  8220. easeOutQuint: function(t) {
  8221. return (t = t - 1) * t * t * t * t + 1;
  8222. },
  8223. easeInOutQuint: function(t) {
  8224. if ((t /= 0.5) < 1) {
  8225. return 0.5 * t * t * t * t * t;
  8226. }
  8227. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  8228. },
  8229. easeInSine: function(t) {
  8230. return -Math.cos(t * (Math.PI / 2)) + 1;
  8231. },
  8232. easeOutSine: function(t) {
  8233. return Math.sin(t * (Math.PI / 2));
  8234. },
  8235. easeInOutSine: function(t) {
  8236. return -0.5 * (Math.cos(Math.PI * t) - 1);
  8237. },
  8238. easeInExpo: function(t) {
  8239. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  8240. },
  8241. easeOutExpo: function(t) {
  8242. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  8243. },
  8244. easeInOutExpo: function(t) {
  8245. if (t === 0) {
  8246. return 0;
  8247. }
  8248. if (t === 1) {
  8249. return 1;
  8250. }
  8251. if ((t /= 0.5) < 1) {
  8252. return 0.5 * Math.pow(2, 10 * (t - 1));
  8253. }
  8254. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  8255. },
  8256. easeInCirc: function(t) {
  8257. if (t >= 1) {
  8258. return t;
  8259. }
  8260. return -(Math.sqrt(1 - t * t) - 1);
  8261. },
  8262. easeOutCirc: function(t) {
  8263. return Math.sqrt(1 - (t = t - 1) * t);
  8264. },
  8265. easeInOutCirc: function(t) {
  8266. if ((t /= 0.5) < 1) {
  8267. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  8268. }
  8269. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  8270. },
  8271. easeInElastic: function(t) {
  8272. var s = 1.70158;
  8273. var p = 0;
  8274. var a = 1;
  8275. if (t === 0) {
  8276. return 0;
  8277. }
  8278. if (t === 1) {
  8279. return 1;
  8280. }
  8281. if (!p) {
  8282. p = 0.3;
  8283. }
  8284. {
  8285. s = p / (2 * Math.PI) * Math.asin(1 / a);
  8286. }
  8287. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  8288. },
  8289. easeOutElastic: function(t) {
  8290. var s = 1.70158;
  8291. var p = 0;
  8292. var a = 1;
  8293. if (t === 0) {
  8294. return 0;
  8295. }
  8296. if (t === 1) {
  8297. return 1;
  8298. }
  8299. if (!p) {
  8300. p = 0.3;
  8301. }
  8302. {
  8303. s = p / (2 * Math.PI) * Math.asin(1 / a);
  8304. }
  8305. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  8306. },
  8307. easeInOutElastic: function(t) {
  8308. var s = 1.70158;
  8309. var p = 0;
  8310. var a = 1;
  8311. if (t === 0) {
  8312. return 0;
  8313. }
  8314. if ((t /= 0.5) === 2) {
  8315. return 1;
  8316. }
  8317. if (!p) {
  8318. p = 0.45;
  8319. }
  8320. {
  8321. s = p / (2 * Math.PI) * Math.asin(1 / a);
  8322. }
  8323. if (t < 1) {
  8324. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  8325. }
  8326. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  8327. },
  8328. easeInBack: function(t) {
  8329. var s = 1.70158;
  8330. return t * t * ((s + 1) * t - s);
  8331. },
  8332. easeOutBack: function(t) {
  8333. var s = 1.70158;
  8334. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  8335. },
  8336. easeInOutBack: function(t) {
  8337. var s = 1.70158;
  8338. if ((t /= 0.5) < 1) {
  8339. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  8340. }
  8341. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  8342. },
  8343. easeInBounce: function(t) {
  8344. return 1 - effects.easeOutBounce(1 - t);
  8345. },
  8346. easeOutBounce: function(t) {
  8347. if (t < (1 / 2.75)) {
  8348. return 7.5625 * t * t;
  8349. }
  8350. if (t < (2 / 2.75)) {
  8351. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  8352. }
  8353. if (t < (2.5 / 2.75)) {
  8354. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  8355. }
  8356. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  8357. },
  8358. easeInOutBounce: function(t) {
  8359. if (t < 0.5) {
  8360. return effects.easeInBounce(t * 2) * 0.5;
  8361. }
  8362. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  8363. }
  8364. };
  8365. var helpers_easing = {
  8366. effects: effects
  8367. };
  8368. // DEPRECATIONS
  8369. /**
  8370. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  8371. * @function Chart.helpers.easingEffects
  8372. * @deprecated since version 2.7.0
  8373. * @todo remove at version 3
  8374. * @private
  8375. */
  8376. helpers_core.easingEffects = effects;
  8377. var PI = Math.PI;
  8378. var RAD_PER_DEG = PI / 180;
  8379. var DOUBLE_PI = PI * 2;
  8380. var HALF_PI = PI / 2;
  8381. var QUARTER_PI = PI / 4;
  8382. var TWO_THIRDS_PI = PI * 2 / 3;
  8383. /**
  8384. * @namespace Chart.helpers.canvas
  8385. */
  8386. var exports$1 = {
  8387. /**
  8388. * Clears the entire canvas associated to the given `chart`.
  8389. * @param {Chart} chart - The chart for which to clear the canvas.
  8390. */
  8391. clear: function(chart) {
  8392. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  8393. },
  8394. /**
  8395. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  8396. * given size (width, height) and the same `radius` for all corners.
  8397. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  8398. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  8399. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  8400. * @param {number} width - The rectangle's width.
  8401. * @param {number} height - The rectangle's height.
  8402. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  8403. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  8404. */
  8405. roundedRect: function(ctx, x, y, width, height, radius) {
  8406. if (radius) {
  8407. var r = Math.min(radius, height / 2, width / 2);
  8408. var left = x + r;
  8409. var top = y + r;
  8410. var right = x + width - r;
  8411. var bottom = y + height - r;
  8412. ctx.moveTo(x, top);
  8413. if (left < right && top < bottom) {
  8414. ctx.arc(left, top, r, -PI, -HALF_PI);
  8415. ctx.arc(right, top, r, -HALF_PI, 0);
  8416. ctx.arc(right, bottom, r, 0, HALF_PI);
  8417. ctx.arc(left, bottom, r, HALF_PI, PI);
  8418. } else if (left < right) {
  8419. ctx.moveTo(left, y);
  8420. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  8421. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  8422. } else if (top < bottom) {
  8423. ctx.arc(left, top, r, -PI, 0);
  8424. ctx.arc(left, bottom, r, 0, PI);
  8425. } else {
  8426. ctx.arc(left, top, r, -PI, PI);
  8427. }
  8428. ctx.closePath();
  8429. ctx.moveTo(x, y);
  8430. } else {
  8431. ctx.rect(x, y, width, height);
  8432. }
  8433. },
  8434. drawPoint: function(ctx, style, radius, x, y, rotation) {
  8435. var type, xOffset, yOffset, size, cornerRadius;
  8436. var rad = (rotation || 0) * RAD_PER_DEG;
  8437. if (style && typeof style === 'object') {
  8438. type = style.toString();
  8439. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  8440. ctx.save();
  8441. ctx.translate(x, y);
  8442. ctx.rotate(rad);
  8443. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  8444. ctx.restore();
  8445. return;
  8446. }
  8447. }
  8448. if (isNaN(radius) || radius <= 0) {
  8449. return;
  8450. }
  8451. ctx.beginPath();
  8452. switch (style) {
  8453. // Default includes circle
  8454. default:
  8455. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  8456. ctx.closePath();
  8457. break;
  8458. case 'triangle':
  8459. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  8460. rad += TWO_THIRDS_PI;
  8461. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  8462. rad += TWO_THIRDS_PI;
  8463. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  8464. ctx.closePath();
  8465. break;
  8466. case 'rectRounded':
  8467. // NOTE: the rounded rect implementation changed to use `arc` instead of
  8468. // `quadraticCurveTo` since it generates better results when rect is
  8469. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  8470. // closer proportion to the previous impl and it is inscribed in the
  8471. // circle with `radius`. For more details, see the following PRs:
  8472. // https://github.com/chartjs/Chart.js/issues/5597
  8473. // https://github.com/chartjs/Chart.js/issues/5858
  8474. cornerRadius = radius * 0.516;
  8475. size = radius - cornerRadius;
  8476. xOffset = Math.cos(rad + QUARTER_PI) * size;
  8477. yOffset = Math.sin(rad + QUARTER_PI) * size;
  8478. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  8479. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  8480. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  8481. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  8482. ctx.closePath();
  8483. break;
  8484. case 'rect':
  8485. if (!rotation) {
  8486. size = Math.SQRT1_2 * radius;
  8487. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  8488. break;
  8489. }
  8490. rad += QUARTER_PI;
  8491. /* falls through */
  8492. case 'rectRot':
  8493. xOffset = Math.cos(rad) * radius;
  8494. yOffset = Math.sin(rad) * radius;
  8495. ctx.moveTo(x - xOffset, y - yOffset);
  8496. ctx.lineTo(x + yOffset, y - xOffset);
  8497. ctx.lineTo(x + xOffset, y + yOffset);
  8498. ctx.lineTo(x - yOffset, y + xOffset);
  8499. ctx.closePath();
  8500. break;
  8501. case 'crossRot':
  8502. rad += QUARTER_PI;
  8503. /* falls through */
  8504. case 'cross':
  8505. xOffset = Math.cos(rad) * radius;
  8506. yOffset = Math.sin(rad) * radius;
  8507. ctx.moveTo(x - xOffset, y - yOffset);
  8508. ctx.lineTo(x + xOffset, y + yOffset);
  8509. ctx.moveTo(x + yOffset, y - xOffset);
  8510. ctx.lineTo(x - yOffset, y + xOffset);
  8511. break;
  8512. case 'star':
  8513. xOffset = Math.cos(rad) * radius;
  8514. yOffset = Math.sin(rad) * radius;
  8515. ctx.moveTo(x - xOffset, y - yOffset);
  8516. ctx.lineTo(x + xOffset, y + yOffset);
  8517. ctx.moveTo(x + yOffset, y - xOffset);
  8518. ctx.lineTo(x - yOffset, y + xOffset);
  8519. rad += QUARTER_PI;
  8520. xOffset = Math.cos(rad) * radius;
  8521. yOffset = Math.sin(rad) * radius;
  8522. ctx.moveTo(x - xOffset, y - yOffset);
  8523. ctx.lineTo(x + xOffset, y + yOffset);
  8524. ctx.moveTo(x + yOffset, y - xOffset);
  8525. ctx.lineTo(x - yOffset, y + xOffset);
  8526. break;
  8527. case 'line':
  8528. xOffset = Math.cos(rad) * radius;
  8529. yOffset = Math.sin(rad) * radius;
  8530. ctx.moveTo(x - xOffset, y - yOffset);
  8531. ctx.lineTo(x + xOffset, y + yOffset);
  8532. break;
  8533. case 'dash':
  8534. ctx.moveTo(x, y);
  8535. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  8536. break;
  8537. }
  8538. ctx.fill();
  8539. ctx.stroke();
  8540. },
  8541. /**
  8542. * Returns true if the point is inside the rectangle
  8543. * @param {object} point - The point to test
  8544. * @param {object} area - The rectangle
  8545. * @returns {boolean}
  8546. * @private
  8547. */
  8548. _isPointInArea: function(point, area) {
  8549. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  8550. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  8551. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  8552. },
  8553. clipArea: function(ctx, area) {
  8554. ctx.save();
  8555. ctx.beginPath();
  8556. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  8557. ctx.clip();
  8558. },
  8559. unclipArea: function(ctx) {
  8560. ctx.restore();
  8561. },
  8562. lineTo: function(ctx, previous, target, flip) {
  8563. var stepped = target.steppedLine;
  8564. if (stepped) {
  8565. if (stepped === 'middle') {
  8566. var midpoint = (previous.x + target.x) / 2.0;
  8567. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  8568. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  8569. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  8570. ctx.lineTo(previous.x, target.y);
  8571. } else {
  8572. ctx.lineTo(target.x, previous.y);
  8573. }
  8574. ctx.lineTo(target.x, target.y);
  8575. return;
  8576. }
  8577. if (!target.tension) {
  8578. ctx.lineTo(target.x, target.y);
  8579. return;
  8580. }
  8581. ctx.bezierCurveTo(
  8582. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  8583. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  8584. flip ? target.controlPointNextX : target.controlPointPreviousX,
  8585. flip ? target.controlPointNextY : target.controlPointPreviousY,
  8586. target.x,
  8587. target.y);
  8588. }
  8589. };
  8590. var helpers_canvas = exports$1;
  8591. // DEPRECATIONS
  8592. /**
  8593. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  8594. * @namespace Chart.helpers.clear
  8595. * @deprecated since version 2.7.0
  8596. * @todo remove at version 3
  8597. * @private
  8598. */
  8599. helpers_core.clear = exports$1.clear;
  8600. /**
  8601. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  8602. * @namespace Chart.helpers.drawRoundedRectangle
  8603. * @deprecated since version 2.7.0
  8604. * @todo remove at version 3
  8605. * @private
  8606. */
  8607. helpers_core.drawRoundedRectangle = function(ctx) {
  8608. ctx.beginPath();
  8609. exports$1.roundedRect.apply(exports$1, arguments);
  8610. };
  8611. var defaults = {
  8612. /**
  8613. * @private
  8614. */
  8615. _set: function(scope, values) {
  8616. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  8617. }
  8618. };
  8619. // TODO(v3): remove 'global' from namespace. all default are global and
  8620. // there's inconsistency around which options are under 'global'
  8621. defaults._set('global', {
  8622. defaultColor: 'rgba(0,0,0,0.1)',
  8623. defaultFontColor: '#666',
  8624. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  8625. defaultFontSize: 12,
  8626. defaultFontStyle: 'normal',
  8627. defaultLineHeight: 1.2,
  8628. showLines: true
  8629. });
  8630. var core_defaults = defaults;
  8631. var valueOrDefault = helpers_core.valueOrDefault;
  8632. /**
  8633. * Converts the given font object into a CSS font string.
  8634. * @param {object} font - A font object.
  8635. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  8636. * @private
  8637. */
  8638. function toFontString(font) {
  8639. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  8640. return null;
  8641. }
  8642. return (font.style ? font.style + ' ' : '')
  8643. + (font.weight ? font.weight + ' ' : '')
  8644. + font.size + 'px '
  8645. + font.family;
  8646. }
  8647. /**
  8648. * @alias Chart.helpers.options
  8649. * @namespace
  8650. */
  8651. var helpers_options = {
  8652. /**
  8653. * Converts the given line height `value` in pixels for a specific font `size`.
  8654. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  8655. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  8656. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  8657. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  8658. * @since 2.7.0
  8659. */
  8660. toLineHeight: function(value, size) {
  8661. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  8662. if (!matches || matches[1] === 'normal') {
  8663. return size * 1.2;
  8664. }
  8665. value = +matches[2];
  8666. switch (matches[3]) {
  8667. case 'px':
  8668. return value;
  8669. case '%':
  8670. value /= 100;
  8671. break;
  8672. }
  8673. return size * value;
  8674. },
  8675. /**
  8676. * Converts the given value into a padding object with pre-computed width/height.
  8677. * @param {number|object} value - If a number, set the value to all TRBL component,
  8678. * else, if and object, use defined properties and sets undefined ones to 0.
  8679. * @returns {object} The padding values (top, right, bottom, left, width, height)
  8680. * @since 2.7.0
  8681. */
  8682. toPadding: function(value) {
  8683. var t, r, b, l;
  8684. if (helpers_core.isObject(value)) {
  8685. t = +value.top || 0;
  8686. r = +value.right || 0;
  8687. b = +value.bottom || 0;
  8688. l = +value.left || 0;
  8689. } else {
  8690. t = r = b = l = +value || 0;
  8691. }
  8692. return {
  8693. top: t,
  8694. right: r,
  8695. bottom: b,
  8696. left: l,
  8697. height: t + b,
  8698. width: l + r
  8699. };
  8700. },
  8701. /**
  8702. * Parses font options and returns the font object.
  8703. * @param {object} options - A object that contains font options to be parsed.
  8704. * @return {object} The font object.
  8705. * @todo Support font.* options and renamed to toFont().
  8706. * @private
  8707. */
  8708. _parseFont: function(options) {
  8709. var globalDefaults = core_defaults.global;
  8710. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  8711. var font = {
  8712. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  8713. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  8714. size: size,
  8715. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  8716. weight: null,
  8717. string: ''
  8718. };
  8719. font.string = toFontString(font);
  8720. return font;
  8721. },
  8722. /**
  8723. * Evaluates the given `inputs` sequentially and returns the first defined value.
  8724. * @param {Array} inputs - An array of values, falling back to the last value.
  8725. * @param {object} [context] - If defined and the current value is a function, the value
  8726. * is called with `context` as first argument and the result becomes the new input.
  8727. * @param {number} [index] - If defined and the current value is an array, the value
  8728. * at `index` become the new input.
  8729. * @param {object} [info] - object to return information about resolution in
  8730. * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.
  8731. * @since 2.7.0
  8732. */
  8733. resolve: function(inputs, context, index, info) {
  8734. var cacheable = true;
  8735. var i, ilen, value;
  8736. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  8737. value = inputs[i];
  8738. if (value === undefined) {
  8739. continue;
  8740. }
  8741. if (context !== undefined && typeof value === 'function') {
  8742. value = value(context);
  8743. cacheable = false;
  8744. }
  8745. if (index !== undefined && helpers_core.isArray(value)) {
  8746. value = value[index];
  8747. cacheable = false;
  8748. }
  8749. if (value !== undefined) {
  8750. if (info && !cacheable) {
  8751. info.cacheable = false;
  8752. }
  8753. return value;
  8754. }
  8755. }
  8756. }
  8757. };
  8758. /**
  8759. * @alias Chart.helpers.math
  8760. * @namespace
  8761. */
  8762. var exports$2 = {
  8763. /**
  8764. * Returns an array of factors sorted from 1 to sqrt(value)
  8765. * @private
  8766. */
  8767. _factorize: function(value) {
  8768. var result = [];
  8769. var sqrt = Math.sqrt(value);
  8770. var i;
  8771. for (i = 1; i < sqrt; i++) {
  8772. if (value % i === 0) {
  8773. result.push(i);
  8774. result.push(value / i);
  8775. }
  8776. }
  8777. if (sqrt === (sqrt | 0)) { // if value is a square number
  8778. result.push(sqrt);
  8779. }
  8780. result.sort(function(a, b) {
  8781. return a - b;
  8782. }).pop();
  8783. return result;
  8784. },
  8785. log10: Math.log10 || function(x) {
  8786. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  8787. // Check for whole powers of 10,
  8788. // which due to floating point rounding error should be corrected.
  8789. var powerOf10 = Math.round(exponent);
  8790. var isPowerOf10 = x === Math.pow(10, powerOf10);
  8791. return isPowerOf10 ? powerOf10 : exponent;
  8792. }
  8793. };
  8794. var helpers_math = exports$2;
  8795. // DEPRECATIONS
  8796. /**
  8797. * Provided for backward compatibility, use Chart.helpers.math.log10 instead.
  8798. * @namespace Chart.helpers.log10
  8799. * @deprecated since version 2.9.0
  8800. * @todo remove at version 3
  8801. * @private
  8802. */
  8803. helpers_core.log10 = exports$2.log10;
  8804. var getRtlAdapter = function(rectX, width) {
  8805. return {
  8806. x: function(x) {
  8807. return rectX + rectX + width - x;
  8808. },
  8809. setWidth: function(w) {
  8810. width = w;
  8811. },
  8812. textAlign: function(align) {
  8813. if (align === 'center') {
  8814. return align;
  8815. }
  8816. return align === 'right' ? 'left' : 'right';
  8817. },
  8818. xPlus: function(x, value) {
  8819. return x - value;
  8820. },
  8821. leftForLtr: function(x, itemWidth) {
  8822. return x - itemWidth;
  8823. },
  8824. };
  8825. };
  8826. var getLtrAdapter = function() {
  8827. return {
  8828. x: function(x) {
  8829. return x;
  8830. },
  8831. setWidth: function(w) { // eslint-disable-line no-unused-vars
  8832. },
  8833. textAlign: function(align) {
  8834. return align;
  8835. },
  8836. xPlus: function(x, value) {
  8837. return x + value;
  8838. },
  8839. leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars
  8840. return x;
  8841. },
  8842. };
  8843. };
  8844. var getAdapter = function(rtl, rectX, width) {
  8845. return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();
  8846. };
  8847. var overrideTextDirection = function(ctx, direction) {
  8848. var style, original;
  8849. if (direction === 'ltr' || direction === 'rtl') {
  8850. style = ctx.canvas.style;
  8851. original = [
  8852. style.getPropertyValue('direction'),
  8853. style.getPropertyPriority('direction'),
  8854. ];
  8855. style.setProperty('direction', direction, 'important');
  8856. ctx.prevTextDirection = original;
  8857. }
  8858. };
  8859. var restoreTextDirection = function(ctx) {
  8860. var original = ctx.prevTextDirection;
  8861. if (original !== undefined) {
  8862. delete ctx.prevTextDirection;
  8863. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  8864. }
  8865. };
  8866. var helpers_rtl = {
  8867. getRtlAdapter: getAdapter,
  8868. overrideTextDirection: overrideTextDirection,
  8869. restoreTextDirection: restoreTextDirection,
  8870. };
  8871. var helpers$1 = helpers_core;
  8872. var easing = helpers_easing;
  8873. var canvas = helpers_canvas;
  8874. var options = helpers_options;
  8875. var math = helpers_math;
  8876. var rtl = helpers_rtl;
  8877. helpers$1.easing = easing;
  8878. helpers$1.canvas = canvas;
  8879. helpers$1.options = options;
  8880. helpers$1.math = math;
  8881. helpers$1.rtl = rtl;
  8882. function interpolate(start, view, model, ease) {
  8883. var keys = Object.keys(model);
  8884. var i, ilen, key, actual, origin, target, type, c0, c1;
  8885. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  8886. key = keys[i];
  8887. target = model[key];
  8888. // if a value is added to the model after pivot() has been called, the view
  8889. // doesn't contain it, so let's initialize the view to the target value.
  8890. if (!view.hasOwnProperty(key)) {
  8891. view[key] = target;
  8892. }
  8893. actual = view[key];
  8894. if (actual === target || key[0] === '_') {
  8895. continue;
  8896. }
  8897. if (!start.hasOwnProperty(key)) {
  8898. start[key] = actual;
  8899. }
  8900. origin = start[key];
  8901. type = typeof target;
  8902. if (type === typeof origin) {
  8903. if (type === 'string') {
  8904. c0 = chartjsColor(origin);
  8905. if (c0.valid) {
  8906. c1 = chartjsColor(target);
  8907. if (c1.valid) {
  8908. view[key] = c1.mix(c0, ease).rgbString();
  8909. continue;
  8910. }
  8911. }
  8912. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  8913. view[key] = origin + (target - origin) * ease;
  8914. continue;
  8915. }
  8916. }
  8917. view[key] = target;
  8918. }
  8919. }
  8920. var Element = function(configuration) {
  8921. helpers$1.extend(this, configuration);
  8922. this.initialize.apply(this, arguments);
  8923. };
  8924. helpers$1.extend(Element.prototype, {
  8925. _type: undefined,
  8926. initialize: function() {
  8927. this.hidden = false;
  8928. },
  8929. pivot: function() {
  8930. var me = this;
  8931. if (!me._view) {
  8932. me._view = helpers$1.extend({}, me._model);
  8933. }
  8934. me._start = {};
  8935. return me;
  8936. },
  8937. transition: function(ease) {
  8938. var me = this;
  8939. var model = me._model;
  8940. var start = me._start;
  8941. var view = me._view;
  8942. // No animation -> No Transition
  8943. if (!model || ease === 1) {
  8944. me._view = helpers$1.extend({}, model);
  8945. me._start = null;
  8946. return me;
  8947. }
  8948. if (!view) {
  8949. view = me._view = {};
  8950. }
  8951. if (!start) {
  8952. start = me._start = {};
  8953. }
  8954. interpolate(start, view, model, ease);
  8955. return me;
  8956. },
  8957. tooltipPosition: function() {
  8958. return {
  8959. x: this._model.x,
  8960. y: this._model.y
  8961. };
  8962. },
  8963. hasValue: function() {
  8964. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  8965. }
  8966. });
  8967. Element.extend = helpers$1.inherits;
  8968. var core_element = Element;
  8969. var exports$3 = core_element.extend({
  8970. chart: null, // the animation associated chart instance
  8971. currentStep: 0, // the current animation step
  8972. numSteps: 60, // default number of steps
  8973. easing: '', // the easing to use for this animation
  8974. render: null, // render function used by the animation service
  8975. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  8976. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  8977. });
  8978. var core_animation = exports$3;
  8979. // DEPRECATIONS
  8980. /**
  8981. * Provided for backward compatibility, use Chart.Animation instead
  8982. * @prop Chart.Animation#animationObject
  8983. * @deprecated since version 2.6.0
  8984. * @todo remove at version 3
  8985. */
  8986. Object.defineProperty(exports$3.prototype, 'animationObject', {
  8987. get: function() {
  8988. return this;
  8989. }
  8990. });
  8991. /**
  8992. * Provided for backward compatibility, use Chart.Animation#chart instead
  8993. * @prop Chart.Animation#chartInstance
  8994. * @deprecated since version 2.6.0
  8995. * @todo remove at version 3
  8996. */
  8997. Object.defineProperty(exports$3.prototype, 'chartInstance', {
  8998. get: function() {
  8999. return this.chart;
  9000. },
  9001. set: function(value) {
  9002. this.chart = value;
  9003. }
  9004. });
  9005. core_defaults._set('global', {
  9006. animation: {
  9007. duration: 1000,
  9008. easing: 'easeOutQuart',
  9009. onProgress: helpers$1.noop,
  9010. onComplete: helpers$1.noop
  9011. }
  9012. });
  9013. var core_animations = {
  9014. animations: [],
  9015. request: null,
  9016. /**
  9017. * @param {Chart} chart - The chart to animate.
  9018. * @param {Chart.Animation} animation - The animation that we will animate.
  9019. * @param {number} duration - The animation duration in ms.
  9020. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  9021. */
  9022. addAnimation: function(chart, animation, duration, lazy) {
  9023. var animations = this.animations;
  9024. var i, ilen;
  9025. animation.chart = chart;
  9026. animation.startTime = Date.now();
  9027. animation.duration = duration;
  9028. if (!lazy) {
  9029. chart.animating = true;
  9030. }
  9031. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  9032. if (animations[i].chart === chart) {
  9033. animations[i] = animation;
  9034. return;
  9035. }
  9036. }
  9037. animations.push(animation);
  9038. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  9039. if (animations.length === 1) {
  9040. this.requestAnimationFrame();
  9041. }
  9042. },
  9043. cancelAnimation: function(chart) {
  9044. var index = helpers$1.findIndex(this.animations, function(animation) {
  9045. return animation.chart === chart;
  9046. });
  9047. if (index !== -1) {
  9048. this.animations.splice(index, 1);
  9049. chart.animating = false;
  9050. }
  9051. },
  9052. requestAnimationFrame: function() {
  9053. var me = this;
  9054. if (me.request === null) {
  9055. // Skip animation frame requests until the active one is executed.
  9056. // This can happen when processing mouse events, e.g. 'mousemove'
  9057. // and 'mouseout' events will trigger multiple renders.
  9058. me.request = helpers$1.requestAnimFrame.call(window, function() {
  9059. me.request = null;
  9060. me.startDigest();
  9061. });
  9062. }
  9063. },
  9064. /**
  9065. * @private
  9066. */
  9067. startDigest: function() {
  9068. var me = this;
  9069. me.advance();
  9070. // Do we have more stuff to animate?
  9071. if (me.animations.length > 0) {
  9072. me.requestAnimationFrame();
  9073. }
  9074. },
  9075. /**
  9076. * @private
  9077. */
  9078. advance: function() {
  9079. var animations = this.animations;
  9080. var animation, chart, numSteps, nextStep;
  9081. var i = 0;
  9082. // 1 animation per chart, so we are looping charts here
  9083. while (i < animations.length) {
  9084. animation = animations[i];
  9085. chart = animation.chart;
  9086. numSteps = animation.numSteps;
  9087. // Make sure that currentStep starts at 1
  9088. // https://github.com/chartjs/Chart.js/issues/6104
  9089. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  9090. animation.currentStep = Math.min(nextStep, numSteps);
  9091. helpers$1.callback(animation.render, [chart, animation], chart);
  9092. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  9093. if (animation.currentStep >= numSteps) {
  9094. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  9095. chart.animating = false;
  9096. animations.splice(i, 1);
  9097. } else {
  9098. ++i;
  9099. }
  9100. }
  9101. }
  9102. };
  9103. var resolve = helpers$1.options.resolve;
  9104. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  9105. /**
  9106. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  9107. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  9108. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  9109. */
  9110. function listenArrayEvents(array, listener) {
  9111. if (array._chartjs) {
  9112. array._chartjs.listeners.push(listener);
  9113. return;
  9114. }
  9115. Object.defineProperty(array, '_chartjs', {
  9116. configurable: true,
  9117. enumerable: false,
  9118. value: {
  9119. listeners: [listener]
  9120. }
  9121. });
  9122. arrayEvents.forEach(function(key) {
  9123. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  9124. var base = array[key];
  9125. Object.defineProperty(array, key, {
  9126. configurable: true,
  9127. enumerable: false,
  9128. value: function() {
  9129. var args = Array.prototype.slice.call(arguments);
  9130. var res = base.apply(this, args);
  9131. helpers$1.each(array._chartjs.listeners, function(object) {
  9132. if (typeof object[method] === 'function') {
  9133. object[method].apply(object, args);
  9134. }
  9135. });
  9136. return res;
  9137. }
  9138. });
  9139. });
  9140. }
  9141. /**
  9142. * Removes the given array event listener and cleanup extra attached properties (such as
  9143. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  9144. */
  9145. function unlistenArrayEvents(array, listener) {
  9146. var stub = array._chartjs;
  9147. if (!stub) {
  9148. return;
  9149. }
  9150. var listeners = stub.listeners;
  9151. var index = listeners.indexOf(listener);
  9152. if (index !== -1) {
  9153. listeners.splice(index, 1);
  9154. }
  9155. if (listeners.length > 0) {
  9156. return;
  9157. }
  9158. arrayEvents.forEach(function(key) {
  9159. delete array[key];
  9160. });
  9161. delete array._chartjs;
  9162. }
  9163. // Base class for all dataset controllers (line, bar, etc)
  9164. var DatasetController = function(chart, datasetIndex) {
  9165. this.initialize(chart, datasetIndex);
  9166. };
  9167. helpers$1.extend(DatasetController.prototype, {
  9168. /**
  9169. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  9170. * @type {Chart.core.element}
  9171. */
  9172. datasetElementType: null,
  9173. /**
  9174. * Element type used to generate a meta data (e.g. Chart.element.Point).
  9175. * @type {Chart.core.element}
  9176. */
  9177. dataElementType: null,
  9178. /**
  9179. * Dataset element option keys to be resolved in _resolveDatasetElementOptions.
  9180. * A derived controller may override this to resolve controller-specific options.
  9181. * The keys defined here are for backward compatibility for legend styles.
  9182. * @private
  9183. */
  9184. _datasetElementOptions: [
  9185. 'backgroundColor',
  9186. 'borderCapStyle',
  9187. 'borderColor',
  9188. 'borderDash',
  9189. 'borderDashOffset',
  9190. 'borderJoinStyle',
  9191. 'borderWidth'
  9192. ],
  9193. /**
  9194. * Data element option keys to be resolved in _resolveDataElementOptions.
  9195. * A derived controller may override this to resolve controller-specific options.
  9196. * The keys defined here are for backward compatibility for legend styles.
  9197. * @private
  9198. */
  9199. _dataElementOptions: [
  9200. 'backgroundColor',
  9201. 'borderColor',
  9202. 'borderWidth',
  9203. 'pointStyle'
  9204. ],
  9205. initialize: function(chart, datasetIndex) {
  9206. var me = this;
  9207. me.chart = chart;
  9208. me.index = datasetIndex;
  9209. me.linkScales();
  9210. me.addElements();
  9211. me._type = me.getMeta().type;
  9212. },
  9213. updateIndex: function(datasetIndex) {
  9214. this.index = datasetIndex;
  9215. },
  9216. linkScales: function() {
  9217. var me = this;
  9218. var meta = me.getMeta();
  9219. var chart = me.chart;
  9220. var scales = chart.scales;
  9221. var dataset = me.getDataset();
  9222. var scalesOpts = chart.options.scales;
  9223. if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
  9224. meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
  9225. }
  9226. if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
  9227. meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
  9228. }
  9229. },
  9230. getDataset: function() {
  9231. return this.chart.data.datasets[this.index];
  9232. },
  9233. getMeta: function() {
  9234. return this.chart.getDatasetMeta(this.index);
  9235. },
  9236. getScaleForId: function(scaleID) {
  9237. return this.chart.scales[scaleID];
  9238. },
  9239. /**
  9240. * @private
  9241. */
  9242. _getValueScaleId: function() {
  9243. return this.getMeta().yAxisID;
  9244. },
  9245. /**
  9246. * @private
  9247. */
  9248. _getIndexScaleId: function() {
  9249. return this.getMeta().xAxisID;
  9250. },
  9251. /**
  9252. * @private
  9253. */
  9254. _getValueScale: function() {
  9255. return this.getScaleForId(this._getValueScaleId());
  9256. },
  9257. /**
  9258. * @private
  9259. */
  9260. _getIndexScale: function() {
  9261. return this.getScaleForId(this._getIndexScaleId());
  9262. },
  9263. reset: function() {
  9264. this._update(true);
  9265. },
  9266. /**
  9267. * @private
  9268. */
  9269. destroy: function() {
  9270. if (this._data) {
  9271. unlistenArrayEvents(this._data, this);
  9272. }
  9273. },
  9274. createMetaDataset: function() {
  9275. var me = this;
  9276. var type = me.datasetElementType;
  9277. return type && new type({
  9278. _chart: me.chart,
  9279. _datasetIndex: me.index
  9280. });
  9281. },
  9282. createMetaData: function(index) {
  9283. var me = this;
  9284. var type = me.dataElementType;
  9285. return type && new type({
  9286. _chart: me.chart,
  9287. _datasetIndex: me.index,
  9288. _index: index
  9289. });
  9290. },
  9291. addElements: function() {
  9292. var me = this;
  9293. var meta = me.getMeta();
  9294. var data = me.getDataset().data || [];
  9295. var metaData = meta.data;
  9296. var i, ilen;
  9297. for (i = 0, ilen = data.length; i < ilen; ++i) {
  9298. metaData[i] = metaData[i] || me.createMetaData(i);
  9299. }
  9300. meta.dataset = meta.dataset || me.createMetaDataset();
  9301. },
  9302. addElementAndReset: function(index) {
  9303. var element = this.createMetaData(index);
  9304. this.getMeta().data.splice(index, 0, element);
  9305. this.updateElement(element, index, true);
  9306. },
  9307. buildOrUpdateElements: function() {
  9308. var me = this;
  9309. var dataset = me.getDataset();
  9310. var data = dataset.data || (dataset.data = []);
  9311. // In order to correctly handle data addition/deletion animation (an thus simulate
  9312. // real-time charts), we need to monitor these data modifications and synchronize
  9313. // the internal meta data accordingly.
  9314. if (me._data !== data) {
  9315. if (me._data) {
  9316. // This case happens when the user replaced the data array instance.
  9317. unlistenArrayEvents(me._data, me);
  9318. }
  9319. if (data && Object.isExtensible(data)) {
  9320. listenArrayEvents(data, me);
  9321. }
  9322. me._data = data;
  9323. }
  9324. // Re-sync meta data in case the user replaced the data array or if we missed
  9325. // any updates and so make sure that we handle number of datapoints changing.
  9326. me.resyncElements();
  9327. },
  9328. /**
  9329. * Returns the merged user-supplied and default dataset-level options
  9330. * @private
  9331. */
  9332. _configure: function() {
  9333. var me = this;
  9334. me._config = helpers$1.merge(Object.create(null), [
  9335. me.chart.options.datasets[me._type],
  9336. me.getDataset(),
  9337. ], {
  9338. merger: function(key, target, source) {
  9339. if (key !== '_meta' && key !== 'data') {
  9340. helpers$1._merger(key, target, source);
  9341. }
  9342. }
  9343. });
  9344. },
  9345. _update: function(reset) {
  9346. var me = this;
  9347. me._configure();
  9348. me._cachedDataOpts = null;
  9349. me.update(reset);
  9350. },
  9351. update: helpers$1.noop,
  9352. transition: function(easingValue) {
  9353. var meta = this.getMeta();
  9354. var elements = meta.data || [];
  9355. var ilen = elements.length;
  9356. var i = 0;
  9357. for (; i < ilen; ++i) {
  9358. elements[i].transition(easingValue);
  9359. }
  9360. if (meta.dataset) {
  9361. meta.dataset.transition(easingValue);
  9362. }
  9363. },
  9364. draw: function() {
  9365. var meta = this.getMeta();
  9366. var elements = meta.data || [];
  9367. var ilen = elements.length;
  9368. var i = 0;
  9369. if (meta.dataset) {
  9370. meta.dataset.draw();
  9371. }
  9372. for (; i < ilen; ++i) {
  9373. elements[i].draw();
  9374. }
  9375. },
  9376. /**
  9377. * Returns a set of predefined style properties that should be used to represent the dataset
  9378. * or the data if the index is specified
  9379. * @param {number} index - data index
  9380. * @return {IStyleInterface} style object
  9381. */
  9382. getStyle: function(index) {
  9383. var me = this;
  9384. var meta = me.getMeta();
  9385. var dataset = meta.dataset;
  9386. var style;
  9387. me._configure();
  9388. if (dataset && index === undefined) {
  9389. style = me._resolveDatasetElementOptions(dataset || {});
  9390. } else {
  9391. index = index || 0;
  9392. style = me._resolveDataElementOptions(meta.data[index] || {}, index);
  9393. }
  9394. if (style.fill === false || style.fill === null) {
  9395. style.backgroundColor = style.borderColor;
  9396. }
  9397. return style;
  9398. },
  9399. /**
  9400. * @private
  9401. */
  9402. _resolveDatasetElementOptions: function(element, hover) {
  9403. var me = this;
  9404. var chart = me.chart;
  9405. var datasetOpts = me._config;
  9406. var custom = element.custom || {};
  9407. var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
  9408. var elementOptions = me._datasetElementOptions;
  9409. var values = {};
  9410. var i, ilen, key, readKey;
  9411. // Scriptable options
  9412. var context = {
  9413. chart: chart,
  9414. dataset: me.getDataset(),
  9415. datasetIndex: me.index,
  9416. hover: hover
  9417. };
  9418. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  9419. key = elementOptions[i];
  9420. readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
  9421. values[key] = resolve([
  9422. custom[readKey],
  9423. datasetOpts[readKey],
  9424. options[readKey]
  9425. ], context);
  9426. }
  9427. return values;
  9428. },
  9429. /**
  9430. * @private
  9431. */
  9432. _resolveDataElementOptions: function(element, index) {
  9433. var me = this;
  9434. var custom = element && element.custom;
  9435. var cached = me._cachedDataOpts;
  9436. if (cached && !custom) {
  9437. return cached;
  9438. }
  9439. var chart = me.chart;
  9440. var datasetOpts = me._config;
  9441. var options = chart.options.elements[me.dataElementType.prototype._type] || {};
  9442. var elementOptions = me._dataElementOptions;
  9443. var values = {};
  9444. // Scriptable options
  9445. var context = {
  9446. chart: chart,
  9447. dataIndex: index,
  9448. dataset: me.getDataset(),
  9449. datasetIndex: me.index
  9450. };
  9451. // `resolve` sets cacheable to `false` if any option is indexed or scripted
  9452. var info = {cacheable: !custom};
  9453. var keys, i, ilen, key;
  9454. custom = custom || {};
  9455. if (helpers$1.isArray(elementOptions)) {
  9456. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  9457. key = elementOptions[i];
  9458. values[key] = resolve([
  9459. custom[key],
  9460. datasetOpts[key],
  9461. options[key]
  9462. ], context, index, info);
  9463. }
  9464. } else {
  9465. keys = Object.keys(elementOptions);
  9466. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  9467. key = keys[i];
  9468. values[key] = resolve([
  9469. custom[key],
  9470. datasetOpts[elementOptions[key]],
  9471. datasetOpts[key],
  9472. options[key]
  9473. ], context, index, info);
  9474. }
  9475. }
  9476. if (info.cacheable) {
  9477. me._cachedDataOpts = Object.freeze(values);
  9478. }
  9479. return values;
  9480. },
  9481. removeHoverStyle: function(element) {
  9482. helpers$1.merge(element._model, element.$previousStyle || {});
  9483. delete element.$previousStyle;
  9484. },
  9485. setHoverStyle: function(element) {
  9486. var dataset = this.chart.data.datasets[element._datasetIndex];
  9487. var index = element._index;
  9488. var custom = element.custom || {};
  9489. var model = element._model;
  9490. var getHoverColor = helpers$1.getHoverColor;
  9491. element.$previousStyle = {
  9492. backgroundColor: model.backgroundColor,
  9493. borderColor: model.borderColor,
  9494. borderWidth: model.borderWidth
  9495. };
  9496. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  9497. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  9498. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  9499. },
  9500. /**
  9501. * @private
  9502. */
  9503. _removeDatasetHoverStyle: function() {
  9504. var element = this.getMeta().dataset;
  9505. if (element) {
  9506. this.removeHoverStyle(element);
  9507. }
  9508. },
  9509. /**
  9510. * @private
  9511. */
  9512. _setDatasetHoverStyle: function() {
  9513. var element = this.getMeta().dataset;
  9514. var prev = {};
  9515. var i, ilen, key, keys, hoverOptions, model;
  9516. if (!element) {
  9517. return;
  9518. }
  9519. model = element._model;
  9520. hoverOptions = this._resolveDatasetElementOptions(element, true);
  9521. keys = Object.keys(hoverOptions);
  9522. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  9523. key = keys[i];
  9524. prev[key] = model[key];
  9525. model[key] = hoverOptions[key];
  9526. }
  9527. element.$previousStyle = prev;
  9528. },
  9529. /**
  9530. * @private
  9531. */
  9532. resyncElements: function() {
  9533. var me = this;
  9534. var meta = me.getMeta();
  9535. var data = me.getDataset().data;
  9536. var numMeta = meta.data.length;
  9537. var numData = data.length;
  9538. if (numData < numMeta) {
  9539. meta.data.splice(numData, numMeta - numData);
  9540. } else if (numData > numMeta) {
  9541. me.insertElements(numMeta, numData - numMeta);
  9542. }
  9543. },
  9544. /**
  9545. * @private
  9546. */
  9547. insertElements: function(start, count) {
  9548. for (var i = 0; i < count; ++i) {
  9549. this.addElementAndReset(start + i);
  9550. }
  9551. },
  9552. /**
  9553. * @private
  9554. */
  9555. onDataPush: function() {
  9556. var count = arguments.length;
  9557. this.insertElements(this.getDataset().data.length - count, count);
  9558. },
  9559. /**
  9560. * @private
  9561. */
  9562. onDataPop: function() {
  9563. this.getMeta().data.pop();
  9564. },
  9565. /**
  9566. * @private
  9567. */
  9568. onDataShift: function() {
  9569. this.getMeta().data.shift();
  9570. },
  9571. /**
  9572. * @private
  9573. */
  9574. onDataSplice: function(start, count) {
  9575. this.getMeta().data.splice(start, count);
  9576. this.insertElements(start, arguments.length - 2);
  9577. },
  9578. /**
  9579. * @private
  9580. */
  9581. onDataUnshift: function() {
  9582. this.insertElements(0, arguments.length);
  9583. }
  9584. });
  9585. DatasetController.extend = helpers$1.inherits;
  9586. var core_datasetController = DatasetController;
  9587. var TAU = Math.PI * 2;
  9588. core_defaults._set('global', {
  9589. elements: {
  9590. arc: {
  9591. backgroundColor: core_defaults.global.defaultColor,
  9592. borderColor: '#fff',
  9593. borderWidth: 2,
  9594. borderAlign: 'center'
  9595. }
  9596. }
  9597. });
  9598. function clipArc(ctx, arc) {
  9599. var startAngle = arc.startAngle;
  9600. var endAngle = arc.endAngle;
  9601. var pixelMargin = arc.pixelMargin;
  9602. var angleMargin = pixelMargin / arc.outerRadius;
  9603. var x = arc.x;
  9604. var y = arc.y;
  9605. // Draw an inner border by cliping the arc and drawing a double-width border
  9606. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  9607. ctx.beginPath();
  9608. ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  9609. if (arc.innerRadius > pixelMargin) {
  9610. angleMargin = pixelMargin / arc.innerRadius;
  9611. ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);
  9612. } else {
  9613. ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);
  9614. }
  9615. ctx.closePath();
  9616. ctx.clip();
  9617. }
  9618. function drawFullCircleBorders(ctx, vm, arc, inner) {
  9619. var endAngle = arc.endAngle;
  9620. var i;
  9621. if (inner) {
  9622. arc.endAngle = arc.startAngle + TAU;
  9623. clipArc(ctx, arc);
  9624. arc.endAngle = endAngle;
  9625. if (arc.endAngle === arc.startAngle && arc.fullCircles) {
  9626. arc.endAngle += TAU;
  9627. arc.fullCircles--;
  9628. }
  9629. }
  9630. ctx.beginPath();
  9631. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);
  9632. for (i = 0; i < arc.fullCircles; ++i) {
  9633. ctx.stroke();
  9634. }
  9635. ctx.beginPath();
  9636. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);
  9637. for (i = 0; i < arc.fullCircles; ++i) {
  9638. ctx.stroke();
  9639. }
  9640. }
  9641. function drawBorder(ctx, vm, arc) {
  9642. var inner = vm.borderAlign === 'inner';
  9643. if (inner) {
  9644. ctx.lineWidth = vm.borderWidth * 2;
  9645. ctx.lineJoin = 'round';
  9646. } else {
  9647. ctx.lineWidth = vm.borderWidth;
  9648. ctx.lineJoin = 'bevel';
  9649. }
  9650. if (arc.fullCircles) {
  9651. drawFullCircleBorders(ctx, vm, arc, inner);
  9652. }
  9653. if (inner) {
  9654. clipArc(ctx, arc);
  9655. }
  9656. ctx.beginPath();
  9657. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);
  9658. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  9659. ctx.closePath();
  9660. ctx.stroke();
  9661. }
  9662. var element_arc = core_element.extend({
  9663. _type: 'arc',
  9664. inLabelRange: function(mouseX) {
  9665. var vm = this._view;
  9666. if (vm) {
  9667. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  9668. }
  9669. return false;
  9670. },
  9671. inRange: function(chartX, chartY) {
  9672. var vm = this._view;
  9673. if (vm) {
  9674. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  9675. var angle = pointRelativePosition.angle;
  9676. var distance = pointRelativePosition.distance;
  9677. // Sanitise angle range
  9678. var startAngle = vm.startAngle;
  9679. var endAngle = vm.endAngle;
  9680. while (endAngle < startAngle) {
  9681. endAngle += TAU;
  9682. }
  9683. while (angle > endAngle) {
  9684. angle -= TAU;
  9685. }
  9686. while (angle < startAngle) {
  9687. angle += TAU;
  9688. }
  9689. // Check if within the range of the open/close angle
  9690. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  9691. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  9692. return (betweenAngles && withinRadius);
  9693. }
  9694. return false;
  9695. },
  9696. getCenterPoint: function() {
  9697. var vm = this._view;
  9698. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  9699. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  9700. return {
  9701. x: vm.x + Math.cos(halfAngle) * halfRadius,
  9702. y: vm.y + Math.sin(halfAngle) * halfRadius
  9703. };
  9704. },
  9705. getArea: function() {
  9706. var vm = this._view;
  9707. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  9708. },
  9709. tooltipPosition: function() {
  9710. var vm = this._view;
  9711. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  9712. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  9713. return {
  9714. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  9715. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  9716. };
  9717. },
  9718. draw: function() {
  9719. var ctx = this._chart.ctx;
  9720. var vm = this._view;
  9721. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  9722. var arc = {
  9723. x: vm.x,
  9724. y: vm.y,
  9725. innerRadius: vm.innerRadius,
  9726. outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),
  9727. pixelMargin: pixelMargin,
  9728. startAngle: vm.startAngle,
  9729. endAngle: vm.endAngle,
  9730. fullCircles: Math.floor(vm.circumference / TAU)
  9731. };
  9732. var i;
  9733. ctx.save();
  9734. ctx.fillStyle = vm.backgroundColor;
  9735. ctx.strokeStyle = vm.borderColor;
  9736. if (arc.fullCircles) {
  9737. arc.endAngle = arc.startAngle + TAU;
  9738. ctx.beginPath();
  9739. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  9740. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  9741. ctx.closePath();
  9742. for (i = 0; i < arc.fullCircles; ++i) {
  9743. ctx.fill();
  9744. }
  9745. arc.endAngle = arc.startAngle + vm.circumference % TAU;
  9746. }
  9747. ctx.beginPath();
  9748. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  9749. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  9750. ctx.closePath();
  9751. ctx.fill();
  9752. if (vm.borderWidth) {
  9753. drawBorder(ctx, vm, arc);
  9754. }
  9755. ctx.restore();
  9756. }
  9757. });
  9758. var valueOrDefault$1 = helpers$1.valueOrDefault;
  9759. var defaultColor = core_defaults.global.defaultColor;
  9760. core_defaults._set('global', {
  9761. elements: {
  9762. line: {
  9763. tension: 0.4,
  9764. backgroundColor: defaultColor,
  9765. borderWidth: 3,
  9766. borderColor: defaultColor,
  9767. borderCapStyle: 'butt',
  9768. borderDash: [],
  9769. borderDashOffset: 0.0,
  9770. borderJoinStyle: 'miter',
  9771. capBezierPoints: true,
  9772. fill: true, // do we fill in the area between the line and its base axis
  9773. }
  9774. }
  9775. });
  9776. var element_line = core_element.extend({
  9777. _type: 'line',
  9778. draw: function() {
  9779. var me = this;
  9780. var vm = me._view;
  9781. var ctx = me._chart.ctx;
  9782. var spanGaps = vm.spanGaps;
  9783. var points = me._children.slice(); // clone array
  9784. var globalDefaults = core_defaults.global;
  9785. var globalOptionLineElements = globalDefaults.elements.line;
  9786. var lastDrawnIndex = -1;
  9787. var closePath = me._loop;
  9788. var index, previous, currentVM;
  9789. if (!points.length) {
  9790. return;
  9791. }
  9792. if (me._loop) {
  9793. for (index = 0; index < points.length; ++index) {
  9794. previous = helpers$1.previousItem(points, index);
  9795. // If the line has an open path, shift the point array
  9796. if (!points[index]._view.skip && previous._view.skip) {
  9797. points = points.slice(index).concat(points.slice(0, index));
  9798. closePath = spanGaps;
  9799. break;
  9800. }
  9801. }
  9802. // If the line has a close path, add the first point again
  9803. if (closePath) {
  9804. points.push(points[0]);
  9805. }
  9806. }
  9807. ctx.save();
  9808. // Stroke Line Options
  9809. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  9810. // IE 9 and 10 do not support line dash
  9811. if (ctx.setLineDash) {
  9812. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  9813. }
  9814. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  9815. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  9816. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  9817. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  9818. // Stroke Line
  9819. ctx.beginPath();
  9820. // First point moves to it's starting position no matter what
  9821. currentVM = points[0]._view;
  9822. if (!currentVM.skip) {
  9823. ctx.moveTo(currentVM.x, currentVM.y);
  9824. lastDrawnIndex = 0;
  9825. }
  9826. for (index = 1; index < points.length; ++index) {
  9827. currentVM = points[index]._view;
  9828. previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];
  9829. if (!currentVM.skip) {
  9830. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  9831. // There was a gap and this is the first point after the gap
  9832. ctx.moveTo(currentVM.x, currentVM.y);
  9833. } else {
  9834. // Line to next point
  9835. helpers$1.canvas.lineTo(ctx, previous._view, currentVM);
  9836. }
  9837. lastDrawnIndex = index;
  9838. }
  9839. }
  9840. if (closePath) {
  9841. ctx.closePath();
  9842. }
  9843. ctx.stroke();
  9844. ctx.restore();
  9845. }
  9846. });
  9847. var valueOrDefault$2 = helpers$1.valueOrDefault;
  9848. var defaultColor$1 = core_defaults.global.defaultColor;
  9849. core_defaults._set('global', {
  9850. elements: {
  9851. point: {
  9852. radius: 3,
  9853. pointStyle: 'circle',
  9854. backgroundColor: defaultColor$1,
  9855. borderColor: defaultColor$1,
  9856. borderWidth: 1,
  9857. // Hover
  9858. hitRadius: 1,
  9859. hoverRadius: 4,
  9860. hoverBorderWidth: 1
  9861. }
  9862. }
  9863. });
  9864. function xRange(mouseX) {
  9865. var vm = this._view;
  9866. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  9867. }
  9868. function yRange(mouseY) {
  9869. var vm = this._view;
  9870. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  9871. }
  9872. var element_point = core_element.extend({
  9873. _type: 'point',
  9874. inRange: function(mouseX, mouseY) {
  9875. var vm = this._view;
  9876. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  9877. },
  9878. inLabelRange: xRange,
  9879. inXRange: xRange,
  9880. inYRange: yRange,
  9881. getCenterPoint: function() {
  9882. var vm = this._view;
  9883. return {
  9884. x: vm.x,
  9885. y: vm.y
  9886. };
  9887. },
  9888. getArea: function() {
  9889. return Math.PI * Math.pow(this._view.radius, 2);
  9890. },
  9891. tooltipPosition: function() {
  9892. var vm = this._view;
  9893. return {
  9894. x: vm.x,
  9895. y: vm.y,
  9896. padding: vm.radius + vm.borderWidth
  9897. };
  9898. },
  9899. draw: function(chartArea) {
  9900. var vm = this._view;
  9901. var ctx = this._chart.ctx;
  9902. var pointStyle = vm.pointStyle;
  9903. var rotation = vm.rotation;
  9904. var radius = vm.radius;
  9905. var x = vm.x;
  9906. var y = vm.y;
  9907. var globalDefaults = core_defaults.global;
  9908. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  9909. if (vm.skip) {
  9910. return;
  9911. }
  9912. // Clipping for Points.
  9913. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  9914. ctx.strokeStyle = vm.borderColor || defaultColor;
  9915. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  9916. ctx.fillStyle = vm.backgroundColor || defaultColor;
  9917. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  9918. }
  9919. }
  9920. });
  9921. var defaultColor$2 = core_defaults.global.defaultColor;
  9922. core_defaults._set('global', {
  9923. elements: {
  9924. rectangle: {
  9925. backgroundColor: defaultColor$2,
  9926. borderColor: defaultColor$2,
  9927. borderSkipped: 'bottom',
  9928. borderWidth: 0
  9929. }
  9930. }
  9931. });
  9932. function isVertical(vm) {
  9933. return vm && vm.width !== undefined;
  9934. }
  9935. /**
  9936. * Helper function to get the bounds of the bar regardless of the orientation
  9937. * @param bar {Chart.Element.Rectangle} the bar
  9938. * @return {Bounds} bounds of the bar
  9939. * @private
  9940. */
  9941. function getBarBounds(vm) {
  9942. var x1, x2, y1, y2, half;
  9943. if (isVertical(vm)) {
  9944. half = vm.width / 2;
  9945. x1 = vm.x - half;
  9946. x2 = vm.x + half;
  9947. y1 = Math.min(vm.y, vm.base);
  9948. y2 = Math.max(vm.y, vm.base);
  9949. } else {
  9950. half = vm.height / 2;
  9951. x1 = Math.min(vm.x, vm.base);
  9952. x2 = Math.max(vm.x, vm.base);
  9953. y1 = vm.y - half;
  9954. y2 = vm.y + half;
  9955. }
  9956. return {
  9957. left: x1,
  9958. top: y1,
  9959. right: x2,
  9960. bottom: y2
  9961. };
  9962. }
  9963. function swap(orig, v1, v2) {
  9964. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  9965. }
  9966. function parseBorderSkipped(vm) {
  9967. var edge = vm.borderSkipped;
  9968. var res = {};
  9969. if (!edge) {
  9970. return res;
  9971. }
  9972. if (vm.horizontal) {
  9973. if (vm.base > vm.x) {
  9974. edge = swap(edge, 'left', 'right');
  9975. }
  9976. } else if (vm.base < vm.y) {
  9977. edge = swap(edge, 'bottom', 'top');
  9978. }
  9979. res[edge] = true;
  9980. return res;
  9981. }
  9982. function parseBorderWidth(vm, maxW, maxH) {
  9983. var value = vm.borderWidth;
  9984. var skip = parseBorderSkipped(vm);
  9985. var t, r, b, l;
  9986. if (helpers$1.isObject(value)) {
  9987. t = +value.top || 0;
  9988. r = +value.right || 0;
  9989. b = +value.bottom || 0;
  9990. l = +value.left || 0;
  9991. } else {
  9992. t = r = b = l = +value || 0;
  9993. }
  9994. return {
  9995. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  9996. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  9997. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  9998. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  9999. };
  10000. }
  10001. function boundingRects(vm) {
  10002. var bounds = getBarBounds(vm);
  10003. var width = bounds.right - bounds.left;
  10004. var height = bounds.bottom - bounds.top;
  10005. var border = parseBorderWidth(vm, width / 2, height / 2);
  10006. return {
  10007. outer: {
  10008. x: bounds.left,
  10009. y: bounds.top,
  10010. w: width,
  10011. h: height
  10012. },
  10013. inner: {
  10014. x: bounds.left + border.l,
  10015. y: bounds.top + border.t,
  10016. w: width - border.l - border.r,
  10017. h: height - border.t - border.b
  10018. }
  10019. };
  10020. }
  10021. function inRange(vm, x, y) {
  10022. var skipX = x === null;
  10023. var skipY = y === null;
  10024. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  10025. return bounds
  10026. && (skipX || x >= bounds.left && x <= bounds.right)
  10027. && (skipY || y >= bounds.top && y <= bounds.bottom);
  10028. }
  10029. var element_rectangle = core_element.extend({
  10030. _type: 'rectangle',
  10031. draw: function() {
  10032. var ctx = this._chart.ctx;
  10033. var vm = this._view;
  10034. var rects = boundingRects(vm);
  10035. var outer = rects.outer;
  10036. var inner = rects.inner;
  10037. ctx.fillStyle = vm.backgroundColor;
  10038. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  10039. if (outer.w === inner.w && outer.h === inner.h) {
  10040. return;
  10041. }
  10042. ctx.save();
  10043. ctx.beginPath();
  10044. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  10045. ctx.clip();
  10046. ctx.fillStyle = vm.borderColor;
  10047. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  10048. ctx.fill('evenodd');
  10049. ctx.restore();
  10050. },
  10051. height: function() {
  10052. var vm = this._view;
  10053. return vm.base - vm.y;
  10054. },
  10055. inRange: function(mouseX, mouseY) {
  10056. return inRange(this._view, mouseX, mouseY);
  10057. },
  10058. inLabelRange: function(mouseX, mouseY) {
  10059. var vm = this._view;
  10060. return isVertical(vm)
  10061. ? inRange(vm, mouseX, null)
  10062. : inRange(vm, null, mouseY);
  10063. },
  10064. inXRange: function(mouseX) {
  10065. return inRange(this._view, mouseX, null);
  10066. },
  10067. inYRange: function(mouseY) {
  10068. return inRange(this._view, null, mouseY);
  10069. },
  10070. getCenterPoint: function() {
  10071. var vm = this._view;
  10072. var x, y;
  10073. if (isVertical(vm)) {
  10074. x = vm.x;
  10075. y = (vm.y + vm.base) / 2;
  10076. } else {
  10077. x = (vm.x + vm.base) / 2;
  10078. y = vm.y;
  10079. }
  10080. return {x: x, y: y};
  10081. },
  10082. getArea: function() {
  10083. var vm = this._view;
  10084. return isVertical(vm)
  10085. ? vm.width * Math.abs(vm.y - vm.base)
  10086. : vm.height * Math.abs(vm.x - vm.base);
  10087. },
  10088. tooltipPosition: function() {
  10089. var vm = this._view;
  10090. return {
  10091. x: vm.x,
  10092. y: vm.y
  10093. };
  10094. }
  10095. });
  10096. var elements = {};
  10097. var Arc = element_arc;
  10098. var Line = element_line;
  10099. var Point = element_point;
  10100. var Rectangle = element_rectangle;
  10101. elements.Arc = Arc;
  10102. elements.Line = Line;
  10103. elements.Point = Point;
  10104. elements.Rectangle = Rectangle;
  10105. var deprecated = helpers$1._deprecated;
  10106. var valueOrDefault$3 = helpers$1.valueOrDefault;
  10107. core_defaults._set('bar', {
  10108. hover: {
  10109. mode: 'label'
  10110. },
  10111. scales: {
  10112. xAxes: [{
  10113. type: 'category',
  10114. offset: true,
  10115. gridLines: {
  10116. offsetGridLines: true
  10117. }
  10118. }],
  10119. yAxes: [{
  10120. type: 'linear'
  10121. }]
  10122. }
  10123. });
  10124. core_defaults._set('global', {
  10125. datasets: {
  10126. bar: {
  10127. categoryPercentage: 0.8,
  10128. barPercentage: 0.9
  10129. }
  10130. }
  10131. });
  10132. /**
  10133. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  10134. * @private
  10135. */
  10136. function computeMinSampleSize(scale, pixels) {
  10137. var min = scale._length;
  10138. var prev, curr, i, ilen;
  10139. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  10140. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  10141. }
  10142. for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
  10143. curr = scale.getPixelForTick(i);
  10144. min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
  10145. prev = curr;
  10146. }
  10147. return min;
  10148. }
  10149. /**
  10150. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  10151. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  10152. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  10153. * @private
  10154. */
  10155. function computeFitCategoryTraits(index, ruler, options) {
  10156. var thickness = options.barThickness;
  10157. var count = ruler.stackCount;
  10158. var curr = ruler.pixels[index];
  10159. var min = helpers$1.isNullOrUndef(thickness)
  10160. ? computeMinSampleSize(ruler.scale, ruler.pixels)
  10161. : -1;
  10162. var size, ratio;
  10163. if (helpers$1.isNullOrUndef(thickness)) {
  10164. size = min * options.categoryPercentage;
  10165. ratio = options.barPercentage;
  10166. } else {
  10167. // When bar thickness is enforced, category and bar percentages are ignored.
  10168. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  10169. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  10170. size = thickness * count;
  10171. ratio = 1;
  10172. }
  10173. return {
  10174. chunk: size / count,
  10175. ratio: ratio,
  10176. start: curr - (size / 2)
  10177. };
  10178. }
  10179. /**
  10180. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  10181. * percentage options are 1), based on the previous and following categories. This mode
  10182. * generates bars with different widths when data are not evenly spaced.
  10183. * @private
  10184. */
  10185. function computeFlexCategoryTraits(index, ruler, options) {
  10186. var pixels = ruler.pixels;
  10187. var curr = pixels[index];
  10188. var prev = index > 0 ? pixels[index - 1] : null;
  10189. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  10190. var percent = options.categoryPercentage;
  10191. var start, size;
  10192. if (prev === null) {
  10193. // first data: its size is double based on the next point or,
  10194. // if it's also the last data, we use the scale size.
  10195. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  10196. }
  10197. if (next === null) {
  10198. // last data: its size is also double based on the previous point.
  10199. next = curr + curr - prev;
  10200. }
  10201. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  10202. size = Math.abs(next - prev) / 2 * percent;
  10203. return {
  10204. chunk: size / ruler.stackCount,
  10205. ratio: options.barPercentage,
  10206. start: start
  10207. };
  10208. }
  10209. var controller_bar = core_datasetController.extend({
  10210. dataElementType: elements.Rectangle,
  10211. /**
  10212. * @private
  10213. */
  10214. _dataElementOptions: [
  10215. 'backgroundColor',
  10216. 'borderColor',
  10217. 'borderSkipped',
  10218. 'borderWidth',
  10219. 'barPercentage',
  10220. 'barThickness',
  10221. 'categoryPercentage',
  10222. 'maxBarThickness',
  10223. 'minBarLength'
  10224. ],
  10225. initialize: function() {
  10226. var me = this;
  10227. var meta, scaleOpts;
  10228. core_datasetController.prototype.initialize.apply(me, arguments);
  10229. meta = me.getMeta();
  10230. meta.stack = me.getDataset().stack;
  10231. meta.bar = true;
  10232. scaleOpts = me._getIndexScale().options;
  10233. deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
  10234. deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
  10235. deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
  10236. deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
  10237. deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
  10238. },
  10239. update: function(reset) {
  10240. var me = this;
  10241. var rects = me.getMeta().data;
  10242. var i, ilen;
  10243. me._ruler = me.getRuler();
  10244. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  10245. me.updateElement(rects[i], i, reset);
  10246. }
  10247. },
  10248. updateElement: function(rectangle, index, reset) {
  10249. var me = this;
  10250. var meta = me.getMeta();
  10251. var dataset = me.getDataset();
  10252. var options = me._resolveDataElementOptions(rectangle, index);
  10253. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  10254. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  10255. rectangle._datasetIndex = me.index;
  10256. rectangle._index = index;
  10257. rectangle._model = {
  10258. backgroundColor: options.backgroundColor,
  10259. borderColor: options.borderColor,
  10260. borderSkipped: options.borderSkipped,
  10261. borderWidth: options.borderWidth,
  10262. datasetLabel: dataset.label,
  10263. label: me.chart.data.labels[index]
  10264. };
  10265. if (helpers$1.isArray(dataset.data[index])) {
  10266. rectangle._model.borderSkipped = null;
  10267. }
  10268. me._updateElementGeometry(rectangle, index, reset, options);
  10269. rectangle.pivot();
  10270. },
  10271. /**
  10272. * @private
  10273. */
  10274. _updateElementGeometry: function(rectangle, index, reset, options) {
  10275. var me = this;
  10276. var model = rectangle._model;
  10277. var vscale = me._getValueScale();
  10278. var base = vscale.getBasePixel();
  10279. var horizontal = vscale.isHorizontal();
  10280. var ruler = me._ruler || me.getRuler();
  10281. var vpixels = me.calculateBarValuePixels(me.index, index, options);
  10282. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
  10283. model.horizontal = horizontal;
  10284. model.base = reset ? base : vpixels.base;
  10285. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  10286. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  10287. model.height = horizontal ? ipixels.size : undefined;
  10288. model.width = horizontal ? undefined : ipixels.size;
  10289. },
  10290. /**
  10291. * Returns the stacks based on groups and bar visibility.
  10292. * @param {number} [last] - The dataset index
  10293. * @returns {string[]} The list of stack IDs
  10294. * @private
  10295. */
  10296. _getStacks: function(last) {
  10297. var me = this;
  10298. var scale = me._getIndexScale();
  10299. var metasets = scale._getMatchingVisibleMetas(me._type);
  10300. var stacked = scale.options.stacked;
  10301. var ilen = metasets.length;
  10302. var stacks = [];
  10303. var i, meta;
  10304. for (i = 0; i < ilen; ++i) {
  10305. meta = metasets[i];
  10306. // stacked | meta.stack
  10307. // | found | not found | undefined
  10308. // false | x | x | x
  10309. // true | | x |
  10310. // undefined | | x | x
  10311. if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
  10312. (stacked === undefined && meta.stack === undefined)) {
  10313. stacks.push(meta.stack);
  10314. }
  10315. if (meta.index === last) {
  10316. break;
  10317. }
  10318. }
  10319. return stacks;
  10320. },
  10321. /**
  10322. * Returns the effective number of stacks based on groups and bar visibility.
  10323. * @private
  10324. */
  10325. getStackCount: function() {
  10326. return this._getStacks().length;
  10327. },
  10328. /**
  10329. * Returns the stack index for the given dataset based on groups and bar visibility.
  10330. * @param {number} [datasetIndex] - The dataset index
  10331. * @param {string} [name] - The stack name to find
  10332. * @returns {number} The stack index
  10333. * @private
  10334. */
  10335. getStackIndex: function(datasetIndex, name) {
  10336. var stacks = this._getStacks(datasetIndex);
  10337. var index = (name !== undefined)
  10338. ? stacks.indexOf(name)
  10339. : -1; // indexOf returns -1 if element is not present
  10340. return (index === -1)
  10341. ? stacks.length - 1
  10342. : index;
  10343. },
  10344. /**
  10345. * @private
  10346. */
  10347. getRuler: function() {
  10348. var me = this;
  10349. var scale = me._getIndexScale();
  10350. var pixels = [];
  10351. var i, ilen;
  10352. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  10353. pixels.push(scale.getPixelForValue(null, i, me.index));
  10354. }
  10355. return {
  10356. pixels: pixels,
  10357. start: scale._startPixel,
  10358. end: scale._endPixel,
  10359. stackCount: me.getStackCount(),
  10360. scale: scale
  10361. };
  10362. },
  10363. /**
  10364. * Note: pixel values are not clamped to the scale area.
  10365. * @private
  10366. */
  10367. calculateBarValuePixels: function(datasetIndex, index, options) {
  10368. var me = this;
  10369. var chart = me.chart;
  10370. var scale = me._getValueScale();
  10371. var isHorizontal = scale.isHorizontal();
  10372. var datasets = chart.data.datasets;
  10373. var metasets = scale._getMatchingVisibleMetas(me._type);
  10374. var value = scale._parseValue(datasets[datasetIndex].data[index]);
  10375. var minBarLength = options.minBarLength;
  10376. var stacked = scale.options.stacked;
  10377. var stack = me.getMeta().stack;
  10378. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  10379. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  10380. var ilen = metasets.length;
  10381. var i, imeta, ivalue, base, head, size, stackLength;
  10382. if (stacked || (stacked === undefined && stack !== undefined)) {
  10383. for (i = 0; i < ilen; ++i) {
  10384. imeta = metasets[i];
  10385. if (imeta.index === datasetIndex) {
  10386. break;
  10387. }
  10388. if (imeta.stack === stack) {
  10389. stackLength = scale._parseValue(datasets[imeta.index].data[index]);
  10390. ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
  10391. if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
  10392. start += ivalue;
  10393. }
  10394. }
  10395. }
  10396. }
  10397. base = scale.getPixelForValue(start);
  10398. head = scale.getPixelForValue(start + length);
  10399. size = head - base;
  10400. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  10401. size = minBarLength;
  10402. if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
  10403. head = base - minBarLength;
  10404. } else {
  10405. head = base + minBarLength;
  10406. }
  10407. }
  10408. return {
  10409. size: size,
  10410. base: base,
  10411. head: head,
  10412. center: head + size / 2
  10413. };
  10414. },
  10415. /**
  10416. * @private
  10417. */
  10418. calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {
  10419. var me = this;
  10420. var range = options.barThickness === 'flex'
  10421. ? computeFlexCategoryTraits(index, ruler, options)
  10422. : computeFitCategoryTraits(index, ruler, options);
  10423. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  10424. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  10425. var size = Math.min(
  10426. valueOrDefault$3(options.maxBarThickness, Infinity),
  10427. range.chunk * range.ratio);
  10428. return {
  10429. base: center - size / 2,
  10430. head: center + size / 2,
  10431. center: center,
  10432. size: size
  10433. };
  10434. },
  10435. draw: function() {
  10436. var me = this;
  10437. var chart = me.chart;
  10438. var scale = me._getValueScale();
  10439. var rects = me.getMeta().data;
  10440. var dataset = me.getDataset();
  10441. var ilen = rects.length;
  10442. var i = 0;
  10443. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  10444. for (; i < ilen; ++i) {
  10445. var val = scale._parseValue(dataset.data[i]);
  10446. if (!isNaN(val.min) && !isNaN(val.max)) {
  10447. rects[i].draw();
  10448. }
  10449. }
  10450. helpers$1.canvas.unclipArea(chart.ctx);
  10451. },
  10452. /**
  10453. * @private
  10454. */
  10455. _resolveDataElementOptions: function() {
  10456. var me = this;
  10457. var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));
  10458. var indexOpts = me._getIndexScale().options;
  10459. var valueOpts = me._getValueScale().options;
  10460. values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);
  10461. values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);
  10462. values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);
  10463. values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);
  10464. values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);
  10465. return values;
  10466. }
  10467. });
  10468. var valueOrDefault$4 = helpers$1.valueOrDefault;
  10469. var resolve$1 = helpers$1.options.resolve;
  10470. core_defaults._set('bubble', {
  10471. hover: {
  10472. mode: 'single'
  10473. },
  10474. scales: {
  10475. xAxes: [{
  10476. type: 'linear', // bubble should probably use a linear scale by default
  10477. position: 'bottom',
  10478. id: 'x-axis-0' // need an ID so datasets can reference the scale
  10479. }],
  10480. yAxes: [{
  10481. type: 'linear',
  10482. position: 'left',
  10483. id: 'y-axis-0'
  10484. }]
  10485. },
  10486. tooltips: {
  10487. callbacks: {
  10488. title: function() {
  10489. // Title doesn't make sense for scatter since we format the data as a point
  10490. return '';
  10491. },
  10492. label: function(item, data) {
  10493. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  10494. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  10495. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  10496. }
  10497. }
  10498. }
  10499. });
  10500. var controller_bubble = core_datasetController.extend({
  10501. /**
  10502. * @protected
  10503. */
  10504. dataElementType: elements.Point,
  10505. /**
  10506. * @private
  10507. */
  10508. _dataElementOptions: [
  10509. 'backgroundColor',
  10510. 'borderColor',
  10511. 'borderWidth',
  10512. 'hoverBackgroundColor',
  10513. 'hoverBorderColor',
  10514. 'hoverBorderWidth',
  10515. 'hoverRadius',
  10516. 'hitRadius',
  10517. 'pointStyle',
  10518. 'rotation'
  10519. ],
  10520. /**
  10521. * @protected
  10522. */
  10523. update: function(reset) {
  10524. var me = this;
  10525. var meta = me.getMeta();
  10526. var points = meta.data;
  10527. // Update Points
  10528. helpers$1.each(points, function(point, index) {
  10529. me.updateElement(point, index, reset);
  10530. });
  10531. },
  10532. /**
  10533. * @protected
  10534. */
  10535. updateElement: function(point, index, reset) {
  10536. var me = this;
  10537. var meta = me.getMeta();
  10538. var custom = point.custom || {};
  10539. var xScale = me.getScaleForId(meta.xAxisID);
  10540. var yScale = me.getScaleForId(meta.yAxisID);
  10541. var options = me._resolveDataElementOptions(point, index);
  10542. var data = me.getDataset().data[index];
  10543. var dsIndex = me.index;
  10544. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  10545. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  10546. point._xScale = xScale;
  10547. point._yScale = yScale;
  10548. point._options = options;
  10549. point._datasetIndex = dsIndex;
  10550. point._index = index;
  10551. point._model = {
  10552. backgroundColor: options.backgroundColor,
  10553. borderColor: options.borderColor,
  10554. borderWidth: options.borderWidth,
  10555. hitRadius: options.hitRadius,
  10556. pointStyle: options.pointStyle,
  10557. rotation: options.rotation,
  10558. radius: reset ? 0 : options.radius,
  10559. skip: custom.skip || isNaN(x) || isNaN(y),
  10560. x: x,
  10561. y: y,
  10562. };
  10563. point.pivot();
  10564. },
  10565. /**
  10566. * @protected
  10567. */
  10568. setHoverStyle: function(point) {
  10569. var model = point._model;
  10570. var options = point._options;
  10571. var getHoverColor = helpers$1.getHoverColor;
  10572. point.$previousStyle = {
  10573. backgroundColor: model.backgroundColor,
  10574. borderColor: model.borderColor,
  10575. borderWidth: model.borderWidth,
  10576. radius: model.radius
  10577. };
  10578. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  10579. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  10580. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  10581. model.radius = options.radius + options.hoverRadius;
  10582. },
  10583. /**
  10584. * @private
  10585. */
  10586. _resolveDataElementOptions: function(point, index) {
  10587. var me = this;
  10588. var chart = me.chart;
  10589. var dataset = me.getDataset();
  10590. var custom = point.custom || {};
  10591. var data = dataset.data[index] || {};
  10592. var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);
  10593. // Scriptable options
  10594. var context = {
  10595. chart: chart,
  10596. dataIndex: index,
  10597. dataset: dataset,
  10598. datasetIndex: me.index
  10599. };
  10600. // In case values were cached (and thus frozen), we need to clone the values
  10601. if (me._cachedDataOpts === values) {
  10602. values = helpers$1.extend({}, values);
  10603. }
  10604. // Custom radius resolution
  10605. values.radius = resolve$1([
  10606. custom.radius,
  10607. data.r,
  10608. me._config.radius,
  10609. chart.options.elements.point.radius
  10610. ], context, index);
  10611. return values;
  10612. }
  10613. });
  10614. var valueOrDefault$5 = helpers$1.valueOrDefault;
  10615. var PI$1 = Math.PI;
  10616. var DOUBLE_PI$1 = PI$1 * 2;
  10617. var HALF_PI$1 = PI$1 / 2;
  10618. core_defaults._set('doughnut', {
  10619. animation: {
  10620. // Boolean - Whether we animate the rotation of the Doughnut
  10621. animateRotate: true,
  10622. // Boolean - Whether we animate scaling the Doughnut from the centre
  10623. animateScale: false
  10624. },
  10625. hover: {
  10626. mode: 'single'
  10627. },
  10628. legendCallback: function(chart) {
  10629. var list = document.createElement('ul');
  10630. var data = chart.data;
  10631. var datasets = data.datasets;
  10632. var labels = data.labels;
  10633. var i, ilen, listItem, listItemSpan;
  10634. list.setAttribute('class', chart.id + '-legend');
  10635. if (datasets.length) {
  10636. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  10637. listItem = list.appendChild(document.createElement('li'));
  10638. listItemSpan = listItem.appendChild(document.createElement('span'));
  10639. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  10640. if (labels[i]) {
  10641. listItem.appendChild(document.createTextNode(labels[i]));
  10642. }
  10643. }
  10644. }
  10645. return list.outerHTML;
  10646. },
  10647. legend: {
  10648. labels: {
  10649. generateLabels: function(chart) {
  10650. var data = chart.data;
  10651. if (data.labels.length && data.datasets.length) {
  10652. return data.labels.map(function(label, i) {
  10653. var meta = chart.getDatasetMeta(0);
  10654. var style = meta.controller.getStyle(i);
  10655. return {
  10656. text: label,
  10657. fillStyle: style.backgroundColor,
  10658. strokeStyle: style.borderColor,
  10659. lineWidth: style.borderWidth,
  10660. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  10661. // Extra data used for toggling the correct item
  10662. index: i
  10663. };
  10664. });
  10665. }
  10666. return [];
  10667. }
  10668. },
  10669. onClick: function(e, legendItem) {
  10670. var index = legendItem.index;
  10671. var chart = this.chart;
  10672. var i, ilen, meta;
  10673. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  10674. meta = chart.getDatasetMeta(i);
  10675. // toggle visibility of index if exists
  10676. if (meta.data[index]) {
  10677. meta.data[index].hidden = !meta.data[index].hidden;
  10678. }
  10679. }
  10680. chart.update();
  10681. }
  10682. },
  10683. // The percentage of the chart that we cut out of the middle.
  10684. cutoutPercentage: 50,
  10685. // The rotation of the chart, where the first data arc begins.
  10686. rotation: -HALF_PI$1,
  10687. // The total circumference of the chart.
  10688. circumference: DOUBLE_PI$1,
  10689. // Need to override these to give a nice default
  10690. tooltips: {
  10691. callbacks: {
  10692. title: function() {
  10693. return '';
  10694. },
  10695. label: function(tooltipItem, data) {
  10696. var dataLabel = data.labels[tooltipItem.index];
  10697. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  10698. if (helpers$1.isArray(dataLabel)) {
  10699. // show value on first line of multiline label
  10700. // need to clone because we are changing the value
  10701. dataLabel = dataLabel.slice();
  10702. dataLabel[0] += value;
  10703. } else {
  10704. dataLabel += value;
  10705. }
  10706. return dataLabel;
  10707. }
  10708. }
  10709. }
  10710. });
  10711. var controller_doughnut = core_datasetController.extend({
  10712. dataElementType: elements.Arc,
  10713. linkScales: helpers$1.noop,
  10714. /**
  10715. * @private
  10716. */
  10717. _dataElementOptions: [
  10718. 'backgroundColor',
  10719. 'borderColor',
  10720. 'borderWidth',
  10721. 'borderAlign',
  10722. 'hoverBackgroundColor',
  10723. 'hoverBorderColor',
  10724. 'hoverBorderWidth',
  10725. ],
  10726. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  10727. getRingIndex: function(datasetIndex) {
  10728. var ringIndex = 0;
  10729. for (var j = 0; j < datasetIndex; ++j) {
  10730. if (this.chart.isDatasetVisible(j)) {
  10731. ++ringIndex;
  10732. }
  10733. }
  10734. return ringIndex;
  10735. },
  10736. update: function(reset) {
  10737. var me = this;
  10738. var chart = me.chart;
  10739. var chartArea = chart.chartArea;
  10740. var opts = chart.options;
  10741. var ratioX = 1;
  10742. var ratioY = 1;
  10743. var offsetX = 0;
  10744. var offsetY = 0;
  10745. var meta = me.getMeta();
  10746. var arcs = meta.data;
  10747. var cutout = opts.cutoutPercentage / 100 || 0;
  10748. var circumference = opts.circumference;
  10749. var chartWeight = me._getRingWeight(me.index);
  10750. var maxWidth, maxHeight, i, ilen;
  10751. // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
  10752. if (circumference < DOUBLE_PI$1) {
  10753. var startAngle = opts.rotation % DOUBLE_PI$1;
  10754. startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;
  10755. var endAngle = startAngle + circumference;
  10756. var startX = Math.cos(startAngle);
  10757. var startY = Math.sin(startAngle);
  10758. var endX = Math.cos(endAngle);
  10759. var endY = Math.sin(endAngle);
  10760. var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;
  10761. var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;
  10762. var contains180 = startAngle === -PI$1 || endAngle >= PI$1;
  10763. var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;
  10764. var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
  10765. var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
  10766. var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
  10767. var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
  10768. ratioX = (maxX - minX) / 2;
  10769. ratioY = (maxY - minY) / 2;
  10770. offsetX = -(maxX + minX) / 2;
  10771. offsetY = -(maxY + minY) / 2;
  10772. }
  10773. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  10774. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  10775. }
  10776. chart.borderWidth = me.getMaxBorderWidth();
  10777. maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
  10778. maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
  10779. chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  10780. chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
  10781. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  10782. chart.offsetX = offsetX * chart.outerRadius;
  10783. chart.offsetY = offsetY * chart.outerRadius;
  10784. meta.total = me.calculateTotal();
  10785. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  10786. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  10787. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  10788. me.updateElement(arcs[i], i, reset);
  10789. }
  10790. },
  10791. updateElement: function(arc, index, reset) {
  10792. var me = this;
  10793. var chart = me.chart;
  10794. var chartArea = chart.chartArea;
  10795. var opts = chart.options;
  10796. var animationOpts = opts.animation;
  10797. var centerX = (chartArea.left + chartArea.right) / 2;
  10798. var centerY = (chartArea.top + chartArea.bottom) / 2;
  10799. var startAngle = opts.rotation; // non reset case handled later
  10800. var endAngle = opts.rotation; // non reset case handled later
  10801. var dataset = me.getDataset();
  10802. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1);
  10803. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  10804. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  10805. var options = arc._options || {};
  10806. helpers$1.extend(arc, {
  10807. // Utility
  10808. _datasetIndex: me.index,
  10809. _index: index,
  10810. // Desired view properties
  10811. _model: {
  10812. backgroundColor: options.backgroundColor,
  10813. borderColor: options.borderColor,
  10814. borderWidth: options.borderWidth,
  10815. borderAlign: options.borderAlign,
  10816. x: centerX + chart.offsetX,
  10817. y: centerY + chart.offsetY,
  10818. startAngle: startAngle,
  10819. endAngle: endAngle,
  10820. circumference: circumference,
  10821. outerRadius: outerRadius,
  10822. innerRadius: innerRadius,
  10823. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  10824. }
  10825. });
  10826. var model = arc._model;
  10827. // Set correct angles if not resetting
  10828. if (!reset || !animationOpts.animateRotate) {
  10829. if (index === 0) {
  10830. model.startAngle = opts.rotation;
  10831. } else {
  10832. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  10833. }
  10834. model.endAngle = model.startAngle + model.circumference;
  10835. }
  10836. arc.pivot();
  10837. },
  10838. calculateTotal: function() {
  10839. var dataset = this.getDataset();
  10840. var meta = this.getMeta();
  10841. var total = 0;
  10842. var value;
  10843. helpers$1.each(meta.data, function(element, index) {
  10844. value = dataset.data[index];
  10845. if (!isNaN(value) && !element.hidden) {
  10846. total += Math.abs(value);
  10847. }
  10848. });
  10849. /* if (total === 0) {
  10850. total = NaN;
  10851. }*/
  10852. return total;
  10853. },
  10854. calculateCircumference: function(value) {
  10855. var total = this.getMeta().total;
  10856. if (total > 0 && !isNaN(value)) {
  10857. return DOUBLE_PI$1 * (Math.abs(value) / total);
  10858. }
  10859. return 0;
  10860. },
  10861. // gets the max border or hover width to properly scale pie charts
  10862. getMaxBorderWidth: function(arcs) {
  10863. var me = this;
  10864. var max = 0;
  10865. var chart = me.chart;
  10866. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  10867. if (!arcs) {
  10868. // Find the outmost visible dataset
  10869. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  10870. if (chart.isDatasetVisible(i)) {
  10871. meta = chart.getDatasetMeta(i);
  10872. arcs = meta.data;
  10873. if (i !== me.index) {
  10874. controller = meta.controller;
  10875. }
  10876. break;
  10877. }
  10878. }
  10879. }
  10880. if (!arcs) {
  10881. return 0;
  10882. }
  10883. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  10884. arc = arcs[i];
  10885. if (controller) {
  10886. controller._configure();
  10887. options = controller._resolveDataElementOptions(arc, i);
  10888. } else {
  10889. options = arc._options;
  10890. }
  10891. if (options.borderAlign !== 'inner') {
  10892. borderWidth = options.borderWidth;
  10893. hoverWidth = options.hoverBorderWidth;
  10894. max = borderWidth > max ? borderWidth : max;
  10895. max = hoverWidth > max ? hoverWidth : max;
  10896. }
  10897. }
  10898. return max;
  10899. },
  10900. /**
  10901. * @protected
  10902. */
  10903. setHoverStyle: function(arc) {
  10904. var model = arc._model;
  10905. var options = arc._options;
  10906. var getHoverColor = helpers$1.getHoverColor;
  10907. arc.$previousStyle = {
  10908. backgroundColor: model.backgroundColor,
  10909. borderColor: model.borderColor,
  10910. borderWidth: model.borderWidth,
  10911. };
  10912. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  10913. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  10914. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  10915. },
  10916. /**
  10917. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  10918. * @private
  10919. */
  10920. _getRingWeightOffset: function(datasetIndex) {
  10921. var ringWeightOffset = 0;
  10922. for (var i = 0; i < datasetIndex; ++i) {
  10923. if (this.chart.isDatasetVisible(i)) {
  10924. ringWeightOffset += this._getRingWeight(i);
  10925. }
  10926. }
  10927. return ringWeightOffset;
  10928. },
  10929. /**
  10930. * @private
  10931. */
  10932. _getRingWeight: function(dataSetIndex) {
  10933. return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  10934. },
  10935. /**
  10936. * Returns the sum of all visibile data set weights. This value can be 0.
  10937. * @private
  10938. */
  10939. _getVisibleDatasetWeightTotal: function() {
  10940. return this._getRingWeightOffset(this.chart.data.datasets.length);
  10941. }
  10942. });
  10943. core_defaults._set('horizontalBar', {
  10944. hover: {
  10945. mode: 'index',
  10946. axis: 'y'
  10947. },
  10948. scales: {
  10949. xAxes: [{
  10950. type: 'linear',
  10951. position: 'bottom'
  10952. }],
  10953. yAxes: [{
  10954. type: 'category',
  10955. position: 'left',
  10956. offset: true,
  10957. gridLines: {
  10958. offsetGridLines: true
  10959. }
  10960. }]
  10961. },
  10962. elements: {
  10963. rectangle: {
  10964. borderSkipped: 'left'
  10965. }
  10966. },
  10967. tooltips: {
  10968. mode: 'index',
  10969. axis: 'y'
  10970. }
  10971. });
  10972. core_defaults._set('global', {
  10973. datasets: {
  10974. horizontalBar: {
  10975. categoryPercentage: 0.8,
  10976. barPercentage: 0.9
  10977. }
  10978. }
  10979. });
  10980. var controller_horizontalBar = controller_bar.extend({
  10981. /**
  10982. * @private
  10983. */
  10984. _getValueScaleId: function() {
  10985. return this.getMeta().xAxisID;
  10986. },
  10987. /**
  10988. * @private
  10989. */
  10990. _getIndexScaleId: function() {
  10991. return this.getMeta().yAxisID;
  10992. }
  10993. });
  10994. var valueOrDefault$6 = helpers$1.valueOrDefault;
  10995. var resolve$2 = helpers$1.options.resolve;
  10996. var isPointInArea = helpers$1.canvas._isPointInArea;
  10997. core_defaults._set('line', {
  10998. showLines: true,
  10999. spanGaps: false,
  11000. hover: {
  11001. mode: 'label'
  11002. },
  11003. scales: {
  11004. xAxes: [{
  11005. type: 'category',
  11006. id: 'x-axis-0'
  11007. }],
  11008. yAxes: [{
  11009. type: 'linear',
  11010. id: 'y-axis-0'
  11011. }]
  11012. }
  11013. });
  11014. function scaleClip(scale, halfBorderWidth) {
  11015. var tickOpts = scale && scale.options.ticks || {};
  11016. var reverse = tickOpts.reverse;
  11017. var min = tickOpts.min === undefined ? halfBorderWidth : 0;
  11018. var max = tickOpts.max === undefined ? halfBorderWidth : 0;
  11019. return {
  11020. start: reverse ? max : min,
  11021. end: reverse ? min : max
  11022. };
  11023. }
  11024. function defaultClip(xScale, yScale, borderWidth) {
  11025. var halfBorderWidth = borderWidth / 2;
  11026. var x = scaleClip(xScale, halfBorderWidth);
  11027. var y = scaleClip(yScale, halfBorderWidth);
  11028. return {
  11029. top: y.end,
  11030. right: x.end,
  11031. bottom: y.start,
  11032. left: x.start
  11033. };
  11034. }
  11035. function toClip(value) {
  11036. var t, r, b, l;
  11037. if (helpers$1.isObject(value)) {
  11038. t = value.top;
  11039. r = value.right;
  11040. b = value.bottom;
  11041. l = value.left;
  11042. } else {
  11043. t = r = b = l = value;
  11044. }
  11045. return {
  11046. top: t,
  11047. right: r,
  11048. bottom: b,
  11049. left: l
  11050. };
  11051. }
  11052. var controller_line = core_datasetController.extend({
  11053. datasetElementType: elements.Line,
  11054. dataElementType: elements.Point,
  11055. /**
  11056. * @private
  11057. */
  11058. _datasetElementOptions: [
  11059. 'backgroundColor',
  11060. 'borderCapStyle',
  11061. 'borderColor',
  11062. 'borderDash',
  11063. 'borderDashOffset',
  11064. 'borderJoinStyle',
  11065. 'borderWidth',
  11066. 'cubicInterpolationMode',
  11067. 'fill'
  11068. ],
  11069. /**
  11070. * @private
  11071. */
  11072. _dataElementOptions: {
  11073. backgroundColor: 'pointBackgroundColor',
  11074. borderColor: 'pointBorderColor',
  11075. borderWidth: 'pointBorderWidth',
  11076. hitRadius: 'pointHitRadius',
  11077. hoverBackgroundColor: 'pointHoverBackgroundColor',
  11078. hoverBorderColor: 'pointHoverBorderColor',
  11079. hoverBorderWidth: 'pointHoverBorderWidth',
  11080. hoverRadius: 'pointHoverRadius',
  11081. pointStyle: 'pointStyle',
  11082. radius: 'pointRadius',
  11083. rotation: 'pointRotation'
  11084. },
  11085. update: function(reset) {
  11086. var me = this;
  11087. var meta = me.getMeta();
  11088. var line = meta.dataset;
  11089. var points = meta.data || [];
  11090. var options = me.chart.options;
  11091. var config = me._config;
  11092. var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);
  11093. var i, ilen;
  11094. me._xScale = me.getScaleForId(meta.xAxisID);
  11095. me._yScale = me.getScaleForId(meta.yAxisID);
  11096. // Update Line
  11097. if (showLine) {
  11098. // Compatibility: If the properties are defined with only the old name, use those values
  11099. if (config.tension !== undefined && config.lineTension === undefined) {
  11100. config.lineTension = config.tension;
  11101. }
  11102. // Utility
  11103. line._scale = me._yScale;
  11104. line._datasetIndex = me.index;
  11105. // Data
  11106. line._children = points;
  11107. // Model
  11108. line._model = me._resolveDatasetElementOptions(line);
  11109. line.pivot();
  11110. }
  11111. // Update Points
  11112. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11113. me.updateElement(points[i], i, reset);
  11114. }
  11115. if (showLine && line._model.tension !== 0) {
  11116. me.updateBezierControlPoints();
  11117. }
  11118. // Now pivot the point for animation
  11119. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11120. points[i].pivot();
  11121. }
  11122. },
  11123. updateElement: function(point, index, reset) {
  11124. var me = this;
  11125. var meta = me.getMeta();
  11126. var custom = point.custom || {};
  11127. var dataset = me.getDataset();
  11128. var datasetIndex = me.index;
  11129. var value = dataset.data[index];
  11130. var xScale = me._xScale;
  11131. var yScale = me._yScale;
  11132. var lineModel = meta.dataset._model;
  11133. var x, y;
  11134. var options = me._resolveDataElementOptions(point, index);
  11135. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  11136. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  11137. // Utility
  11138. point._xScale = xScale;
  11139. point._yScale = yScale;
  11140. point._options = options;
  11141. point._datasetIndex = datasetIndex;
  11142. point._index = index;
  11143. // Desired view properties
  11144. point._model = {
  11145. x: x,
  11146. y: y,
  11147. skip: custom.skip || isNaN(x) || isNaN(y),
  11148. // Appearance
  11149. radius: options.radius,
  11150. pointStyle: options.pointStyle,
  11151. rotation: options.rotation,
  11152. backgroundColor: options.backgroundColor,
  11153. borderColor: options.borderColor,
  11154. borderWidth: options.borderWidth,
  11155. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  11156. steppedLine: lineModel ? lineModel.steppedLine : false,
  11157. // Tooltip
  11158. hitRadius: options.hitRadius
  11159. };
  11160. },
  11161. /**
  11162. * @private
  11163. */
  11164. _resolveDatasetElementOptions: function(element) {
  11165. var me = this;
  11166. var config = me._config;
  11167. var custom = element.custom || {};
  11168. var options = me.chart.options;
  11169. var lineOptions = options.elements.line;
  11170. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  11171. // The default behavior of lines is to break at null values, according
  11172. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  11173. // This option gives lines the ability to span gaps
  11174. values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps);
  11175. values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);
  11176. values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
  11177. values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
  11178. return values;
  11179. },
  11180. calculatePointY: function(value, index, datasetIndex) {
  11181. var me = this;
  11182. var chart = me.chart;
  11183. var yScale = me._yScale;
  11184. var sumPos = 0;
  11185. var sumNeg = 0;
  11186. var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
  11187. if (yScale.options.stacked) {
  11188. rightValue = +yScale.getRightValue(value);
  11189. metasets = chart._getSortedVisibleDatasetMetas();
  11190. ilen = metasets.length;
  11191. for (i = 0; i < ilen; ++i) {
  11192. dsMeta = metasets[i];
  11193. if (dsMeta.index === datasetIndex) {
  11194. break;
  11195. }
  11196. ds = chart.data.datasets[dsMeta.index];
  11197. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
  11198. stackedRightValue = +yScale.getRightValue(ds.data[index]);
  11199. if (stackedRightValue < 0) {
  11200. sumNeg += stackedRightValue || 0;
  11201. } else {
  11202. sumPos += stackedRightValue || 0;
  11203. }
  11204. }
  11205. }
  11206. if (rightValue < 0) {
  11207. return yScale.getPixelForValue(sumNeg + rightValue);
  11208. }
  11209. return yScale.getPixelForValue(sumPos + rightValue);
  11210. }
  11211. return yScale.getPixelForValue(value);
  11212. },
  11213. updateBezierControlPoints: function() {
  11214. var me = this;
  11215. var chart = me.chart;
  11216. var meta = me.getMeta();
  11217. var lineModel = meta.dataset._model;
  11218. var area = chart.chartArea;
  11219. var points = meta.data || [];
  11220. var i, ilen, model, controlPoints;
  11221. // Only consider points that are drawn in case the spanGaps option is used
  11222. if (lineModel.spanGaps) {
  11223. points = points.filter(function(pt) {
  11224. return !pt._model.skip;
  11225. });
  11226. }
  11227. function capControlPoint(pt, min, max) {
  11228. return Math.max(Math.min(pt, max), min);
  11229. }
  11230. if (lineModel.cubicInterpolationMode === 'monotone') {
  11231. helpers$1.splineCurveMonotone(points);
  11232. } else {
  11233. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11234. model = points[i]._model;
  11235. controlPoints = helpers$1.splineCurve(
  11236. helpers$1.previousItem(points, i)._model,
  11237. model,
  11238. helpers$1.nextItem(points, i)._model,
  11239. lineModel.tension
  11240. );
  11241. model.controlPointPreviousX = controlPoints.previous.x;
  11242. model.controlPointPreviousY = controlPoints.previous.y;
  11243. model.controlPointNextX = controlPoints.next.x;
  11244. model.controlPointNextY = controlPoints.next.y;
  11245. }
  11246. }
  11247. if (chart.options.elements.line.capBezierPoints) {
  11248. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11249. model = points[i]._model;
  11250. if (isPointInArea(model, area)) {
  11251. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  11252. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  11253. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  11254. }
  11255. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  11256. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  11257. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  11258. }
  11259. }
  11260. }
  11261. }
  11262. },
  11263. draw: function() {
  11264. var me = this;
  11265. var chart = me.chart;
  11266. var meta = me.getMeta();
  11267. var points = meta.data || [];
  11268. var area = chart.chartArea;
  11269. var canvas = chart.canvas;
  11270. var i = 0;
  11271. var ilen = points.length;
  11272. var clip;
  11273. if (me._showLine) {
  11274. clip = meta.dataset._model.clip;
  11275. helpers$1.canvas.clipArea(chart.ctx, {
  11276. left: clip.left === false ? 0 : area.left - clip.left,
  11277. right: clip.right === false ? canvas.width : area.right + clip.right,
  11278. top: clip.top === false ? 0 : area.top - clip.top,
  11279. bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
  11280. });
  11281. meta.dataset.draw();
  11282. helpers$1.canvas.unclipArea(chart.ctx);
  11283. }
  11284. // Draw the points
  11285. for (; i < ilen; ++i) {
  11286. points[i].draw(area);
  11287. }
  11288. },
  11289. /**
  11290. * @protected
  11291. */
  11292. setHoverStyle: function(point) {
  11293. var model = point._model;
  11294. var options = point._options;
  11295. var getHoverColor = helpers$1.getHoverColor;
  11296. point.$previousStyle = {
  11297. backgroundColor: model.backgroundColor,
  11298. borderColor: model.borderColor,
  11299. borderWidth: model.borderWidth,
  11300. radius: model.radius
  11301. };
  11302. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  11303. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  11304. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  11305. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  11306. },
  11307. });
  11308. var resolve$3 = helpers$1.options.resolve;
  11309. core_defaults._set('polarArea', {
  11310. scale: {
  11311. type: 'radialLinear',
  11312. angleLines: {
  11313. display: false
  11314. },
  11315. gridLines: {
  11316. circular: true
  11317. },
  11318. pointLabels: {
  11319. display: false
  11320. },
  11321. ticks: {
  11322. beginAtZero: true
  11323. }
  11324. },
  11325. // Boolean - Whether to animate the rotation of the chart
  11326. animation: {
  11327. animateRotate: true,
  11328. animateScale: true
  11329. },
  11330. startAngle: -0.5 * Math.PI,
  11331. legendCallback: function(chart) {
  11332. var list = document.createElement('ul');
  11333. var data = chart.data;
  11334. var datasets = data.datasets;
  11335. var labels = data.labels;
  11336. var i, ilen, listItem, listItemSpan;
  11337. list.setAttribute('class', chart.id + '-legend');
  11338. if (datasets.length) {
  11339. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  11340. listItem = list.appendChild(document.createElement('li'));
  11341. listItemSpan = listItem.appendChild(document.createElement('span'));
  11342. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  11343. if (labels[i]) {
  11344. listItem.appendChild(document.createTextNode(labels[i]));
  11345. }
  11346. }
  11347. }
  11348. return list.outerHTML;
  11349. },
  11350. legend: {
  11351. labels: {
  11352. generateLabels: function(chart) {
  11353. var data = chart.data;
  11354. if (data.labels.length && data.datasets.length) {
  11355. return data.labels.map(function(label, i) {
  11356. var meta = chart.getDatasetMeta(0);
  11357. var style = meta.controller.getStyle(i);
  11358. return {
  11359. text: label,
  11360. fillStyle: style.backgroundColor,
  11361. strokeStyle: style.borderColor,
  11362. lineWidth: style.borderWidth,
  11363. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  11364. // Extra data used for toggling the correct item
  11365. index: i
  11366. };
  11367. });
  11368. }
  11369. return [];
  11370. }
  11371. },
  11372. onClick: function(e, legendItem) {
  11373. var index = legendItem.index;
  11374. var chart = this.chart;
  11375. var i, ilen, meta;
  11376. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  11377. meta = chart.getDatasetMeta(i);
  11378. meta.data[index].hidden = !meta.data[index].hidden;
  11379. }
  11380. chart.update();
  11381. }
  11382. },
  11383. // Need to override these to give a nice default
  11384. tooltips: {
  11385. callbacks: {
  11386. title: function() {
  11387. return '';
  11388. },
  11389. label: function(item, data) {
  11390. return data.labels[item.index] + ': ' + item.yLabel;
  11391. }
  11392. }
  11393. }
  11394. });
  11395. var controller_polarArea = core_datasetController.extend({
  11396. dataElementType: elements.Arc,
  11397. linkScales: helpers$1.noop,
  11398. /**
  11399. * @private
  11400. */
  11401. _dataElementOptions: [
  11402. 'backgroundColor',
  11403. 'borderColor',
  11404. 'borderWidth',
  11405. 'borderAlign',
  11406. 'hoverBackgroundColor',
  11407. 'hoverBorderColor',
  11408. 'hoverBorderWidth',
  11409. ],
  11410. /**
  11411. * @private
  11412. */
  11413. _getIndexScaleId: function() {
  11414. return this.chart.scale.id;
  11415. },
  11416. /**
  11417. * @private
  11418. */
  11419. _getValueScaleId: function() {
  11420. return this.chart.scale.id;
  11421. },
  11422. update: function(reset) {
  11423. var me = this;
  11424. var dataset = me.getDataset();
  11425. var meta = me.getMeta();
  11426. var start = me.chart.options.startAngle || 0;
  11427. var starts = me._starts = [];
  11428. var angles = me._angles = [];
  11429. var arcs = meta.data;
  11430. var i, ilen, angle;
  11431. me._updateRadius();
  11432. meta.count = me.countVisibleElements();
  11433. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  11434. starts[i] = start;
  11435. angle = me._computeAngle(i);
  11436. angles[i] = angle;
  11437. start += angle;
  11438. }
  11439. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  11440. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  11441. me.updateElement(arcs[i], i, reset);
  11442. }
  11443. },
  11444. /**
  11445. * @private
  11446. */
  11447. _updateRadius: function() {
  11448. var me = this;
  11449. var chart = me.chart;
  11450. var chartArea = chart.chartArea;
  11451. var opts = chart.options;
  11452. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  11453. chart.outerRadius = Math.max(minSize / 2, 0);
  11454. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  11455. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  11456. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  11457. me.innerRadius = me.outerRadius - chart.radiusLength;
  11458. },
  11459. updateElement: function(arc, index, reset) {
  11460. var me = this;
  11461. var chart = me.chart;
  11462. var dataset = me.getDataset();
  11463. var opts = chart.options;
  11464. var animationOpts = opts.animation;
  11465. var scale = chart.scale;
  11466. var labels = chart.data.labels;
  11467. var centerX = scale.xCenter;
  11468. var centerY = scale.yCenter;
  11469. // var negHalfPI = -0.5 * Math.PI;
  11470. var datasetStartAngle = opts.startAngle;
  11471. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  11472. var startAngle = me._starts[index];
  11473. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  11474. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  11475. var options = arc._options || {};
  11476. helpers$1.extend(arc, {
  11477. // Utility
  11478. _datasetIndex: me.index,
  11479. _index: index,
  11480. _scale: scale,
  11481. // Desired view properties
  11482. _model: {
  11483. backgroundColor: options.backgroundColor,
  11484. borderColor: options.borderColor,
  11485. borderWidth: options.borderWidth,
  11486. borderAlign: options.borderAlign,
  11487. x: centerX,
  11488. y: centerY,
  11489. innerRadius: 0,
  11490. outerRadius: reset ? resetRadius : distance,
  11491. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  11492. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  11493. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  11494. }
  11495. });
  11496. arc.pivot();
  11497. },
  11498. countVisibleElements: function() {
  11499. var dataset = this.getDataset();
  11500. var meta = this.getMeta();
  11501. var count = 0;
  11502. helpers$1.each(meta.data, function(element, index) {
  11503. if (!isNaN(dataset.data[index]) && !element.hidden) {
  11504. count++;
  11505. }
  11506. });
  11507. return count;
  11508. },
  11509. /**
  11510. * @protected
  11511. */
  11512. setHoverStyle: function(arc) {
  11513. var model = arc._model;
  11514. var options = arc._options;
  11515. var getHoverColor = helpers$1.getHoverColor;
  11516. var valueOrDefault = helpers$1.valueOrDefault;
  11517. arc.$previousStyle = {
  11518. backgroundColor: model.backgroundColor,
  11519. borderColor: model.borderColor,
  11520. borderWidth: model.borderWidth,
  11521. };
  11522. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  11523. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  11524. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  11525. },
  11526. /**
  11527. * @private
  11528. */
  11529. _computeAngle: function(index) {
  11530. var me = this;
  11531. var count = this.getMeta().count;
  11532. var dataset = me.getDataset();
  11533. var meta = me.getMeta();
  11534. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  11535. return 0;
  11536. }
  11537. // Scriptable options
  11538. var context = {
  11539. chart: me.chart,
  11540. dataIndex: index,
  11541. dataset: dataset,
  11542. datasetIndex: me.index
  11543. };
  11544. return resolve$3([
  11545. me.chart.options.elements.arc.angle,
  11546. (2 * Math.PI) / count
  11547. ], context, index);
  11548. }
  11549. });
  11550. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  11551. core_defaults._set('pie', {
  11552. cutoutPercentage: 0
  11553. });
  11554. // Pie charts are Doughnut chart with different defaults
  11555. var controller_pie = controller_doughnut;
  11556. var valueOrDefault$7 = helpers$1.valueOrDefault;
  11557. core_defaults._set('radar', {
  11558. spanGaps: false,
  11559. scale: {
  11560. type: 'radialLinear'
  11561. },
  11562. elements: {
  11563. line: {
  11564. fill: 'start',
  11565. tension: 0 // no bezier in radar
  11566. }
  11567. }
  11568. });
  11569. var controller_radar = core_datasetController.extend({
  11570. datasetElementType: elements.Line,
  11571. dataElementType: elements.Point,
  11572. linkScales: helpers$1.noop,
  11573. /**
  11574. * @private
  11575. */
  11576. _datasetElementOptions: [
  11577. 'backgroundColor',
  11578. 'borderWidth',
  11579. 'borderColor',
  11580. 'borderCapStyle',
  11581. 'borderDash',
  11582. 'borderDashOffset',
  11583. 'borderJoinStyle',
  11584. 'fill'
  11585. ],
  11586. /**
  11587. * @private
  11588. */
  11589. _dataElementOptions: {
  11590. backgroundColor: 'pointBackgroundColor',
  11591. borderColor: 'pointBorderColor',
  11592. borderWidth: 'pointBorderWidth',
  11593. hitRadius: 'pointHitRadius',
  11594. hoverBackgroundColor: 'pointHoverBackgroundColor',
  11595. hoverBorderColor: 'pointHoverBorderColor',
  11596. hoverBorderWidth: 'pointHoverBorderWidth',
  11597. hoverRadius: 'pointHoverRadius',
  11598. pointStyle: 'pointStyle',
  11599. radius: 'pointRadius',
  11600. rotation: 'pointRotation'
  11601. },
  11602. /**
  11603. * @private
  11604. */
  11605. _getIndexScaleId: function() {
  11606. return this.chart.scale.id;
  11607. },
  11608. /**
  11609. * @private
  11610. */
  11611. _getValueScaleId: function() {
  11612. return this.chart.scale.id;
  11613. },
  11614. update: function(reset) {
  11615. var me = this;
  11616. var meta = me.getMeta();
  11617. var line = meta.dataset;
  11618. var points = meta.data || [];
  11619. var scale = me.chart.scale;
  11620. var config = me._config;
  11621. var i, ilen;
  11622. // Compatibility: If the properties are defined with only the old name, use those values
  11623. if (config.tension !== undefined && config.lineTension === undefined) {
  11624. config.lineTension = config.tension;
  11625. }
  11626. // Utility
  11627. line._scale = scale;
  11628. line._datasetIndex = me.index;
  11629. // Data
  11630. line._children = points;
  11631. line._loop = true;
  11632. // Model
  11633. line._model = me._resolveDatasetElementOptions(line);
  11634. line.pivot();
  11635. // Update Points
  11636. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11637. me.updateElement(points[i], i, reset);
  11638. }
  11639. // Update bezier control points
  11640. me.updateBezierControlPoints();
  11641. // Now pivot the point for animation
  11642. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11643. points[i].pivot();
  11644. }
  11645. },
  11646. updateElement: function(point, index, reset) {
  11647. var me = this;
  11648. var custom = point.custom || {};
  11649. var dataset = me.getDataset();
  11650. var scale = me.chart.scale;
  11651. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  11652. var options = me._resolveDataElementOptions(point, index);
  11653. var lineModel = me.getMeta().dataset._model;
  11654. var x = reset ? scale.xCenter : pointPosition.x;
  11655. var y = reset ? scale.yCenter : pointPosition.y;
  11656. // Utility
  11657. point._scale = scale;
  11658. point._options = options;
  11659. point._datasetIndex = me.index;
  11660. point._index = index;
  11661. // Desired view properties
  11662. point._model = {
  11663. x: x, // value not used in dataset scale, but we want a consistent API between scales
  11664. y: y,
  11665. skip: custom.skip || isNaN(x) || isNaN(y),
  11666. // Appearance
  11667. radius: options.radius,
  11668. pointStyle: options.pointStyle,
  11669. rotation: options.rotation,
  11670. backgroundColor: options.backgroundColor,
  11671. borderColor: options.borderColor,
  11672. borderWidth: options.borderWidth,
  11673. tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0),
  11674. // Tooltip
  11675. hitRadius: options.hitRadius
  11676. };
  11677. },
  11678. /**
  11679. * @private
  11680. */
  11681. _resolveDatasetElementOptions: function() {
  11682. var me = this;
  11683. var config = me._config;
  11684. var options = me.chart.options;
  11685. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  11686. values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);
  11687. values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);
  11688. return values;
  11689. },
  11690. updateBezierControlPoints: function() {
  11691. var me = this;
  11692. var meta = me.getMeta();
  11693. var area = me.chart.chartArea;
  11694. var points = meta.data || [];
  11695. var i, ilen, model, controlPoints;
  11696. // Only consider points that are drawn in case the spanGaps option is used
  11697. if (meta.dataset._model.spanGaps) {
  11698. points = points.filter(function(pt) {
  11699. return !pt._model.skip;
  11700. });
  11701. }
  11702. function capControlPoint(pt, min, max) {
  11703. return Math.max(Math.min(pt, max), min);
  11704. }
  11705. for (i = 0, ilen = points.length; i < ilen; ++i) {
  11706. model = points[i]._model;
  11707. controlPoints = helpers$1.splineCurve(
  11708. helpers$1.previousItem(points, i, true)._model,
  11709. model,
  11710. helpers$1.nextItem(points, i, true)._model,
  11711. model.tension
  11712. );
  11713. // Prevent the bezier going outside of the bounds of the graph
  11714. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  11715. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  11716. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  11717. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  11718. }
  11719. },
  11720. setHoverStyle: function(point) {
  11721. var model = point._model;
  11722. var options = point._options;
  11723. var getHoverColor = helpers$1.getHoverColor;
  11724. point.$previousStyle = {
  11725. backgroundColor: model.backgroundColor,
  11726. borderColor: model.borderColor,
  11727. borderWidth: model.borderWidth,
  11728. radius: model.radius
  11729. };
  11730. model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  11731. model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));
  11732. model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);
  11733. model.radius = valueOrDefault$7(options.hoverRadius, options.radius);
  11734. }
  11735. });
  11736. core_defaults._set('scatter', {
  11737. hover: {
  11738. mode: 'single'
  11739. },
  11740. scales: {
  11741. xAxes: [{
  11742. id: 'x-axis-1', // need an ID so datasets can reference the scale
  11743. type: 'linear', // scatter should not use a category axis
  11744. position: 'bottom'
  11745. }],
  11746. yAxes: [{
  11747. id: 'y-axis-1',
  11748. type: 'linear',
  11749. position: 'left'
  11750. }]
  11751. },
  11752. tooltips: {
  11753. callbacks: {
  11754. title: function() {
  11755. return ''; // doesn't make sense for scatter since data are formatted as a point
  11756. },
  11757. label: function(item) {
  11758. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  11759. }
  11760. }
  11761. }
  11762. });
  11763. core_defaults._set('global', {
  11764. datasets: {
  11765. scatter: {
  11766. showLine: false
  11767. }
  11768. }
  11769. });
  11770. // Scatter charts use line controllers
  11771. var controller_scatter = controller_line;
  11772. // NOTE export a map in which the key represents the controller type, not
  11773. // the class, and so must be CamelCase in order to be correctly retrieved
  11774. // by the controller in core.controller.js (`controllers[meta.type]`).
  11775. var controllers = {
  11776. bar: controller_bar,
  11777. bubble: controller_bubble,
  11778. doughnut: controller_doughnut,
  11779. horizontalBar: controller_horizontalBar,
  11780. line: controller_line,
  11781. polarArea: controller_polarArea,
  11782. pie: controller_pie,
  11783. radar: controller_radar,
  11784. scatter: controller_scatter
  11785. };
  11786. /**
  11787. * Helper function to get relative position for an event
  11788. * @param {Event|IEvent} event - The event to get the position for
  11789. * @param {Chart} chart - The chart
  11790. * @returns {object} the event position
  11791. */
  11792. function getRelativePosition(e, chart) {
  11793. if (e.native) {
  11794. return {
  11795. x: e.x,
  11796. y: e.y
  11797. };
  11798. }
  11799. return helpers$1.getRelativePosition(e, chart);
  11800. }
  11801. /**
  11802. * Helper function to traverse all of the visible elements in the chart
  11803. * @param {Chart} chart - the chart
  11804. * @param {function} handler - the callback to execute for each visible item
  11805. */
  11806. function parseVisibleItems(chart, handler) {
  11807. var metasets = chart._getSortedVisibleDatasetMetas();
  11808. var metadata, i, j, ilen, jlen, element;
  11809. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  11810. metadata = metasets[i].data;
  11811. for (j = 0, jlen = metadata.length; j < jlen; ++j) {
  11812. element = metadata[j];
  11813. if (!element._view.skip) {
  11814. handler(element);
  11815. }
  11816. }
  11817. }
  11818. }
  11819. /**
  11820. * Helper function to get the items that intersect the event position
  11821. * @param {ChartElement[]} items - elements to filter
  11822. * @param {object} position - the point to be nearest to
  11823. * @return {ChartElement[]} the nearest items
  11824. */
  11825. function getIntersectItems(chart, position) {
  11826. var elements = [];
  11827. parseVisibleItems(chart, function(element) {
  11828. if (element.inRange(position.x, position.y)) {
  11829. elements.push(element);
  11830. }
  11831. });
  11832. return elements;
  11833. }
  11834. /**
  11835. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  11836. * @param {Chart} chart - the chart to look at elements from
  11837. * @param {object} position - the point to be nearest to
  11838. * @param {boolean} intersect - if true, only consider items that intersect the position
  11839. * @param {function} distanceMetric - function to provide the distance between points
  11840. * @return {ChartElement[]} the nearest items
  11841. */
  11842. function getNearestItems(chart, position, intersect, distanceMetric) {
  11843. var minDistance = Number.POSITIVE_INFINITY;
  11844. var nearestItems = [];
  11845. parseVisibleItems(chart, function(element) {
  11846. if (intersect && !element.inRange(position.x, position.y)) {
  11847. return;
  11848. }
  11849. var center = element.getCenterPoint();
  11850. var distance = distanceMetric(position, center);
  11851. if (distance < minDistance) {
  11852. nearestItems = [element];
  11853. minDistance = distance;
  11854. } else if (distance === minDistance) {
  11855. // Can have multiple items at the same distance in which case we sort by size
  11856. nearestItems.push(element);
  11857. }
  11858. });
  11859. return nearestItems;
  11860. }
  11861. /**
  11862. * Get a distance metric function for two points based on the
  11863. * axis mode setting
  11864. * @param {string} axis - the axis mode. x|y|xy
  11865. */
  11866. function getDistanceMetricForAxis(axis) {
  11867. var useX = axis.indexOf('x') !== -1;
  11868. var useY = axis.indexOf('y') !== -1;
  11869. return function(pt1, pt2) {
  11870. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  11871. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  11872. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  11873. };
  11874. }
  11875. function indexMode(chart, e, options) {
  11876. var position = getRelativePosition(e, chart);
  11877. // Default axis for index mode is 'x' to match old behaviour
  11878. options.axis = options.axis || 'x';
  11879. var distanceMetric = getDistanceMetricForAxis(options.axis);
  11880. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  11881. var elements = [];
  11882. if (!items.length) {
  11883. return [];
  11884. }
  11885. chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
  11886. var element = meta.data[items[0]._index];
  11887. // don't count items that are skipped (null data)
  11888. if (element && !element._view.skip) {
  11889. elements.push(element);
  11890. }
  11891. });
  11892. return elements;
  11893. }
  11894. /**
  11895. * @interface IInteractionOptions
  11896. */
  11897. /**
  11898. * If true, only consider items that intersect the point
  11899. * @name IInterfaceOptions#boolean
  11900. * @type Boolean
  11901. */
  11902. /**
  11903. * Contains interaction related functions
  11904. * @namespace Chart.Interaction
  11905. */
  11906. var core_interaction = {
  11907. // Helper function for different modes
  11908. modes: {
  11909. single: function(chart, e) {
  11910. var position = getRelativePosition(e, chart);
  11911. var elements = [];
  11912. parseVisibleItems(chart, function(element) {
  11913. if (element.inRange(position.x, position.y)) {
  11914. elements.push(element);
  11915. return elements;
  11916. }
  11917. });
  11918. return elements.slice(0, 1);
  11919. },
  11920. /**
  11921. * @function Chart.Interaction.modes.label
  11922. * @deprecated since version 2.4.0
  11923. * @todo remove at version 3
  11924. * @private
  11925. */
  11926. label: indexMode,
  11927. /**
  11928. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  11929. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  11930. * @function Chart.Interaction.modes.index
  11931. * @since v2.4.0
  11932. * @param {Chart} chart - the chart we are returning items from
  11933. * @param {Event} e - the event we are find things at
  11934. * @param {IInteractionOptions} options - options to use during interaction
  11935. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11936. */
  11937. index: indexMode,
  11938. /**
  11939. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  11940. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  11941. * @function Chart.Interaction.modes.dataset
  11942. * @param {Chart} chart - the chart we are returning items from
  11943. * @param {Event} e - the event we are find things at
  11944. * @param {IInteractionOptions} options - options to use during interaction
  11945. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11946. */
  11947. dataset: function(chart, e, options) {
  11948. var position = getRelativePosition(e, chart);
  11949. options.axis = options.axis || 'xy';
  11950. var distanceMetric = getDistanceMetricForAxis(options.axis);
  11951. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  11952. if (items.length > 0) {
  11953. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  11954. }
  11955. return items;
  11956. },
  11957. /**
  11958. * @function Chart.Interaction.modes.x-axis
  11959. * @deprecated since version 2.4.0. Use index mode and intersect == true
  11960. * @todo remove at version 3
  11961. * @private
  11962. */
  11963. 'x-axis': function(chart, e) {
  11964. return indexMode(chart, e, {intersect: false});
  11965. },
  11966. /**
  11967. * Point mode returns all elements that hit test based on the event position
  11968. * of the event
  11969. * @function Chart.Interaction.modes.intersect
  11970. * @param {Chart} chart - the chart we are returning items from
  11971. * @param {Event} e - the event we are find things at
  11972. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11973. */
  11974. point: function(chart, e) {
  11975. var position = getRelativePosition(e, chart);
  11976. return getIntersectItems(chart, position);
  11977. },
  11978. /**
  11979. * nearest mode returns the element closest to the point
  11980. * @function Chart.Interaction.modes.intersect
  11981. * @param {Chart} chart - the chart we are returning items from
  11982. * @param {Event} e - the event we are find things at
  11983. * @param {IInteractionOptions} options - options to use
  11984. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11985. */
  11986. nearest: function(chart, e, options) {
  11987. var position = getRelativePosition(e, chart);
  11988. options.axis = options.axis || 'xy';
  11989. var distanceMetric = getDistanceMetricForAxis(options.axis);
  11990. return getNearestItems(chart, position, options.intersect, distanceMetric);
  11991. },
  11992. /**
  11993. * x mode returns the elements that hit-test at the current x coordinate
  11994. * @function Chart.Interaction.modes.x
  11995. * @param {Chart} chart - the chart we are returning items from
  11996. * @param {Event} e - the event we are find things at
  11997. * @param {IInteractionOptions} options - options to use
  11998. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  11999. */
  12000. x: function(chart, e, options) {
  12001. var position = getRelativePosition(e, chart);
  12002. var items = [];
  12003. var intersectsItem = false;
  12004. parseVisibleItems(chart, function(element) {
  12005. if (element.inXRange(position.x)) {
  12006. items.push(element);
  12007. }
  12008. if (element.inRange(position.x, position.y)) {
  12009. intersectsItem = true;
  12010. }
  12011. });
  12012. // If we want to trigger on an intersect and we don't have any items
  12013. // that intersect the position, return nothing
  12014. if (options.intersect && !intersectsItem) {
  12015. items = [];
  12016. }
  12017. return items;
  12018. },
  12019. /**
  12020. * y mode returns the elements that hit-test at the current y coordinate
  12021. * @function Chart.Interaction.modes.y
  12022. * @param {Chart} chart - the chart we are returning items from
  12023. * @param {Event} e - the event we are find things at
  12024. * @param {IInteractionOptions} options - options to use
  12025. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  12026. */
  12027. y: function(chart, e, options) {
  12028. var position = getRelativePosition(e, chart);
  12029. var items = [];
  12030. var intersectsItem = false;
  12031. parseVisibleItems(chart, function(element) {
  12032. if (element.inYRange(position.y)) {
  12033. items.push(element);
  12034. }
  12035. if (element.inRange(position.x, position.y)) {
  12036. intersectsItem = true;
  12037. }
  12038. });
  12039. // If we want to trigger on an intersect and we don't have any items
  12040. // that intersect the position, return nothing
  12041. if (options.intersect && !intersectsItem) {
  12042. items = [];
  12043. }
  12044. return items;
  12045. }
  12046. }
  12047. };
  12048. var extend = helpers$1.extend;
  12049. function filterByPosition(array, position) {
  12050. return helpers$1.where(array, function(v) {
  12051. return v.pos === position;
  12052. });
  12053. }
  12054. function sortByWeight(array, reverse) {
  12055. return array.sort(function(a, b) {
  12056. var v0 = reverse ? b : a;
  12057. var v1 = reverse ? a : b;
  12058. return v0.weight === v1.weight ?
  12059. v0.index - v1.index :
  12060. v0.weight - v1.weight;
  12061. });
  12062. }
  12063. function wrapBoxes(boxes) {
  12064. var layoutBoxes = [];
  12065. var i, ilen, box;
  12066. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  12067. box = boxes[i];
  12068. layoutBoxes.push({
  12069. index: i,
  12070. box: box,
  12071. pos: box.position,
  12072. horizontal: box.isHorizontal(),
  12073. weight: box.weight
  12074. });
  12075. }
  12076. return layoutBoxes;
  12077. }
  12078. function setLayoutDims(layouts, params) {
  12079. var i, ilen, layout;
  12080. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  12081. layout = layouts[i];
  12082. // store width used instead of chartArea.w in fitBoxes
  12083. layout.width = layout.horizontal
  12084. ? layout.box.fullWidth && params.availableWidth
  12085. : params.vBoxMaxWidth;
  12086. // store height used instead of chartArea.h in fitBoxes
  12087. layout.height = layout.horizontal && params.hBoxMaxHeight;
  12088. }
  12089. }
  12090. function buildLayoutBoxes(boxes) {
  12091. var layoutBoxes = wrapBoxes(boxes);
  12092. var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  12093. var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  12094. var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  12095. var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  12096. return {
  12097. leftAndTop: left.concat(top),
  12098. rightAndBottom: right.concat(bottom),
  12099. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  12100. vertical: left.concat(right),
  12101. horizontal: top.concat(bottom)
  12102. };
  12103. }
  12104. function getCombinedMax(maxPadding, chartArea, a, b) {
  12105. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  12106. }
  12107. function updateDims(chartArea, params, layout) {
  12108. var box = layout.box;
  12109. var maxPadding = chartArea.maxPadding;
  12110. var newWidth, newHeight;
  12111. if (layout.size) {
  12112. // this layout was already counted for, lets first reduce old size
  12113. chartArea[layout.pos] -= layout.size;
  12114. }
  12115. layout.size = layout.horizontal ? box.height : box.width;
  12116. chartArea[layout.pos] += layout.size;
  12117. if (box.getPadding) {
  12118. var boxPadding = box.getPadding();
  12119. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  12120. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  12121. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  12122. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  12123. }
  12124. newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
  12125. newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
  12126. if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
  12127. chartArea.w = newWidth;
  12128. chartArea.h = newHeight;
  12129. // return true if chart area changed in layout's direction
  12130. var sizes = layout.horizontal ? [newWidth, chartArea.w] : [newHeight, chartArea.h];
  12131. return sizes[0] !== sizes[1] && (!isNaN(sizes[0]) || !isNaN(sizes[1]));
  12132. }
  12133. }
  12134. function handleMaxPadding(chartArea) {
  12135. var maxPadding = chartArea.maxPadding;
  12136. function updatePos(pos) {
  12137. var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  12138. chartArea[pos] += change;
  12139. return change;
  12140. }
  12141. chartArea.y += updatePos('top');
  12142. chartArea.x += updatePos('left');
  12143. updatePos('right');
  12144. updatePos('bottom');
  12145. }
  12146. function getMargins(horizontal, chartArea) {
  12147. var maxPadding = chartArea.maxPadding;
  12148. function marginForPositions(positions) {
  12149. var margin = {left: 0, top: 0, right: 0, bottom: 0};
  12150. positions.forEach(function(pos) {
  12151. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  12152. });
  12153. return margin;
  12154. }
  12155. return horizontal
  12156. ? marginForPositions(['left', 'right'])
  12157. : marginForPositions(['top', 'bottom']);
  12158. }
  12159. function fitBoxes(boxes, chartArea, params) {
  12160. var refitBoxes = [];
  12161. var i, ilen, layout, box, refit, changed;
  12162. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  12163. layout = boxes[i];
  12164. box = layout.box;
  12165. box.update(
  12166. layout.width || chartArea.w,
  12167. layout.height || chartArea.h,
  12168. getMargins(layout.horizontal, chartArea)
  12169. );
  12170. if (updateDims(chartArea, params, layout)) {
  12171. changed = true;
  12172. if (refitBoxes.length) {
  12173. // Dimensions changed and there were non full width boxes before this
  12174. // -> we have to refit those
  12175. refit = true;
  12176. }
  12177. }
  12178. if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case
  12179. refitBoxes.push(layout);
  12180. }
  12181. }
  12182. return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;
  12183. }
  12184. function placeBoxes(boxes, chartArea, params) {
  12185. var userPadding = params.padding;
  12186. var x = chartArea.x;
  12187. var y = chartArea.y;
  12188. var i, ilen, layout, box;
  12189. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  12190. layout = boxes[i];
  12191. box = layout.box;
  12192. if (layout.horizontal) {
  12193. box.left = box.fullWidth ? userPadding.left : chartArea.left;
  12194. box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  12195. box.top = y;
  12196. box.bottom = y + box.height;
  12197. box.width = box.right - box.left;
  12198. y = box.bottom;
  12199. } else {
  12200. box.left = x;
  12201. box.right = x + box.width;
  12202. box.top = chartArea.top;
  12203. box.bottom = chartArea.top + chartArea.h;
  12204. box.height = box.bottom - box.top;
  12205. x = box.right;
  12206. }
  12207. }
  12208. chartArea.x = x;
  12209. chartArea.y = y;
  12210. }
  12211. core_defaults._set('global', {
  12212. layout: {
  12213. padding: {
  12214. top: 0,
  12215. right: 0,
  12216. bottom: 0,
  12217. left: 0
  12218. }
  12219. }
  12220. });
  12221. /**
  12222. * @interface ILayoutItem
  12223. * @prop {string} position - The position of the item in the chart layout. Possible values are
  12224. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  12225. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  12226. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  12227. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  12228. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  12229. * @prop {function} getPadding - Returns an object with padding on the edges
  12230. * @prop {number} width - Width of item. Must be valid after update()
  12231. * @prop {number} height - Height of item. Must be valid after update()
  12232. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  12233. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  12234. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  12235. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  12236. */
  12237. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  12238. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  12239. // It is this service's responsibility of carrying out that layout.
  12240. var core_layouts = {
  12241. defaults: {},
  12242. /**
  12243. * Register a box to a chart.
  12244. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  12245. * @param {Chart} chart - the chart to use
  12246. * @param {ILayoutItem} item - the item to add to be layed out
  12247. */
  12248. addBox: function(chart, item) {
  12249. if (!chart.boxes) {
  12250. chart.boxes = [];
  12251. }
  12252. // initialize item with default values
  12253. item.fullWidth = item.fullWidth || false;
  12254. item.position = item.position || 'top';
  12255. item.weight = item.weight || 0;
  12256. item._layers = item._layers || function() {
  12257. return [{
  12258. z: 0,
  12259. draw: function() {
  12260. item.draw.apply(item, arguments);
  12261. }
  12262. }];
  12263. };
  12264. chart.boxes.push(item);
  12265. },
  12266. /**
  12267. * Remove a layoutItem from a chart
  12268. * @param {Chart} chart - the chart to remove the box from
  12269. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  12270. */
  12271. removeBox: function(chart, layoutItem) {
  12272. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  12273. if (index !== -1) {
  12274. chart.boxes.splice(index, 1);
  12275. }
  12276. },
  12277. /**
  12278. * Sets (or updates) options on the given `item`.
  12279. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  12280. * @param {ILayoutItem} item - the item to configure with the given options
  12281. * @param {object} options - the new item options.
  12282. */
  12283. configure: function(chart, item, options) {
  12284. var props = ['fullWidth', 'position', 'weight'];
  12285. var ilen = props.length;
  12286. var i = 0;
  12287. var prop;
  12288. for (; i < ilen; ++i) {
  12289. prop = props[i];
  12290. if (options.hasOwnProperty(prop)) {
  12291. item[prop] = options[prop];
  12292. }
  12293. }
  12294. },
  12295. /**
  12296. * Fits boxes of the given chart into the given size by having each box measure itself
  12297. * then running a fitting algorithm
  12298. * @param {Chart} chart - the chart
  12299. * @param {number} width - the width to fit into
  12300. * @param {number} height - the height to fit into
  12301. */
  12302. update: function(chart, width, height) {
  12303. if (!chart) {
  12304. return;
  12305. }
  12306. var layoutOptions = chart.options.layout || {};
  12307. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  12308. var availableWidth = width - padding.width;
  12309. var availableHeight = height - padding.height;
  12310. var boxes = buildLayoutBoxes(chart.boxes);
  12311. var verticalBoxes = boxes.vertical;
  12312. var horizontalBoxes = boxes.horizontal;
  12313. // Essentially we now have any number of boxes on each of the 4 sides.
  12314. // Our canvas looks like the following.
  12315. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  12316. // B1 is the bottom axis
  12317. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  12318. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  12319. // an error will be thrown.
  12320. //
  12321. // |----------------------------------------------------|
  12322. // | T1 (Full Width) |
  12323. // |----------------------------------------------------|
  12324. // | | | T2 | |
  12325. // | |----|-------------------------------------|----|
  12326. // | | | C1 | | C2 | |
  12327. // | | |----| |----| |
  12328. // | | | | |
  12329. // | L1 | L2 | ChartArea (C0) | R1 |
  12330. // | | | | |
  12331. // | | |----| |----| |
  12332. // | | | C3 | | C4 | |
  12333. // | |----|-------------------------------------|----|
  12334. // | | | B1 | |
  12335. // |----------------------------------------------------|
  12336. // | B2 (Full Width) |
  12337. // |----------------------------------------------------|
  12338. //
  12339. var params = Object.freeze({
  12340. outerWidth: width,
  12341. outerHeight: height,
  12342. padding: padding,
  12343. availableWidth: availableWidth,
  12344. vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
  12345. hBoxMaxHeight: availableHeight / 2
  12346. });
  12347. var chartArea = extend({
  12348. maxPadding: extend({}, padding),
  12349. w: availableWidth,
  12350. h: availableHeight,
  12351. x: padding.left,
  12352. y: padding.top
  12353. }, padding);
  12354. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  12355. // First fit vertical boxes
  12356. fitBoxes(verticalBoxes, chartArea, params);
  12357. // Then fit horizontal boxes
  12358. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  12359. // if the area changed, re-fit vertical boxes
  12360. fitBoxes(verticalBoxes, chartArea, params);
  12361. }
  12362. handleMaxPadding(chartArea);
  12363. // Finally place the boxes to correct coordinates
  12364. placeBoxes(boxes.leftAndTop, chartArea, params);
  12365. // Move to opposite side of chart
  12366. chartArea.x += chartArea.w;
  12367. chartArea.y += chartArea.h;
  12368. placeBoxes(boxes.rightAndBottom, chartArea, params);
  12369. chart.chartArea = {
  12370. left: chartArea.left,
  12371. top: chartArea.top,
  12372. right: chartArea.left + chartArea.w,
  12373. bottom: chartArea.top + chartArea.h
  12374. };
  12375. // Finally update boxes in chartArea (radial scale for example)
  12376. helpers$1.each(boxes.chartArea, function(layout) {
  12377. var box = layout.box;
  12378. extend(box, chart.chartArea);
  12379. box.update(chartArea.w, chartArea.h);
  12380. });
  12381. }
  12382. };
  12383. /**
  12384. * Platform fallback implementation (minimal).
  12385. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  12386. */
  12387. var platform_basic = {
  12388. acquireContext: function(item) {
  12389. if (item && item.canvas) {
  12390. // Support for any object associated to a canvas (including a context2d)
  12391. item = item.canvas;
  12392. }
  12393. return item && item.getContext('2d') || null;
  12394. }
  12395. };
  12396. 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";
  12397. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  12398. __proto__: null,
  12399. 'default': platform_dom
  12400. });
  12401. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  12402. var EXPANDO_KEY = '$chartjs';
  12403. var CSS_PREFIX = 'chartjs-';
  12404. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  12405. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  12406. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  12407. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  12408. /**
  12409. * DOM event types -> Chart.js event types.
  12410. * Note: only events with different types are mapped.
  12411. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  12412. */
  12413. var EVENT_TYPES = {
  12414. touchstart: 'mousedown',
  12415. touchmove: 'mousemove',
  12416. touchend: 'mouseup',
  12417. pointerenter: 'mouseenter',
  12418. pointerdown: 'mousedown',
  12419. pointermove: 'mousemove',
  12420. pointerup: 'mouseup',
  12421. pointerleave: 'mouseout',
  12422. pointerout: 'mouseout'
  12423. };
  12424. /**
  12425. * The "used" size is the final value of a dimension property after all calculations have
  12426. * been performed. This method uses the computed style of `element` but returns undefined
  12427. * if the computed style is not expressed in pixels. That can happen in some cases where
  12428. * `element` has a size relative to its parent and this last one is not yet displayed,
  12429. * for example because of `display: none` on a parent node.
  12430. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  12431. * @returns {number} Size in pixels or undefined if unknown.
  12432. */
  12433. function readUsedSize(element, property) {
  12434. var value = helpers$1.getStyle(element, property);
  12435. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  12436. return matches ? Number(matches[1]) : undefined;
  12437. }
  12438. /**
  12439. * Initializes the canvas style and render size without modifying the canvas display size,
  12440. * since responsiveness is handled by the controller.resize() method. The config is used
  12441. * to determine the aspect ratio to apply in case no explicit height has been specified.
  12442. */
  12443. function initCanvas(canvas, config) {
  12444. var style = canvas.style;
  12445. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  12446. // returns null or '' if no explicit value has been set to the canvas attribute.
  12447. var renderHeight = canvas.getAttribute('height');
  12448. var renderWidth = canvas.getAttribute('width');
  12449. // Chart.js modifies some canvas values that we want to restore on destroy
  12450. canvas[EXPANDO_KEY] = {
  12451. initial: {
  12452. height: renderHeight,
  12453. width: renderWidth,
  12454. style: {
  12455. display: style.display,
  12456. height: style.height,
  12457. width: style.width
  12458. }
  12459. }
  12460. };
  12461. // Force canvas to display as block to avoid extra space caused by inline
  12462. // elements, which would interfere with the responsive resize process.
  12463. // https://github.com/chartjs/Chart.js/issues/2538
  12464. style.display = style.display || 'block';
  12465. if (renderWidth === null || renderWidth === '') {
  12466. var displayWidth = readUsedSize(canvas, 'width');
  12467. if (displayWidth !== undefined) {
  12468. canvas.width = displayWidth;
  12469. }
  12470. }
  12471. if (renderHeight === null || renderHeight === '') {
  12472. if (canvas.style.height === '') {
  12473. // If no explicit render height and style height, let's apply the aspect ratio,
  12474. // which one can be specified by the user but also by charts as default option
  12475. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  12476. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  12477. } else {
  12478. var displayHeight = readUsedSize(canvas, 'height');
  12479. if (displayWidth !== undefined) {
  12480. canvas.height = displayHeight;
  12481. }
  12482. }
  12483. }
  12484. return canvas;
  12485. }
  12486. /**
  12487. * Detects support for options object argument in addEventListener.
  12488. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  12489. * @private
  12490. */
  12491. var supportsEventListenerOptions = (function() {
  12492. var supports = false;
  12493. try {
  12494. var options = Object.defineProperty({}, 'passive', {
  12495. // eslint-disable-next-line getter-return
  12496. get: function() {
  12497. supports = true;
  12498. }
  12499. });
  12500. window.addEventListener('e', null, options);
  12501. } catch (e) {
  12502. // continue regardless of error
  12503. }
  12504. return supports;
  12505. }());
  12506. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  12507. // https://github.com/chartjs/Chart.js/issues/4287
  12508. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  12509. function addListener(node, type, listener) {
  12510. node.addEventListener(type, listener, eventListenerOptions);
  12511. }
  12512. function removeListener(node, type, listener) {
  12513. node.removeEventListener(type, listener, eventListenerOptions);
  12514. }
  12515. function createEvent(type, chart, x, y, nativeEvent) {
  12516. return {
  12517. type: type,
  12518. chart: chart,
  12519. native: nativeEvent || null,
  12520. x: x !== undefined ? x : null,
  12521. y: y !== undefined ? y : null,
  12522. };
  12523. }
  12524. function fromNativeEvent(event, chart) {
  12525. var type = EVENT_TYPES[event.type] || event.type;
  12526. var pos = helpers$1.getRelativePosition(event, chart);
  12527. return createEvent(type, chart, pos.x, pos.y, event);
  12528. }
  12529. function throttled(fn, thisArg) {
  12530. var ticking = false;
  12531. var args = [];
  12532. return function() {
  12533. args = Array.prototype.slice.call(arguments);
  12534. thisArg = thisArg || this;
  12535. if (!ticking) {
  12536. ticking = true;
  12537. helpers$1.requestAnimFrame.call(window, function() {
  12538. ticking = false;
  12539. fn.apply(thisArg, args);
  12540. });
  12541. }
  12542. };
  12543. }
  12544. function createDiv(cls) {
  12545. var el = document.createElement('div');
  12546. el.className = cls || '';
  12547. return el;
  12548. }
  12549. // Implementation based on https://github.com/marcj/css-element-queries
  12550. function createResizer(handler) {
  12551. var maxSize = 1000000;
  12552. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  12553. // https://github.com/chartjs/Chart.js/issues/5902
  12554. var resizer = createDiv(CSS_SIZE_MONITOR);
  12555. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  12556. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  12557. expand.appendChild(createDiv());
  12558. shrink.appendChild(createDiv());
  12559. resizer.appendChild(expand);
  12560. resizer.appendChild(shrink);
  12561. resizer._reset = function() {
  12562. expand.scrollLeft = maxSize;
  12563. expand.scrollTop = maxSize;
  12564. shrink.scrollLeft = maxSize;
  12565. shrink.scrollTop = maxSize;
  12566. };
  12567. var onScroll = function() {
  12568. resizer._reset();
  12569. handler();
  12570. };
  12571. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  12572. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  12573. return resizer;
  12574. }
  12575. // https://davidwalsh.name/detect-node-insertion
  12576. function watchForRender(node, handler) {
  12577. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  12578. var proxy = expando.renderProxy = function(e) {
  12579. if (e.animationName === CSS_RENDER_ANIMATION) {
  12580. handler();
  12581. }
  12582. };
  12583. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  12584. addListener(node, type, proxy);
  12585. });
  12586. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  12587. // is removed then added back immediately (same animation frame?). Accessing the
  12588. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  12589. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  12590. // https://github.com/chartjs/Chart.js/issues/4737
  12591. expando.reflow = !!node.offsetParent;
  12592. node.classList.add(CSS_RENDER_MONITOR);
  12593. }
  12594. function unwatchForRender(node) {
  12595. var expando = node[EXPANDO_KEY] || {};
  12596. var proxy = expando.renderProxy;
  12597. if (proxy) {
  12598. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  12599. removeListener(node, type, proxy);
  12600. });
  12601. delete expando.renderProxy;
  12602. }
  12603. node.classList.remove(CSS_RENDER_MONITOR);
  12604. }
  12605. function addResizeListener(node, listener, chart) {
  12606. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  12607. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  12608. var resizer = expando.resizer = createResizer(throttled(function() {
  12609. if (expando.resizer) {
  12610. var container = chart.options.maintainAspectRatio && node.parentNode;
  12611. var w = container ? container.clientWidth : 0;
  12612. listener(createEvent('resize', chart));
  12613. if (container && container.clientWidth < w && chart.canvas) {
  12614. // If the container size shrank during chart resize, let's assume
  12615. // scrollbar appeared. So we resize again with the scrollbar visible -
  12616. // effectively making chart smaller and the scrollbar hidden again.
  12617. // Because we are inside `throttled`, and currently `ticking`, scroll
  12618. // events are ignored during this whole 2 resize process.
  12619. // If we assumed wrong and something else happened, we are resizing
  12620. // twice in a frame (potential performance issue)
  12621. listener(createEvent('resize', chart));
  12622. }
  12623. }
  12624. }));
  12625. // The resizer needs to be attached to the node parent, so we first need to be
  12626. // sure that `node` is attached to the DOM before injecting the resizer element.
  12627. watchForRender(node, function() {
  12628. if (expando.resizer) {
  12629. var container = node.parentNode;
  12630. if (container && container !== resizer.parentNode) {
  12631. container.insertBefore(resizer, container.firstChild);
  12632. }
  12633. // The container size might have changed, let's reset the resizer state.
  12634. resizer._reset();
  12635. }
  12636. });
  12637. }
  12638. function removeResizeListener(node) {
  12639. var expando = node[EXPANDO_KEY] || {};
  12640. var resizer = expando.resizer;
  12641. delete expando.resizer;
  12642. unwatchForRender(node);
  12643. if (resizer && resizer.parentNode) {
  12644. resizer.parentNode.removeChild(resizer);
  12645. }
  12646. }
  12647. /**
  12648. * Injects CSS styles inline if the styles are not already present.
  12649. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.
  12650. * @param {string} css - the CSS to be injected.
  12651. */
  12652. function injectCSS(rootNode, css) {
  12653. // https://stackoverflow.com/q/3922139
  12654. var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});
  12655. if (!expando.containsStyles) {
  12656. expando.containsStyles = true;
  12657. css = '/* Chart.js */\n' + css;
  12658. var style = document.createElement('style');
  12659. style.setAttribute('type', 'text/css');
  12660. style.appendChild(document.createTextNode(css));
  12661. rootNode.appendChild(style);
  12662. }
  12663. }
  12664. var platform_dom$2 = {
  12665. /**
  12666. * When `true`, prevents the automatic injection of the stylesheet required to
  12667. * correctly detect when the chart is added to the DOM and then resized. This
  12668. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  12669. * to be manually imported to make this library compatible with any CSP.
  12670. * See https://github.com/chartjs/Chart.js/issues/5208
  12671. */
  12672. disableCSSInjection: false,
  12673. /**
  12674. * This property holds whether this platform is enabled for the current environment.
  12675. * Currently used by platform.js to select the proper implementation.
  12676. * @private
  12677. */
  12678. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  12679. /**
  12680. * Initializes resources that depend on platform options.
  12681. * @param {HTMLCanvasElement} canvas - The Canvas element.
  12682. * @private
  12683. */
  12684. _ensureLoaded: function(canvas) {
  12685. if (!this.disableCSSInjection) {
  12686. // If the canvas is in a shadow DOM, then the styles must also be inserted
  12687. // into the same shadow DOM.
  12688. // https://github.com/chartjs/Chart.js/issues/5763
  12689. var root = canvas.getRootNode ? canvas.getRootNode() : document;
  12690. var targetNode = root.host ? root : document.head;
  12691. injectCSS(targetNode, stylesheet);
  12692. }
  12693. },
  12694. acquireContext: function(item, config) {
  12695. if (typeof item === 'string') {
  12696. item = document.getElementById(item);
  12697. } else if (item.length) {
  12698. // Support for array based queries (such as jQuery)
  12699. item = item[0];
  12700. }
  12701. if (item && item.canvas) {
  12702. // Support for any object associated to a canvas (including a context2d)
  12703. item = item.canvas;
  12704. }
  12705. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  12706. // method, for example: https://github.com/kkapsner/CanvasBlocker
  12707. // https://github.com/chartjs/Chart.js/issues/2807
  12708. var context = item && item.getContext && item.getContext('2d');
  12709. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  12710. // inside an iframe or when running in a protected environment. We could guess the
  12711. // types from their toString() value but let's keep things flexible and assume it's
  12712. // a sufficient condition if the item has a context2D which has item as `canvas`.
  12713. // https://github.com/chartjs/Chart.js/issues/3887
  12714. // https://github.com/chartjs/Chart.js/issues/4102
  12715. // https://github.com/chartjs/Chart.js/issues/4152
  12716. if (context && context.canvas === item) {
  12717. // Load platform resources on first chart creation, to make it possible to
  12718. // import the library before setting platform options.
  12719. this._ensureLoaded(item);
  12720. initCanvas(item, config);
  12721. return context;
  12722. }
  12723. return null;
  12724. },
  12725. releaseContext: function(context) {
  12726. var canvas = context.canvas;
  12727. if (!canvas[EXPANDO_KEY]) {
  12728. return;
  12729. }
  12730. var initial = canvas[EXPANDO_KEY].initial;
  12731. ['height', 'width'].forEach(function(prop) {
  12732. var value = initial[prop];
  12733. if (helpers$1.isNullOrUndef(value)) {
  12734. canvas.removeAttribute(prop);
  12735. } else {
  12736. canvas.setAttribute(prop, value);
  12737. }
  12738. });
  12739. helpers$1.each(initial.style || {}, function(value, key) {
  12740. canvas.style[key] = value;
  12741. });
  12742. // The canvas render size might have been changed (and thus the state stack discarded),
  12743. // we can't use save() and restore() to restore the initial state. So make sure that at
  12744. // least the canvas context is reset to the default state by setting the canvas width.
  12745. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  12746. // eslint-disable-next-line no-self-assign
  12747. canvas.width = canvas.width;
  12748. delete canvas[EXPANDO_KEY];
  12749. },
  12750. addEventListener: function(chart, type, listener) {
  12751. var canvas = chart.canvas;
  12752. if (type === 'resize') {
  12753. // Note: the resize event is not supported on all browsers.
  12754. addResizeListener(canvas, listener, chart);
  12755. return;
  12756. }
  12757. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  12758. var proxies = expando.proxies || (expando.proxies = {});
  12759. var proxy = proxies[chart.id + '_' + type] = function(event) {
  12760. listener(fromNativeEvent(event, chart));
  12761. };
  12762. addListener(canvas, type, proxy);
  12763. },
  12764. removeEventListener: function(chart, type, listener) {
  12765. var canvas = chart.canvas;
  12766. if (type === 'resize') {
  12767. // Note: the resize event is not supported on all browsers.
  12768. removeResizeListener(canvas);
  12769. return;
  12770. }
  12771. var expando = listener[EXPANDO_KEY] || {};
  12772. var proxies = expando.proxies || {};
  12773. var proxy = proxies[chart.id + '_' + type];
  12774. if (!proxy) {
  12775. return;
  12776. }
  12777. removeListener(canvas, type, proxy);
  12778. }
  12779. };
  12780. // DEPRECATIONS
  12781. /**
  12782. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  12783. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  12784. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  12785. * @function Chart.helpers.addEvent
  12786. * @deprecated since version 2.7.0
  12787. * @todo remove at version 3
  12788. * @private
  12789. */
  12790. helpers$1.addEvent = addListener;
  12791. /**
  12792. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  12793. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  12794. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  12795. * @function Chart.helpers.removeEvent
  12796. * @deprecated since version 2.7.0
  12797. * @todo remove at version 3
  12798. * @private
  12799. */
  12800. helpers$1.removeEvent = removeListener;
  12801. // @TODO Make possible to select another platform at build time.
  12802. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  12803. /**
  12804. * @namespace Chart.platform
  12805. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  12806. * @since 2.4.0
  12807. */
  12808. var platform = helpers$1.extend({
  12809. /**
  12810. * @since 2.7.0
  12811. */
  12812. initialize: function() {},
  12813. /**
  12814. * Called at chart construction time, returns a context2d instance implementing
  12815. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  12816. * @param {*} item - The native item from which to acquire context (platform specific)
  12817. * @param {object} options - The chart options
  12818. * @returns {CanvasRenderingContext2D} context2d instance
  12819. */
  12820. acquireContext: function() {},
  12821. /**
  12822. * Called at chart destruction time, releases any resources associated to the context
  12823. * previously returned by the acquireContext() method.
  12824. * @param {CanvasRenderingContext2D} context - The context2d instance
  12825. * @returns {boolean} true if the method succeeded, else false
  12826. */
  12827. releaseContext: function() {},
  12828. /**
  12829. * Registers the specified listener on the given chart.
  12830. * @param {Chart} chart - Chart from which to listen for event
  12831. * @param {string} type - The ({@link IEvent}) type to listen for
  12832. * @param {function} listener - Receives a notification (an object that implements
  12833. * the {@link IEvent} interface) when an event of the specified type occurs.
  12834. */
  12835. addEventListener: function() {},
  12836. /**
  12837. * Removes the specified listener previously registered with addEventListener.
  12838. * @param {Chart} chart - Chart from which to remove the listener
  12839. * @param {string} type - The ({@link IEvent}) type to remove
  12840. * @param {function} listener - The listener function to remove from the event target.
  12841. */
  12842. removeEventListener: function() {}
  12843. }, implementation);
  12844. core_defaults._set('global', {
  12845. plugins: {}
  12846. });
  12847. /**
  12848. * The plugin service singleton
  12849. * @namespace Chart.plugins
  12850. * @since 2.1.0
  12851. */
  12852. var core_plugins = {
  12853. /**
  12854. * Globally registered plugins.
  12855. * @private
  12856. */
  12857. _plugins: [],
  12858. /**
  12859. * This identifier is used to invalidate the descriptors cache attached to each chart
  12860. * when a global plugin is registered or unregistered. In this case, the cache ID is
  12861. * incremented and descriptors are regenerated during following API calls.
  12862. * @private
  12863. */
  12864. _cacheId: 0,
  12865. /**
  12866. * Registers the given plugin(s) if not already registered.
  12867. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  12868. */
  12869. register: function(plugins) {
  12870. var p = this._plugins;
  12871. ([]).concat(plugins).forEach(function(plugin) {
  12872. if (p.indexOf(plugin) === -1) {
  12873. p.push(plugin);
  12874. }
  12875. });
  12876. this._cacheId++;
  12877. },
  12878. /**
  12879. * Unregisters the given plugin(s) only if registered.
  12880. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  12881. */
  12882. unregister: function(plugins) {
  12883. var p = this._plugins;
  12884. ([]).concat(plugins).forEach(function(plugin) {
  12885. var idx = p.indexOf(plugin);
  12886. if (idx !== -1) {
  12887. p.splice(idx, 1);
  12888. }
  12889. });
  12890. this._cacheId++;
  12891. },
  12892. /**
  12893. * Remove all registered plugins.
  12894. * @since 2.1.5
  12895. */
  12896. clear: function() {
  12897. this._plugins = [];
  12898. this._cacheId++;
  12899. },
  12900. /**
  12901. * Returns the number of registered plugins?
  12902. * @returns {number}
  12903. * @since 2.1.5
  12904. */
  12905. count: function() {
  12906. return this._plugins.length;
  12907. },
  12908. /**
  12909. * Returns all registered plugin instances.
  12910. * @returns {IPlugin[]} array of plugin objects.
  12911. * @since 2.1.5
  12912. */
  12913. getAll: function() {
  12914. return this._plugins;
  12915. },
  12916. /**
  12917. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  12918. * This method immediately returns as soon as a plugin explicitly returns false. The
  12919. * returned value can be used, for instance, to interrupt the current action.
  12920. * @param {Chart} chart - The chart instance for which plugins should be called.
  12921. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  12922. * @param {Array} [args] - Extra arguments to apply to the hook call.
  12923. * @returns {boolean} false if any of the plugins return false, else returns true.
  12924. */
  12925. notify: function(chart, hook, args) {
  12926. var descriptors = this.descriptors(chart);
  12927. var ilen = descriptors.length;
  12928. var i, descriptor, plugin, params, method;
  12929. for (i = 0; i < ilen; ++i) {
  12930. descriptor = descriptors[i];
  12931. plugin = descriptor.plugin;
  12932. method = plugin[hook];
  12933. if (typeof method === 'function') {
  12934. params = [chart].concat(args || []);
  12935. params.push(descriptor.options);
  12936. if (method.apply(plugin, params) === false) {
  12937. return false;
  12938. }
  12939. }
  12940. }
  12941. return true;
  12942. },
  12943. /**
  12944. * Returns descriptors of enabled plugins for the given chart.
  12945. * @returns {object[]} [{ plugin, options }]
  12946. * @private
  12947. */
  12948. descriptors: function(chart) {
  12949. var cache = chart.$plugins || (chart.$plugins = {});
  12950. if (cache.id === this._cacheId) {
  12951. return cache.descriptors;
  12952. }
  12953. var plugins = [];
  12954. var descriptors = [];
  12955. var config = (chart && chart.config) || {};
  12956. var options = (config.options && config.options.plugins) || {};
  12957. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  12958. var idx = plugins.indexOf(plugin);
  12959. if (idx !== -1) {
  12960. return;
  12961. }
  12962. var id = plugin.id;
  12963. var opts = options[id];
  12964. if (opts === false) {
  12965. return;
  12966. }
  12967. if (opts === true) {
  12968. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  12969. }
  12970. plugins.push(plugin);
  12971. descriptors.push({
  12972. plugin: plugin,
  12973. options: opts || {}
  12974. });
  12975. });
  12976. cache.descriptors = descriptors;
  12977. cache.id = this._cacheId;
  12978. return descriptors;
  12979. },
  12980. /**
  12981. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  12982. * but in some cases, this reference can be changed by the user when updating options.
  12983. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  12984. * @private
  12985. */
  12986. _invalidate: function(chart) {
  12987. delete chart.$plugins;
  12988. }
  12989. };
  12990. var core_scaleService = {
  12991. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  12992. // use the new chart options to grab the correct scale
  12993. constructors: {},
  12994. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  12995. // old browsers
  12996. // Scale config defaults
  12997. defaults: {},
  12998. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  12999. this.constructors[type] = scaleConstructor;
  13000. this.defaults[type] = helpers$1.clone(scaleDefaults);
  13001. },
  13002. getScaleConstructor: function(type) {
  13003. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  13004. },
  13005. getScaleDefaults: function(type) {
  13006. // Return the scale defaults merged with the global settings so that we always use the latest ones
  13007. return this.defaults.hasOwnProperty(type) ? helpers$1.merge(Object.create(null), [core_defaults.scale, this.defaults[type]]) : {};
  13008. },
  13009. updateScaleDefaults: function(type, additions) {
  13010. var me = this;
  13011. if (me.defaults.hasOwnProperty(type)) {
  13012. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  13013. }
  13014. },
  13015. addScalesToLayout: function(chart) {
  13016. // Adds each scale to the chart.boxes array to be sized accordingly
  13017. helpers$1.each(chart.scales, function(scale) {
  13018. // Set ILayoutItem parameters for backwards compatibility
  13019. scale.fullWidth = scale.options.fullWidth;
  13020. scale.position = scale.options.position;
  13021. scale.weight = scale.options.weight;
  13022. core_layouts.addBox(chart, scale);
  13023. });
  13024. }
  13025. };
  13026. var valueOrDefault$8 = helpers$1.valueOrDefault;
  13027. var getRtlHelper = helpers$1.rtl.getRtlAdapter;
  13028. core_defaults._set('global', {
  13029. tooltips: {
  13030. enabled: true,
  13031. custom: null,
  13032. mode: 'nearest',
  13033. position: 'average',
  13034. intersect: true,
  13035. backgroundColor: 'rgba(0,0,0,0.8)',
  13036. titleFontStyle: 'bold',
  13037. titleSpacing: 2,
  13038. titleMarginBottom: 6,
  13039. titleFontColor: '#fff',
  13040. titleAlign: 'left',
  13041. bodySpacing: 2,
  13042. bodyFontColor: '#fff',
  13043. bodyAlign: 'left',
  13044. footerFontStyle: 'bold',
  13045. footerSpacing: 2,
  13046. footerMarginTop: 6,
  13047. footerFontColor: '#fff',
  13048. footerAlign: 'left',
  13049. yPadding: 6,
  13050. xPadding: 6,
  13051. caretPadding: 2,
  13052. caretSize: 5,
  13053. cornerRadius: 6,
  13054. multiKeyBackground: '#fff',
  13055. displayColors: true,
  13056. borderColor: 'rgba(0,0,0,0)',
  13057. borderWidth: 0,
  13058. callbacks: {
  13059. // Args are: (tooltipItems, data)
  13060. beforeTitle: helpers$1.noop,
  13061. title: function(tooltipItems, data) {
  13062. var title = '';
  13063. var labels = data.labels;
  13064. var labelCount = labels ? labels.length : 0;
  13065. if (tooltipItems.length > 0) {
  13066. var item = tooltipItems[0];
  13067. if (item.label) {
  13068. title = item.label;
  13069. } else if (item.xLabel) {
  13070. title = item.xLabel;
  13071. } else if (labelCount > 0 && item.index < labelCount) {
  13072. title = labels[item.index];
  13073. }
  13074. }
  13075. return title;
  13076. },
  13077. afterTitle: helpers$1.noop,
  13078. // Args are: (tooltipItems, data)
  13079. beforeBody: helpers$1.noop,
  13080. // Args are: (tooltipItem, data)
  13081. beforeLabel: helpers$1.noop,
  13082. label: function(tooltipItem, data) {
  13083. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  13084. if (label) {
  13085. label += ': ';
  13086. }
  13087. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  13088. label += tooltipItem.value;
  13089. } else {
  13090. label += tooltipItem.yLabel;
  13091. }
  13092. return label;
  13093. },
  13094. labelColor: function(tooltipItem, chart) {
  13095. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  13096. var activeElement = meta.data[tooltipItem.index];
  13097. var view = activeElement._view;
  13098. return {
  13099. borderColor: view.borderColor,
  13100. backgroundColor: view.backgroundColor
  13101. };
  13102. },
  13103. labelTextColor: function() {
  13104. return this._options.bodyFontColor;
  13105. },
  13106. afterLabel: helpers$1.noop,
  13107. // Args are: (tooltipItems, data)
  13108. afterBody: helpers$1.noop,
  13109. // Args are: (tooltipItems, data)
  13110. beforeFooter: helpers$1.noop,
  13111. footer: helpers$1.noop,
  13112. afterFooter: helpers$1.noop
  13113. }
  13114. }
  13115. });
  13116. var positioners = {
  13117. /**
  13118. * Average mode places the tooltip at the average position of the elements shown
  13119. * @function Chart.Tooltip.positioners.average
  13120. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  13121. * @returns {object} tooltip position
  13122. */
  13123. average: function(elements) {
  13124. if (!elements.length) {
  13125. return false;
  13126. }
  13127. var i, len;
  13128. var x = 0;
  13129. var y = 0;
  13130. var count = 0;
  13131. for (i = 0, len = elements.length; i < len; ++i) {
  13132. var el = elements[i];
  13133. if (el && el.hasValue()) {
  13134. var pos = el.tooltipPosition();
  13135. x += pos.x;
  13136. y += pos.y;
  13137. ++count;
  13138. }
  13139. }
  13140. return {
  13141. x: x / count,
  13142. y: y / count
  13143. };
  13144. },
  13145. /**
  13146. * Gets the tooltip position nearest of the item nearest to the event position
  13147. * @function Chart.Tooltip.positioners.nearest
  13148. * @param elements {Chart.Element[]} the tooltip elements
  13149. * @param eventPosition {object} the position of the event in canvas coordinates
  13150. * @returns {object} the tooltip position
  13151. */
  13152. nearest: function(elements, eventPosition) {
  13153. var x = eventPosition.x;
  13154. var y = eventPosition.y;
  13155. var minDistance = Number.POSITIVE_INFINITY;
  13156. var i, len, nearestElement;
  13157. for (i = 0, len = elements.length; i < len; ++i) {
  13158. var el = elements[i];
  13159. if (el && el.hasValue()) {
  13160. var center = el.getCenterPoint();
  13161. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  13162. if (d < minDistance) {
  13163. minDistance = d;
  13164. nearestElement = el;
  13165. }
  13166. }
  13167. }
  13168. if (nearestElement) {
  13169. var tp = nearestElement.tooltipPosition();
  13170. x = tp.x;
  13171. y = tp.y;
  13172. }
  13173. return {
  13174. x: x,
  13175. y: y
  13176. };
  13177. }
  13178. };
  13179. // Helper to push or concat based on if the 2nd parameter is an array or not
  13180. function pushOrConcat(base, toPush) {
  13181. if (toPush) {
  13182. if (helpers$1.isArray(toPush)) {
  13183. // base = base.concat(toPush);
  13184. Array.prototype.push.apply(base, toPush);
  13185. } else {
  13186. base.push(toPush);
  13187. }
  13188. }
  13189. return base;
  13190. }
  13191. /**
  13192. * Returns array of strings split by newline
  13193. * @param {string} value - The value to split by newline.
  13194. * @returns {string[]} value if newline present - Returned from String split() method
  13195. * @function
  13196. */
  13197. function splitNewlines(str) {
  13198. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  13199. return str.split('\n');
  13200. }
  13201. return str;
  13202. }
  13203. /**
  13204. * Private helper to create a tooltip item model
  13205. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  13206. * @return new tooltip item
  13207. */
  13208. function createTooltipItem(element) {
  13209. var xScale = element._xScale;
  13210. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  13211. var index = element._index;
  13212. var datasetIndex = element._datasetIndex;
  13213. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  13214. var indexScale = controller._getIndexScale();
  13215. var valueScale = controller._getValueScale();
  13216. return {
  13217. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  13218. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  13219. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  13220. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  13221. index: index,
  13222. datasetIndex: datasetIndex,
  13223. x: element._model.x,
  13224. y: element._model.y
  13225. };
  13226. }
  13227. /**
  13228. * Helper to get the reset model for the tooltip
  13229. * @param tooltipOpts {object} the tooltip options
  13230. */
  13231. function getBaseModel(tooltipOpts) {
  13232. var globalDefaults = core_defaults.global;
  13233. return {
  13234. // Positioning
  13235. xPadding: tooltipOpts.xPadding,
  13236. yPadding: tooltipOpts.yPadding,
  13237. xAlign: tooltipOpts.xAlign,
  13238. yAlign: tooltipOpts.yAlign,
  13239. // Drawing direction and text direction
  13240. rtl: tooltipOpts.rtl,
  13241. textDirection: tooltipOpts.textDirection,
  13242. // Body
  13243. bodyFontColor: tooltipOpts.bodyFontColor,
  13244. _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  13245. _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  13246. _bodyAlign: tooltipOpts.bodyAlign,
  13247. bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  13248. bodySpacing: tooltipOpts.bodySpacing,
  13249. // Title
  13250. titleFontColor: tooltipOpts.titleFontColor,
  13251. _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  13252. _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  13253. titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  13254. _titleAlign: tooltipOpts.titleAlign,
  13255. titleSpacing: tooltipOpts.titleSpacing,
  13256. titleMarginBottom: tooltipOpts.titleMarginBottom,
  13257. // Footer
  13258. footerFontColor: tooltipOpts.footerFontColor,
  13259. _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  13260. _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  13261. footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  13262. _footerAlign: tooltipOpts.footerAlign,
  13263. footerSpacing: tooltipOpts.footerSpacing,
  13264. footerMarginTop: tooltipOpts.footerMarginTop,
  13265. // Appearance
  13266. caretSize: tooltipOpts.caretSize,
  13267. cornerRadius: tooltipOpts.cornerRadius,
  13268. backgroundColor: tooltipOpts.backgroundColor,
  13269. opacity: 0,
  13270. legendColorBackground: tooltipOpts.multiKeyBackground,
  13271. displayColors: tooltipOpts.displayColors,
  13272. borderColor: tooltipOpts.borderColor,
  13273. borderWidth: tooltipOpts.borderWidth
  13274. };
  13275. }
  13276. /**
  13277. * Get the size of the tooltip
  13278. */
  13279. function getTooltipSize(tooltip, model) {
  13280. var ctx = tooltip._chart.ctx;
  13281. var height = model.yPadding * 2; // Tooltip Padding
  13282. var width = 0;
  13283. // Count of all lines in the body
  13284. var body = model.body;
  13285. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  13286. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  13287. }, 0);
  13288. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  13289. var titleLineCount = model.title.length;
  13290. var footerLineCount = model.footer.length;
  13291. var titleFontSize = model.titleFontSize;
  13292. var bodyFontSize = model.bodyFontSize;
  13293. var footerFontSize = model.footerFontSize;
  13294. height += titleLineCount * titleFontSize; // Title Lines
  13295. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  13296. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  13297. height += combinedBodyLength * bodyFontSize; // Body Lines
  13298. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  13299. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  13300. height += footerLineCount * (footerFontSize); // Footer Lines
  13301. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  13302. // Title width
  13303. var widthPadding = 0;
  13304. var maxLineWidth = function(line) {
  13305. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  13306. };
  13307. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  13308. helpers$1.each(model.title, maxLineWidth);
  13309. // Body width
  13310. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  13311. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  13312. // Body lines may include some extra width due to the color box
  13313. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  13314. helpers$1.each(body, function(bodyItem) {
  13315. helpers$1.each(bodyItem.before, maxLineWidth);
  13316. helpers$1.each(bodyItem.lines, maxLineWidth);
  13317. helpers$1.each(bodyItem.after, maxLineWidth);
  13318. });
  13319. // Reset back to 0
  13320. widthPadding = 0;
  13321. // Footer width
  13322. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  13323. helpers$1.each(model.footer, maxLineWidth);
  13324. // Add padding
  13325. width += 2 * model.xPadding;
  13326. return {
  13327. width: width,
  13328. height: height
  13329. };
  13330. }
  13331. /**
  13332. * Helper to get the alignment of a tooltip given the size
  13333. */
  13334. function determineAlignment(tooltip, size) {
  13335. var model = tooltip._model;
  13336. var chart = tooltip._chart;
  13337. var chartArea = tooltip._chart.chartArea;
  13338. var xAlign = 'center';
  13339. var yAlign = 'center';
  13340. if (model.y < size.height) {
  13341. yAlign = 'top';
  13342. } else if (model.y > (chart.height - size.height)) {
  13343. yAlign = 'bottom';
  13344. }
  13345. var lf, rf; // functions to determine left, right alignment
  13346. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  13347. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  13348. var midX = (chartArea.left + chartArea.right) / 2;
  13349. var midY = (chartArea.top + chartArea.bottom) / 2;
  13350. if (yAlign === 'center') {
  13351. lf = function(x) {
  13352. return x <= midX;
  13353. };
  13354. rf = function(x) {
  13355. return x > midX;
  13356. };
  13357. } else {
  13358. lf = function(x) {
  13359. return x <= (size.width / 2);
  13360. };
  13361. rf = function(x) {
  13362. return x >= (chart.width - (size.width / 2));
  13363. };
  13364. }
  13365. olf = function(x) {
  13366. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  13367. };
  13368. orf = function(x) {
  13369. return x - size.width - model.caretSize - model.caretPadding < 0;
  13370. };
  13371. yf = function(y) {
  13372. return y <= midY ? 'top' : 'bottom';
  13373. };
  13374. if (lf(model.x)) {
  13375. xAlign = 'left';
  13376. // Is tooltip too wide and goes over the right side of the chart.?
  13377. if (olf(model.x)) {
  13378. xAlign = 'center';
  13379. yAlign = yf(model.y);
  13380. }
  13381. } else if (rf(model.x)) {
  13382. xAlign = 'right';
  13383. // Is tooltip too wide and goes outside left edge of canvas?
  13384. if (orf(model.x)) {
  13385. xAlign = 'center';
  13386. yAlign = yf(model.y);
  13387. }
  13388. }
  13389. var opts = tooltip._options;
  13390. return {
  13391. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  13392. yAlign: opts.yAlign ? opts.yAlign : yAlign
  13393. };
  13394. }
  13395. /**
  13396. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  13397. */
  13398. function getBackgroundPoint(vm, size, alignment, chart) {
  13399. // Background Position
  13400. var x = vm.x;
  13401. var y = vm.y;
  13402. var caretSize = vm.caretSize;
  13403. var caretPadding = vm.caretPadding;
  13404. var cornerRadius = vm.cornerRadius;
  13405. var xAlign = alignment.xAlign;
  13406. var yAlign = alignment.yAlign;
  13407. var paddingAndSize = caretSize + caretPadding;
  13408. var radiusAndPadding = cornerRadius + caretPadding;
  13409. if (xAlign === 'right') {
  13410. x -= size.width;
  13411. } else if (xAlign === 'center') {
  13412. x -= (size.width / 2);
  13413. if (x + size.width > chart.width) {
  13414. x = chart.width - size.width;
  13415. }
  13416. if (x < 0) {
  13417. x = 0;
  13418. }
  13419. }
  13420. if (yAlign === 'top') {
  13421. y += paddingAndSize;
  13422. } else if (yAlign === 'bottom') {
  13423. y -= size.height + paddingAndSize;
  13424. } else {
  13425. y -= (size.height / 2);
  13426. }
  13427. if (yAlign === 'center') {
  13428. if (xAlign === 'left') {
  13429. x += paddingAndSize;
  13430. } else if (xAlign === 'right') {
  13431. x -= paddingAndSize;
  13432. }
  13433. } else if (xAlign === 'left') {
  13434. x -= radiusAndPadding;
  13435. } else if (xAlign === 'right') {
  13436. x += radiusAndPadding;
  13437. }
  13438. return {
  13439. x: x,
  13440. y: y
  13441. };
  13442. }
  13443. function getAlignedX(vm, align) {
  13444. return align === 'center'
  13445. ? vm.x + vm.width / 2
  13446. : align === 'right'
  13447. ? vm.x + vm.width - vm.xPadding
  13448. : vm.x + vm.xPadding;
  13449. }
  13450. /**
  13451. * Helper to build before and after body lines
  13452. */
  13453. function getBeforeAfterBodyLines(callback) {
  13454. return pushOrConcat([], splitNewlines(callback));
  13455. }
  13456. var exports$4 = core_element.extend({
  13457. initialize: function() {
  13458. this._model = getBaseModel(this._options);
  13459. this._lastActive = [];
  13460. },
  13461. // Get the title
  13462. // Args are: (tooltipItem, data)
  13463. getTitle: function() {
  13464. var me = this;
  13465. var opts = me._options;
  13466. var callbacks = opts.callbacks;
  13467. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  13468. var title = callbacks.title.apply(me, arguments);
  13469. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  13470. var lines = [];
  13471. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  13472. lines = pushOrConcat(lines, splitNewlines(title));
  13473. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  13474. return lines;
  13475. },
  13476. // Args are: (tooltipItem, data)
  13477. getBeforeBody: function() {
  13478. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  13479. },
  13480. // Args are: (tooltipItem, data)
  13481. getBody: function(tooltipItems, data) {
  13482. var me = this;
  13483. var callbacks = me._options.callbacks;
  13484. var bodyItems = [];
  13485. helpers$1.each(tooltipItems, function(tooltipItem) {
  13486. var bodyItem = {
  13487. before: [],
  13488. lines: [],
  13489. after: []
  13490. };
  13491. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  13492. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  13493. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  13494. bodyItems.push(bodyItem);
  13495. });
  13496. return bodyItems;
  13497. },
  13498. // Args are: (tooltipItem, data)
  13499. getAfterBody: function() {
  13500. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  13501. },
  13502. // Get the footer and beforeFooter and afterFooter lines
  13503. // Args are: (tooltipItem, data)
  13504. getFooter: function() {
  13505. var me = this;
  13506. var callbacks = me._options.callbacks;
  13507. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  13508. var footer = callbacks.footer.apply(me, arguments);
  13509. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  13510. var lines = [];
  13511. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  13512. lines = pushOrConcat(lines, splitNewlines(footer));
  13513. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  13514. return lines;
  13515. },
  13516. update: function(changed) {
  13517. var me = this;
  13518. var opts = me._options;
  13519. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  13520. // 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
  13521. // which breaks any animations.
  13522. var existingModel = me._model;
  13523. var model = me._model = getBaseModel(opts);
  13524. var active = me._active;
  13525. var data = me._data;
  13526. // In the case where active.length === 0 we need to keep these at existing values for good animations
  13527. var alignment = {
  13528. xAlign: existingModel.xAlign,
  13529. yAlign: existingModel.yAlign
  13530. };
  13531. var backgroundPoint = {
  13532. x: existingModel.x,
  13533. y: existingModel.y
  13534. };
  13535. var tooltipSize = {
  13536. width: existingModel.width,
  13537. height: existingModel.height
  13538. };
  13539. var tooltipPosition = {
  13540. x: existingModel.caretX,
  13541. y: existingModel.caretY
  13542. };
  13543. var i, len;
  13544. if (active.length) {
  13545. model.opacity = 1;
  13546. var labelColors = [];
  13547. var labelTextColors = [];
  13548. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  13549. var tooltipItems = [];
  13550. for (i = 0, len = active.length; i < len; ++i) {
  13551. tooltipItems.push(createTooltipItem(active[i]));
  13552. }
  13553. // If the user provided a filter function, use it to modify the tooltip items
  13554. if (opts.filter) {
  13555. tooltipItems = tooltipItems.filter(function(a) {
  13556. return opts.filter(a, data);
  13557. });
  13558. }
  13559. // If the user provided a sorting function, use it to modify the tooltip items
  13560. if (opts.itemSort) {
  13561. tooltipItems = tooltipItems.sort(function(a, b) {
  13562. return opts.itemSort(a, b, data);
  13563. });
  13564. }
  13565. // Determine colors for boxes
  13566. helpers$1.each(tooltipItems, function(tooltipItem) {
  13567. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  13568. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  13569. });
  13570. // Build the Text Lines
  13571. model.title = me.getTitle(tooltipItems, data);
  13572. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  13573. model.body = me.getBody(tooltipItems, data);
  13574. model.afterBody = me.getAfterBody(tooltipItems, data);
  13575. model.footer = me.getFooter(tooltipItems, data);
  13576. // Initial positioning and colors
  13577. model.x = tooltipPosition.x;
  13578. model.y = tooltipPosition.y;
  13579. model.caretPadding = opts.caretPadding;
  13580. model.labelColors = labelColors;
  13581. model.labelTextColors = labelTextColors;
  13582. // data points
  13583. model.dataPoints = tooltipItems;
  13584. // We need to determine alignment of the tooltip
  13585. tooltipSize = getTooltipSize(this, model);
  13586. alignment = determineAlignment(this, tooltipSize);
  13587. // Final Size and Position
  13588. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  13589. } else {
  13590. model.opacity = 0;
  13591. }
  13592. model.xAlign = alignment.xAlign;
  13593. model.yAlign = alignment.yAlign;
  13594. model.x = backgroundPoint.x;
  13595. model.y = backgroundPoint.y;
  13596. model.width = tooltipSize.width;
  13597. model.height = tooltipSize.height;
  13598. // Point where the caret on the tooltip points to
  13599. model.caretX = tooltipPosition.x;
  13600. model.caretY = tooltipPosition.y;
  13601. me._model = model;
  13602. if (changed && opts.custom) {
  13603. opts.custom.call(me, model);
  13604. }
  13605. return me;
  13606. },
  13607. drawCaret: function(tooltipPoint, size) {
  13608. var ctx = this._chart.ctx;
  13609. var vm = this._view;
  13610. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  13611. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  13612. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  13613. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  13614. },
  13615. getCaretPosition: function(tooltipPoint, size, vm) {
  13616. var x1, x2, x3, y1, y2, y3;
  13617. var caretSize = vm.caretSize;
  13618. var cornerRadius = vm.cornerRadius;
  13619. var xAlign = vm.xAlign;
  13620. var yAlign = vm.yAlign;
  13621. var ptX = tooltipPoint.x;
  13622. var ptY = tooltipPoint.y;
  13623. var width = size.width;
  13624. var height = size.height;
  13625. if (yAlign === 'center') {
  13626. y2 = ptY + (height / 2);
  13627. if (xAlign === 'left') {
  13628. x1 = ptX;
  13629. x2 = x1 - caretSize;
  13630. x3 = x1;
  13631. y1 = y2 + caretSize;
  13632. y3 = y2 - caretSize;
  13633. } else {
  13634. x1 = ptX + width;
  13635. x2 = x1 + caretSize;
  13636. x3 = x1;
  13637. y1 = y2 - caretSize;
  13638. y3 = y2 + caretSize;
  13639. }
  13640. } else {
  13641. if (xAlign === 'left') {
  13642. x2 = ptX + cornerRadius + (caretSize);
  13643. x1 = x2 - caretSize;
  13644. x3 = x2 + caretSize;
  13645. } else if (xAlign === 'right') {
  13646. x2 = ptX + width - cornerRadius - caretSize;
  13647. x1 = x2 - caretSize;
  13648. x3 = x2 + caretSize;
  13649. } else {
  13650. x2 = vm.caretX;
  13651. x1 = x2 - caretSize;
  13652. x3 = x2 + caretSize;
  13653. }
  13654. if (yAlign === 'top') {
  13655. y1 = ptY;
  13656. y2 = y1 - caretSize;
  13657. y3 = y1;
  13658. } else {
  13659. y1 = ptY + height;
  13660. y2 = y1 + caretSize;
  13661. y3 = y1;
  13662. // invert drawing order
  13663. var tmp = x3;
  13664. x3 = x1;
  13665. x1 = tmp;
  13666. }
  13667. }
  13668. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  13669. },
  13670. drawTitle: function(pt, vm, ctx) {
  13671. var title = vm.title;
  13672. var length = title.length;
  13673. var titleFontSize, titleSpacing, i;
  13674. if (length) {
  13675. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  13676. pt.x = getAlignedX(vm, vm._titleAlign);
  13677. ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);
  13678. ctx.textBaseline = 'middle';
  13679. titleFontSize = vm.titleFontSize;
  13680. titleSpacing = vm.titleSpacing;
  13681. ctx.fillStyle = vm.titleFontColor;
  13682. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  13683. for (i = 0; i < length; ++i) {
  13684. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);
  13685. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  13686. if (i + 1 === length) {
  13687. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  13688. }
  13689. }
  13690. }
  13691. },
  13692. drawBody: function(pt, vm, ctx) {
  13693. var bodyFontSize = vm.bodyFontSize;
  13694. var bodySpacing = vm.bodySpacing;
  13695. var bodyAlign = vm._bodyAlign;
  13696. var body = vm.body;
  13697. var drawColorBoxes = vm.displayColors;
  13698. var xLinePadding = 0;
  13699. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  13700. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  13701. var fillLineOfText = function(line) {
  13702. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
  13703. pt.y += bodyFontSize + bodySpacing;
  13704. };
  13705. var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;
  13706. var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  13707. ctx.textAlign = bodyAlign;
  13708. ctx.textBaseline = 'middle';
  13709. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  13710. pt.x = getAlignedX(vm, bodyAlignForCalculation);
  13711. // Before body lines
  13712. ctx.fillStyle = vm.bodyFontColor;
  13713. helpers$1.each(vm.beforeBody, fillLineOfText);
  13714. xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'
  13715. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  13716. : 0;
  13717. // Draw body lines now
  13718. for (i = 0, ilen = body.length; i < ilen; ++i) {
  13719. bodyItem = body[i];
  13720. textColor = vm.labelTextColors[i];
  13721. labelColors = vm.labelColors[i];
  13722. ctx.fillStyle = textColor;
  13723. helpers$1.each(bodyItem.before, fillLineOfText);
  13724. lines = bodyItem.lines;
  13725. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  13726. // Draw Legend-like boxes if needed
  13727. if (drawColorBoxes) {
  13728. var rtlColorX = rtlHelper.x(colorX);
  13729. // Fill a white rect so that colours merge nicely if the opacity is < 1
  13730. ctx.fillStyle = vm.legendColorBackground;
  13731. ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  13732. // Border
  13733. ctx.lineWidth = 1;
  13734. ctx.strokeStyle = labelColors.borderColor;
  13735. ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  13736. // Inner square
  13737. ctx.fillStyle = labelColors.backgroundColor;
  13738. ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  13739. ctx.fillStyle = textColor;
  13740. }
  13741. fillLineOfText(lines[j]);
  13742. }
  13743. helpers$1.each(bodyItem.after, fillLineOfText);
  13744. }
  13745. // Reset back to 0 for after body
  13746. xLinePadding = 0;
  13747. // After body lines
  13748. helpers$1.each(vm.afterBody, fillLineOfText);
  13749. pt.y -= bodySpacing; // Remove last body spacing
  13750. },
  13751. drawFooter: function(pt, vm, ctx) {
  13752. var footer = vm.footer;
  13753. var length = footer.length;
  13754. var footerFontSize, i;
  13755. if (length) {
  13756. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  13757. pt.x = getAlignedX(vm, vm._footerAlign);
  13758. pt.y += vm.footerMarginTop;
  13759. ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);
  13760. ctx.textBaseline = 'middle';
  13761. footerFontSize = vm.footerFontSize;
  13762. ctx.fillStyle = vm.footerFontColor;
  13763. ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  13764. for (i = 0; i < length; ++i) {
  13765. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);
  13766. pt.y += footerFontSize + vm.footerSpacing;
  13767. }
  13768. }
  13769. },
  13770. drawBackground: function(pt, vm, ctx, tooltipSize) {
  13771. ctx.fillStyle = vm.backgroundColor;
  13772. ctx.strokeStyle = vm.borderColor;
  13773. ctx.lineWidth = vm.borderWidth;
  13774. var xAlign = vm.xAlign;
  13775. var yAlign = vm.yAlign;
  13776. var x = pt.x;
  13777. var y = pt.y;
  13778. var width = tooltipSize.width;
  13779. var height = tooltipSize.height;
  13780. var radius = vm.cornerRadius;
  13781. ctx.beginPath();
  13782. ctx.moveTo(x + radius, y);
  13783. if (yAlign === 'top') {
  13784. this.drawCaret(pt, tooltipSize);
  13785. }
  13786. ctx.lineTo(x + width - radius, y);
  13787. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  13788. if (yAlign === 'center' && xAlign === 'right') {
  13789. this.drawCaret(pt, tooltipSize);
  13790. }
  13791. ctx.lineTo(x + width, y + height - radius);
  13792. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  13793. if (yAlign === 'bottom') {
  13794. this.drawCaret(pt, tooltipSize);
  13795. }
  13796. ctx.lineTo(x + radius, y + height);
  13797. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  13798. if (yAlign === 'center' && xAlign === 'left') {
  13799. this.drawCaret(pt, tooltipSize);
  13800. }
  13801. ctx.lineTo(x, y + radius);
  13802. ctx.quadraticCurveTo(x, y, x + radius, y);
  13803. ctx.closePath();
  13804. ctx.fill();
  13805. if (vm.borderWidth > 0) {
  13806. ctx.stroke();
  13807. }
  13808. },
  13809. draw: function() {
  13810. var ctx = this._chart.ctx;
  13811. var vm = this._view;
  13812. if (vm.opacity === 0) {
  13813. return;
  13814. }
  13815. var tooltipSize = {
  13816. width: vm.width,
  13817. height: vm.height
  13818. };
  13819. var pt = {
  13820. x: vm.x,
  13821. y: vm.y
  13822. };
  13823. // IE11/Edge does not like very small opacities, so snap to 0
  13824. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  13825. // Truthy/falsey value for empty tooltip
  13826. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  13827. if (this._options.enabled && hasTooltipContent) {
  13828. ctx.save();
  13829. ctx.globalAlpha = opacity;
  13830. // Draw Background
  13831. this.drawBackground(pt, vm, ctx, tooltipSize);
  13832. // Draw Title, Body, and Footer
  13833. pt.y += vm.yPadding;
  13834. helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);
  13835. // Titles
  13836. this.drawTitle(pt, vm, ctx);
  13837. // Body
  13838. this.drawBody(pt, vm, ctx);
  13839. // Footer
  13840. this.drawFooter(pt, vm, ctx);
  13841. helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);
  13842. ctx.restore();
  13843. }
  13844. },
  13845. /**
  13846. * Handle an event
  13847. * @private
  13848. * @param {IEvent} event - The event to handle
  13849. * @returns {boolean} true if the tooltip changed
  13850. */
  13851. handleEvent: function(e) {
  13852. var me = this;
  13853. var options = me._options;
  13854. var changed = false;
  13855. me._lastActive = me._lastActive || [];
  13856. // Find Active Elements for tooltips
  13857. if (e.type === 'mouseout') {
  13858. me._active = [];
  13859. } else {
  13860. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  13861. if (options.reverse) {
  13862. me._active.reverse();
  13863. }
  13864. }
  13865. // Remember Last Actives
  13866. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  13867. // Only handle target event on tooltip change
  13868. if (changed) {
  13869. me._lastActive = me._active;
  13870. if (options.enabled || options.custom) {
  13871. me._eventPosition = {
  13872. x: e.x,
  13873. y: e.y
  13874. };
  13875. me.update(true);
  13876. me.pivot();
  13877. }
  13878. }
  13879. return changed;
  13880. }
  13881. });
  13882. /**
  13883. * @namespace Chart.Tooltip.positioners
  13884. */
  13885. var positioners_1 = positioners;
  13886. var core_tooltip = exports$4;
  13887. core_tooltip.positioners = positioners_1;
  13888. var valueOrDefault$9 = helpers$1.valueOrDefault;
  13889. core_defaults._set('global', {
  13890. elements: {},
  13891. events: [
  13892. 'mousemove',
  13893. 'mouseout',
  13894. 'click',
  13895. 'touchstart',
  13896. 'touchmove'
  13897. ],
  13898. hover: {
  13899. onHover: null,
  13900. mode: 'nearest',
  13901. intersect: true,
  13902. animationDuration: 400
  13903. },
  13904. onClick: null,
  13905. maintainAspectRatio: true,
  13906. responsive: true,
  13907. responsiveAnimationDuration: 0
  13908. });
  13909. /**
  13910. * Recursively merge the given config objects representing the `scales` option
  13911. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  13912. * returns a deep copy of the result, thus doesn't alter inputs.
  13913. */
  13914. function mergeScaleConfig(/* config objects ... */) {
  13915. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  13916. merger: function(key, target, source, options) {
  13917. if (key === 'xAxes' || key === 'yAxes') {
  13918. var slen = source[key].length;
  13919. var i, type, scale;
  13920. if (!target[key]) {
  13921. target[key] = [];
  13922. }
  13923. for (i = 0; i < slen; ++i) {
  13924. scale = source[key][i];
  13925. type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');
  13926. if (i >= target[key].length) {
  13927. target[key].push({});
  13928. }
  13929. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  13930. // new/untyped scale or type changed: let's apply the new defaults
  13931. // then merge source scale to correctly overwrite the defaults.
  13932. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  13933. } else {
  13934. // scales type are the same
  13935. helpers$1.merge(target[key][i], scale);
  13936. }
  13937. }
  13938. } else {
  13939. helpers$1._merger(key, target, source, options);
  13940. }
  13941. }
  13942. });
  13943. }
  13944. /**
  13945. * Recursively merge the given config objects as the root options by handling
  13946. * default scale options for the `scales` and `scale` properties, then returns
  13947. * a deep copy of the result, thus doesn't alter inputs.
  13948. */
  13949. function mergeConfig(/* config objects ... */) {
  13950. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  13951. merger: function(key, target, source, options) {
  13952. var tval = target[key] || Object.create(null);
  13953. var sval = source[key];
  13954. if (key === 'scales') {
  13955. // scale config merging is complex. Add our own function here for that
  13956. target[key] = mergeScaleConfig(tval, sval);
  13957. } else if (key === 'scale') {
  13958. // used in polar area & radar charts since there is only one scale
  13959. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  13960. } else {
  13961. helpers$1._merger(key, target, source, options);
  13962. }
  13963. }
  13964. });
  13965. }
  13966. function initConfig(config) {
  13967. config = config || Object.create(null);
  13968. // Do NOT use mergeConfig for the data object because this method merges arrays
  13969. // and so would change references to labels and datasets, preventing data updates.
  13970. var data = config.data = config.data || {};
  13971. data.datasets = data.datasets || [];
  13972. data.labels = data.labels || [];
  13973. config.options = mergeConfig(
  13974. core_defaults.global,
  13975. core_defaults[config.type],
  13976. config.options || {});
  13977. return config;
  13978. }
  13979. function updateConfig(chart) {
  13980. var newOptions = chart.options;
  13981. helpers$1.each(chart.scales, function(scale) {
  13982. core_layouts.removeBox(chart, scale);
  13983. });
  13984. newOptions = mergeConfig(
  13985. core_defaults.global,
  13986. core_defaults[chart.config.type],
  13987. newOptions);
  13988. chart.options = chart.config.options = newOptions;
  13989. chart.ensureScalesHaveIDs();
  13990. chart.buildOrUpdateScales();
  13991. // Tooltip
  13992. chart.tooltip._options = newOptions.tooltips;
  13993. chart.tooltip.initialize();
  13994. }
  13995. function nextAvailableScaleId(axesOpts, prefix, index) {
  13996. var id;
  13997. var hasId = function(obj) {
  13998. return obj.id === id;
  13999. };
  14000. do {
  14001. id = prefix + index++;
  14002. } while (helpers$1.findIndex(axesOpts, hasId) >= 0);
  14003. return id;
  14004. }
  14005. function positionIsHorizontal(position) {
  14006. return position === 'top' || position === 'bottom';
  14007. }
  14008. function compare2Level(l1, l2) {
  14009. return function(a, b) {
  14010. return a[l1] === b[l1]
  14011. ? a[l2] - b[l2]
  14012. : a[l1] - b[l1];
  14013. };
  14014. }
  14015. var Chart = function(item, config) {
  14016. this.construct(item, config);
  14017. return this;
  14018. };
  14019. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  14020. /**
  14021. * @private
  14022. */
  14023. construct: function(item, config) {
  14024. var me = this;
  14025. config = initConfig(config);
  14026. var context = platform.acquireContext(item, config);
  14027. var canvas = context && context.canvas;
  14028. var height = canvas && canvas.height;
  14029. var width = canvas && canvas.width;
  14030. me.id = helpers$1.uid();
  14031. me.ctx = context;
  14032. me.canvas = canvas;
  14033. me.config = config;
  14034. me.width = width;
  14035. me.height = height;
  14036. me.aspectRatio = height ? width / height : null;
  14037. me.options = config.options;
  14038. me._bufferedRender = false;
  14039. me._layers = [];
  14040. /**
  14041. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  14042. * the "instance" still need to be defined since it might be called from plugins.
  14043. * @prop Chart#chart
  14044. * @deprecated since version 2.6.0
  14045. * @todo remove at version 3
  14046. * @private
  14047. */
  14048. me.chart = me;
  14049. me.controller = me; // chart.chart.controller #inception
  14050. // Add the chart instance to the global namespace
  14051. Chart.instances[me.id] = me;
  14052. // Define alias to the config data: `chart.data === chart.config.data`
  14053. Object.defineProperty(me, 'data', {
  14054. get: function() {
  14055. return me.config.data;
  14056. },
  14057. set: function(value) {
  14058. me.config.data = value;
  14059. }
  14060. });
  14061. if (!context || !canvas) {
  14062. // The given item is not a compatible context2d element, let's return before finalizing
  14063. // the chart initialization but after setting basic chart / controller properties that
  14064. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  14065. // https://github.com/chartjs/Chart.js/issues/2807
  14066. console.error("Failed to create chart: can't acquire context from the given item");
  14067. return;
  14068. }
  14069. me.initialize();
  14070. me.update();
  14071. },
  14072. /**
  14073. * @private
  14074. */
  14075. initialize: function() {
  14076. var me = this;
  14077. // Before init plugin notification
  14078. core_plugins.notify(me, 'beforeInit');
  14079. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  14080. me.bindEvents();
  14081. if (me.options.responsive) {
  14082. // Initial resize before chart draws (must be silent to preserve initial animations).
  14083. me.resize(true);
  14084. }
  14085. me.initToolTip();
  14086. // After init plugin notification
  14087. core_plugins.notify(me, 'afterInit');
  14088. return me;
  14089. },
  14090. clear: function() {
  14091. helpers$1.canvas.clear(this);
  14092. return this;
  14093. },
  14094. stop: function() {
  14095. // Stops any current animation loop occurring
  14096. core_animations.cancelAnimation(this);
  14097. return this;
  14098. },
  14099. resize: function(silent) {
  14100. var me = this;
  14101. var options = me.options;
  14102. var canvas = me.canvas;
  14103. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  14104. // the canvas render width and height will be casted to integers so make sure that
  14105. // the canvas display style uses the same integer values to avoid blurring effect.
  14106. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  14107. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  14108. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  14109. if (me.width === newWidth && me.height === newHeight) {
  14110. return;
  14111. }
  14112. canvas.width = me.width = newWidth;
  14113. canvas.height = me.height = newHeight;
  14114. canvas.style.width = newWidth + 'px';
  14115. canvas.style.height = newHeight + 'px';
  14116. helpers$1.retinaScale(me, options.devicePixelRatio);
  14117. if (!silent) {
  14118. // Notify any plugins about the resize
  14119. var newSize = {width: newWidth, height: newHeight};
  14120. core_plugins.notify(me, 'resize', [newSize]);
  14121. // Notify of resize
  14122. if (options.onResize) {
  14123. options.onResize(me, newSize);
  14124. }
  14125. me.stop();
  14126. me.update({
  14127. duration: options.responsiveAnimationDuration
  14128. });
  14129. }
  14130. },
  14131. ensureScalesHaveIDs: function() {
  14132. var options = this.options;
  14133. var scalesOptions = options.scales || {};
  14134. var scaleOptions = options.scale;
  14135. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  14136. if (!xAxisOptions.id) {
  14137. xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);
  14138. }
  14139. });
  14140. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  14141. if (!yAxisOptions.id) {
  14142. yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);
  14143. }
  14144. });
  14145. if (scaleOptions) {
  14146. scaleOptions.id = scaleOptions.id || 'scale';
  14147. }
  14148. },
  14149. /**
  14150. * Builds a map of scale ID to scale object for future lookup.
  14151. */
  14152. buildOrUpdateScales: function() {
  14153. var me = this;
  14154. var options = me.options;
  14155. var scales = me.scales || {};
  14156. var items = [];
  14157. var updated = Object.keys(scales).reduce(function(obj, id) {
  14158. obj[id] = false;
  14159. return obj;
  14160. }, {});
  14161. if (options.scales) {
  14162. items = items.concat(
  14163. (options.scales.xAxes || []).map(function(xAxisOptions) {
  14164. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  14165. }),
  14166. (options.scales.yAxes || []).map(function(yAxisOptions) {
  14167. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  14168. })
  14169. );
  14170. }
  14171. if (options.scale) {
  14172. items.push({
  14173. options: options.scale,
  14174. dtype: 'radialLinear',
  14175. isDefault: true,
  14176. dposition: 'chartArea'
  14177. });
  14178. }
  14179. helpers$1.each(items, function(item) {
  14180. var scaleOptions = item.options;
  14181. var id = scaleOptions.id;
  14182. var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);
  14183. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  14184. scaleOptions.position = item.dposition;
  14185. }
  14186. updated[id] = true;
  14187. var scale = null;
  14188. if (id in scales && scales[id].type === scaleType) {
  14189. scale = scales[id];
  14190. scale.options = scaleOptions;
  14191. scale.ctx = me.ctx;
  14192. scale.chart = me;
  14193. } else {
  14194. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  14195. if (!scaleClass) {
  14196. return;
  14197. }
  14198. scale = new scaleClass({
  14199. id: id,
  14200. type: scaleType,
  14201. options: scaleOptions,
  14202. ctx: me.ctx,
  14203. chart: me
  14204. });
  14205. scales[scale.id] = scale;
  14206. }
  14207. scale.mergeTicksOptions();
  14208. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  14209. // and consider it as a regular scale part of the "scales"" map only! This would
  14210. // make the logic easier and remove some useless? custom code.
  14211. if (item.isDefault) {
  14212. me.scale = scale;
  14213. }
  14214. });
  14215. // clear up discarded scales
  14216. helpers$1.each(updated, function(hasUpdated, id) {
  14217. if (!hasUpdated) {
  14218. delete scales[id];
  14219. }
  14220. });
  14221. me.scales = scales;
  14222. core_scaleService.addScalesToLayout(this);
  14223. },
  14224. buildOrUpdateControllers: function() {
  14225. var me = this;
  14226. var newControllers = [];
  14227. var datasets = me.data.datasets;
  14228. var i, ilen;
  14229. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  14230. var dataset = datasets[i];
  14231. var meta = me.getDatasetMeta(i);
  14232. var type = dataset.type || me.config.type;
  14233. if (meta.type && meta.type !== type) {
  14234. me.destroyDatasetMeta(i);
  14235. meta = me.getDatasetMeta(i);
  14236. }
  14237. meta.type = type;
  14238. meta.order = dataset.order || 0;
  14239. meta.index = i;
  14240. if (meta.controller) {
  14241. meta.controller.updateIndex(i);
  14242. meta.controller.linkScales();
  14243. } else {
  14244. var ControllerClass = controllers[meta.type];
  14245. if (ControllerClass === undefined) {
  14246. throw new Error('"' + meta.type + '" is not a chart type.');
  14247. }
  14248. meta.controller = new ControllerClass(me, i);
  14249. newControllers.push(meta.controller);
  14250. }
  14251. }
  14252. return newControllers;
  14253. },
  14254. /**
  14255. * Reset the elements of all datasets
  14256. * @private
  14257. */
  14258. resetElements: function() {
  14259. var me = this;
  14260. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  14261. me.getDatasetMeta(datasetIndex).controller.reset();
  14262. }, me);
  14263. },
  14264. /**
  14265. * Resets the chart back to it's state before the initial animation
  14266. */
  14267. reset: function() {
  14268. this.resetElements();
  14269. this.tooltip.initialize();
  14270. },
  14271. update: function(config) {
  14272. var me = this;
  14273. var i, ilen;
  14274. if (!config || typeof config !== 'object') {
  14275. // backwards compatibility
  14276. config = {
  14277. duration: config,
  14278. lazy: arguments[1]
  14279. };
  14280. }
  14281. updateConfig(me);
  14282. // plugins options references might have change, let's invalidate the cache
  14283. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  14284. core_plugins._invalidate(me);
  14285. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  14286. return;
  14287. }
  14288. // In case the entire data object changed
  14289. me.tooltip._data = me.data;
  14290. // Make sure dataset controllers are updated and new controllers are reset
  14291. var newControllers = me.buildOrUpdateControllers();
  14292. // Make sure all dataset controllers have correct meta data counts
  14293. for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  14294. me.getDatasetMeta(i).controller.buildOrUpdateElements();
  14295. }
  14296. me.updateLayout();
  14297. // Can only reset the new controllers after the scales have been updated
  14298. if (me.options.animation && me.options.animation.duration) {
  14299. helpers$1.each(newControllers, function(controller) {
  14300. controller.reset();
  14301. });
  14302. }
  14303. me.updateDatasets();
  14304. // Need to reset tooltip in case it is displayed with elements that are removed
  14305. // after update.
  14306. me.tooltip.initialize();
  14307. // Last active contains items that were previously in the tooltip.
  14308. // When we reset the tooltip, we need to clear it
  14309. me.lastActive = [];
  14310. // Do this before render so that any plugins that need final scale updates can use it
  14311. core_plugins.notify(me, 'afterUpdate');
  14312. me._layers.sort(compare2Level('z', '_idx'));
  14313. if (me._bufferedRender) {
  14314. me._bufferedRequest = {
  14315. duration: config.duration,
  14316. easing: config.easing,
  14317. lazy: config.lazy
  14318. };
  14319. } else {
  14320. me.render(config);
  14321. }
  14322. },
  14323. /**
  14324. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  14325. * hook, in which case, plugins will not be called on `afterLayout`.
  14326. * @private
  14327. */
  14328. updateLayout: function() {
  14329. var me = this;
  14330. if (core_plugins.notify(me, 'beforeLayout') === false) {
  14331. return;
  14332. }
  14333. core_layouts.update(this, this.width, this.height);
  14334. me._layers = [];
  14335. helpers$1.each(me.boxes, function(box) {
  14336. // _configure is called twice, once in core.scale.update and once here.
  14337. // Here the boxes are fully updated and at their final positions.
  14338. if (box._configure) {
  14339. box._configure();
  14340. }
  14341. me._layers.push.apply(me._layers, box._layers());
  14342. }, me);
  14343. me._layers.forEach(function(item, index) {
  14344. item._idx = index;
  14345. });
  14346. /**
  14347. * Provided for backward compatibility, use `afterLayout` instead.
  14348. * @method IPlugin#afterScaleUpdate
  14349. * @deprecated since version 2.5.0
  14350. * @todo remove at version 3
  14351. * @private
  14352. */
  14353. core_plugins.notify(me, 'afterScaleUpdate');
  14354. core_plugins.notify(me, 'afterLayout');
  14355. },
  14356. /**
  14357. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  14358. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  14359. * @private
  14360. */
  14361. updateDatasets: function() {
  14362. var me = this;
  14363. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  14364. return;
  14365. }
  14366. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  14367. me.updateDataset(i);
  14368. }
  14369. core_plugins.notify(me, 'afterDatasetsUpdate');
  14370. },
  14371. /**
  14372. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  14373. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  14374. * @private
  14375. */
  14376. updateDataset: function(index) {
  14377. var me = this;
  14378. var meta = me.getDatasetMeta(index);
  14379. var args = {
  14380. meta: meta,
  14381. index: index
  14382. };
  14383. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  14384. return;
  14385. }
  14386. meta.controller._update();
  14387. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  14388. },
  14389. render: function(config) {
  14390. var me = this;
  14391. if (!config || typeof config !== 'object') {
  14392. // backwards compatibility
  14393. config = {
  14394. duration: config,
  14395. lazy: arguments[1]
  14396. };
  14397. }
  14398. var animationOptions = me.options.animation;
  14399. var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);
  14400. var lazy = config.lazy;
  14401. if (core_plugins.notify(me, 'beforeRender') === false) {
  14402. return;
  14403. }
  14404. var onComplete = function(animation) {
  14405. core_plugins.notify(me, 'afterRender');
  14406. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  14407. };
  14408. if (animationOptions && duration) {
  14409. var animation = new core_animation({
  14410. numSteps: duration / 16.66, // 60 fps
  14411. easing: config.easing || animationOptions.easing,
  14412. render: function(chart, animationObject) {
  14413. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  14414. var currentStep = animationObject.currentStep;
  14415. var stepDecimal = currentStep / animationObject.numSteps;
  14416. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  14417. },
  14418. onAnimationProgress: animationOptions.onProgress,
  14419. onAnimationComplete: onComplete
  14420. });
  14421. core_animations.addAnimation(me, animation, duration, lazy);
  14422. } else {
  14423. me.draw();
  14424. // See https://github.com/chartjs/Chart.js/issues/3781
  14425. onComplete(new core_animation({numSteps: 0, chart: me}));
  14426. }
  14427. return me;
  14428. },
  14429. draw: function(easingValue) {
  14430. var me = this;
  14431. var i, layers;
  14432. me.clear();
  14433. if (helpers$1.isNullOrUndef(easingValue)) {
  14434. easingValue = 1;
  14435. }
  14436. me.transition(easingValue);
  14437. if (me.width <= 0 || me.height <= 0) {
  14438. return;
  14439. }
  14440. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  14441. return;
  14442. }
  14443. // Because of plugin hooks (before/afterDatasetsDraw), datasets can't
  14444. // currently be part of layers. Instead, we draw
  14445. // layers <= 0 before(default, backward compat), and the rest after
  14446. layers = me._layers;
  14447. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  14448. layers[i].draw(me.chartArea);
  14449. }
  14450. me.drawDatasets(easingValue);
  14451. // Rest of layers
  14452. for (; i < layers.length; ++i) {
  14453. layers[i].draw(me.chartArea);
  14454. }
  14455. me._drawTooltip(easingValue);
  14456. core_plugins.notify(me, 'afterDraw', [easingValue]);
  14457. },
  14458. /**
  14459. * @private
  14460. */
  14461. transition: function(easingValue) {
  14462. var me = this;
  14463. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  14464. if (me.isDatasetVisible(i)) {
  14465. me.getDatasetMeta(i).controller.transition(easingValue);
  14466. }
  14467. }
  14468. me.tooltip.transition(easingValue);
  14469. },
  14470. /**
  14471. * @private
  14472. */
  14473. _getSortedDatasetMetas: function(filterVisible) {
  14474. var me = this;
  14475. var datasets = me.data.datasets || [];
  14476. var result = [];
  14477. var i, ilen;
  14478. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  14479. if (!filterVisible || me.isDatasetVisible(i)) {
  14480. result.push(me.getDatasetMeta(i));
  14481. }
  14482. }
  14483. result.sort(compare2Level('order', 'index'));
  14484. return result;
  14485. },
  14486. /**
  14487. * @private
  14488. */
  14489. _getSortedVisibleDatasetMetas: function() {
  14490. return this._getSortedDatasetMetas(true);
  14491. },
  14492. /**
  14493. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  14494. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  14495. * @private
  14496. */
  14497. drawDatasets: function(easingValue) {
  14498. var me = this;
  14499. var metasets, i;
  14500. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  14501. return;
  14502. }
  14503. metasets = me._getSortedVisibleDatasetMetas();
  14504. for (i = metasets.length - 1; i >= 0; --i) {
  14505. me.drawDataset(metasets[i], easingValue);
  14506. }
  14507. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  14508. },
  14509. /**
  14510. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  14511. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  14512. * @private
  14513. */
  14514. drawDataset: function(meta, easingValue) {
  14515. var me = this;
  14516. var args = {
  14517. meta: meta,
  14518. index: meta.index,
  14519. easingValue: easingValue
  14520. };
  14521. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  14522. return;
  14523. }
  14524. meta.controller.draw(easingValue);
  14525. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  14526. },
  14527. /**
  14528. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  14529. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  14530. * @private
  14531. */
  14532. _drawTooltip: function(easingValue) {
  14533. var me = this;
  14534. var tooltip = me.tooltip;
  14535. var args = {
  14536. tooltip: tooltip,
  14537. easingValue: easingValue
  14538. };
  14539. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  14540. return;
  14541. }
  14542. tooltip.draw();
  14543. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  14544. },
  14545. /**
  14546. * Get the single element that was clicked on
  14547. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  14548. */
  14549. getElementAtEvent: function(e) {
  14550. return core_interaction.modes.single(this, e);
  14551. },
  14552. getElementsAtEvent: function(e) {
  14553. return core_interaction.modes.label(this, e, {intersect: true});
  14554. },
  14555. getElementsAtXAxis: function(e) {
  14556. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  14557. },
  14558. getElementsAtEventForMode: function(e, mode, options) {
  14559. var method = core_interaction.modes[mode];
  14560. if (typeof method === 'function') {
  14561. return method(this, e, options);
  14562. }
  14563. return [];
  14564. },
  14565. getDatasetAtEvent: function(e) {
  14566. return core_interaction.modes.dataset(this, e, {intersect: true});
  14567. },
  14568. getDatasetMeta: function(datasetIndex) {
  14569. var me = this;
  14570. var dataset = me.data.datasets[datasetIndex];
  14571. if (!dataset._meta) {
  14572. dataset._meta = {};
  14573. }
  14574. var meta = dataset._meta[me.id];
  14575. if (!meta) {
  14576. meta = dataset._meta[me.id] = {
  14577. type: null,
  14578. data: [],
  14579. dataset: null,
  14580. controller: null,
  14581. hidden: null, // See isDatasetVisible() comment
  14582. xAxisID: null,
  14583. yAxisID: null,
  14584. order: dataset.order || 0,
  14585. index: datasetIndex
  14586. };
  14587. }
  14588. return meta;
  14589. },
  14590. getVisibleDatasetCount: function() {
  14591. var count = 0;
  14592. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  14593. if (this.isDatasetVisible(i)) {
  14594. count++;
  14595. }
  14596. }
  14597. return count;
  14598. },
  14599. isDatasetVisible: function(datasetIndex) {
  14600. var meta = this.getDatasetMeta(datasetIndex);
  14601. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  14602. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  14603. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  14604. },
  14605. generateLegend: function() {
  14606. return this.options.legendCallback(this);
  14607. },
  14608. /**
  14609. * @private
  14610. */
  14611. destroyDatasetMeta: function(datasetIndex) {
  14612. var id = this.id;
  14613. var dataset = this.data.datasets[datasetIndex];
  14614. var meta = dataset._meta && dataset._meta[id];
  14615. if (meta) {
  14616. meta.controller.destroy();
  14617. delete dataset._meta[id];
  14618. }
  14619. },
  14620. destroy: function() {
  14621. var me = this;
  14622. var canvas = me.canvas;
  14623. var i, ilen;
  14624. me.stop();
  14625. // dataset controllers need to cleanup associated data
  14626. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  14627. me.destroyDatasetMeta(i);
  14628. }
  14629. if (canvas) {
  14630. me.unbindEvents();
  14631. helpers$1.canvas.clear(me);
  14632. platform.releaseContext(me.ctx);
  14633. me.canvas = null;
  14634. me.ctx = null;
  14635. }
  14636. core_plugins.notify(me, 'destroy');
  14637. delete Chart.instances[me.id];
  14638. },
  14639. toBase64Image: function() {
  14640. return this.canvas.toDataURL.apply(this.canvas, arguments);
  14641. },
  14642. initToolTip: function() {
  14643. var me = this;
  14644. me.tooltip = new core_tooltip({
  14645. _chart: me,
  14646. _chartInstance: me, // deprecated, backward compatibility
  14647. _data: me.data,
  14648. _options: me.options.tooltips
  14649. }, me);
  14650. },
  14651. /**
  14652. * @private
  14653. */
  14654. bindEvents: function() {
  14655. var me = this;
  14656. var listeners = me._listeners = {};
  14657. var listener = function() {
  14658. me.eventHandler.apply(me, arguments);
  14659. };
  14660. helpers$1.each(me.options.events, function(type) {
  14661. platform.addEventListener(me, type, listener);
  14662. listeners[type] = listener;
  14663. });
  14664. // Elements used to detect size change should not be injected for non responsive charts.
  14665. // See https://github.com/chartjs/Chart.js/issues/2210
  14666. if (me.options.responsive) {
  14667. listener = function() {
  14668. me.resize();
  14669. };
  14670. platform.addEventListener(me, 'resize', listener);
  14671. listeners.resize = listener;
  14672. }
  14673. },
  14674. /**
  14675. * @private
  14676. */
  14677. unbindEvents: function() {
  14678. var me = this;
  14679. var listeners = me._listeners;
  14680. if (!listeners) {
  14681. return;
  14682. }
  14683. delete me._listeners;
  14684. helpers$1.each(listeners, function(listener, type) {
  14685. platform.removeEventListener(me, type, listener);
  14686. });
  14687. },
  14688. updateHoverStyle: function(elements, mode, enabled) {
  14689. var prefix = enabled ? 'set' : 'remove';
  14690. var element, i, ilen;
  14691. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  14692. element = elements[i];
  14693. if (element) {
  14694. this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);
  14695. }
  14696. }
  14697. if (mode === 'dataset') {
  14698. this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();
  14699. }
  14700. },
  14701. /**
  14702. * @private
  14703. */
  14704. eventHandler: function(e) {
  14705. var me = this;
  14706. var tooltip = me.tooltip;
  14707. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  14708. return;
  14709. }
  14710. // Buffer any update calls so that renders do not occur
  14711. me._bufferedRender = true;
  14712. me._bufferedRequest = null;
  14713. var changed = me.handleEvent(e);
  14714. // for smooth tooltip animations issue #4989
  14715. // the tooltip should be the source of change
  14716. // Animation check workaround:
  14717. // tooltip._start will be null when tooltip isn't animating
  14718. if (tooltip) {
  14719. changed = tooltip._start
  14720. ? tooltip.handleEvent(e)
  14721. : changed | tooltip.handleEvent(e);
  14722. }
  14723. core_plugins.notify(me, 'afterEvent', [e]);
  14724. var bufferedRequest = me._bufferedRequest;
  14725. if (bufferedRequest) {
  14726. // If we have an update that was triggered, we need to do a normal render
  14727. me.render(bufferedRequest);
  14728. } else if (changed && !me.animating) {
  14729. // If entering, leaving, or changing elements, animate the change via pivot
  14730. me.stop();
  14731. // We only need to render at this point. Updating will cause scales to be
  14732. // recomputed generating flicker & using more memory than necessary.
  14733. me.render({
  14734. duration: me.options.hover.animationDuration,
  14735. lazy: true
  14736. });
  14737. }
  14738. me._bufferedRender = false;
  14739. me._bufferedRequest = null;
  14740. return me;
  14741. },
  14742. /**
  14743. * Handle an event
  14744. * @private
  14745. * @param {IEvent} event the event to handle
  14746. * @return {boolean} true if the chart needs to re-render
  14747. */
  14748. handleEvent: function(e) {
  14749. var me = this;
  14750. var options = me.options || {};
  14751. var hoverOptions = options.hover;
  14752. var changed = false;
  14753. me.lastActive = me.lastActive || [];
  14754. // Find Active Elements for hover and tooltips
  14755. if (e.type === 'mouseout') {
  14756. me.active = [];
  14757. } else {
  14758. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  14759. }
  14760. // Invoke onHover hook
  14761. // Need to call with native event here to not break backwards compatibility
  14762. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  14763. if (e.type === 'mouseup' || e.type === 'click') {
  14764. if (options.onClick) {
  14765. // Use e.native here for backwards compatibility
  14766. options.onClick.call(me, e.native, me.active);
  14767. }
  14768. }
  14769. // Remove styling for last active (even if it may still be active)
  14770. if (me.lastActive.length) {
  14771. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  14772. }
  14773. // Built in hover styling
  14774. if (me.active.length && hoverOptions.mode) {
  14775. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  14776. }
  14777. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  14778. // Remember Last Actives
  14779. me.lastActive = me.active;
  14780. return changed;
  14781. }
  14782. });
  14783. /**
  14784. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  14785. * for backward compatibility. Though, it can still be useful for plugins that
  14786. * would need to work on multiple charts?!
  14787. */
  14788. Chart.instances = {};
  14789. var core_controller = Chart;
  14790. // DEPRECATIONS
  14791. /**
  14792. * Provided for backward compatibility, use Chart instead.
  14793. * @class Chart.Controller
  14794. * @deprecated since version 2.6
  14795. * @todo remove at version 3
  14796. * @private
  14797. */
  14798. Chart.Controller = Chart;
  14799. /**
  14800. * Provided for backward compatibility, not available anymore.
  14801. * @namespace Chart
  14802. * @deprecated since version 2.8
  14803. * @todo remove at version 3
  14804. * @private
  14805. */
  14806. Chart.types = {};
  14807. /**
  14808. * Provided for backward compatibility, not available anymore.
  14809. * @namespace Chart.helpers.configMerge
  14810. * @deprecated since version 2.8.0
  14811. * @todo remove at version 3
  14812. * @private
  14813. */
  14814. helpers$1.configMerge = mergeConfig;
  14815. /**
  14816. * Provided for backward compatibility, not available anymore.
  14817. * @namespace Chart.helpers.scaleMerge
  14818. * @deprecated since version 2.8.0
  14819. * @todo remove at version 3
  14820. * @private
  14821. */
  14822. helpers$1.scaleMerge = mergeScaleConfig;
  14823. var core_helpers = function() {
  14824. // -- Basic js utility methods
  14825. helpers$1.where = function(collection, filterCallback) {
  14826. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  14827. return collection.filter(filterCallback);
  14828. }
  14829. var filtered = [];
  14830. helpers$1.each(collection, function(item) {
  14831. if (filterCallback(item)) {
  14832. filtered.push(item);
  14833. }
  14834. });
  14835. return filtered;
  14836. };
  14837. helpers$1.findIndex = Array.prototype.findIndex ?
  14838. function(array, callback, scope) {
  14839. return array.findIndex(callback, scope);
  14840. } :
  14841. function(array, callback, scope) {
  14842. scope = scope === undefined ? array : scope;
  14843. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  14844. if (callback.call(scope, array[i], i, array)) {
  14845. return i;
  14846. }
  14847. }
  14848. return -1;
  14849. };
  14850. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  14851. // Default to start of the array
  14852. if (helpers$1.isNullOrUndef(startIndex)) {
  14853. startIndex = -1;
  14854. }
  14855. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  14856. var currentItem = arrayToSearch[i];
  14857. if (filterCallback(currentItem)) {
  14858. return currentItem;
  14859. }
  14860. }
  14861. };
  14862. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  14863. // Default to end of the array
  14864. if (helpers$1.isNullOrUndef(startIndex)) {
  14865. startIndex = arrayToSearch.length;
  14866. }
  14867. for (var i = startIndex - 1; i >= 0; i--) {
  14868. var currentItem = arrayToSearch[i];
  14869. if (filterCallback(currentItem)) {
  14870. return currentItem;
  14871. }
  14872. }
  14873. };
  14874. // -- Math methods
  14875. helpers$1.isNumber = function(n) {
  14876. return !isNaN(parseFloat(n)) && isFinite(n);
  14877. };
  14878. helpers$1.almostEquals = function(x, y, epsilon) {
  14879. return Math.abs(x - y) < epsilon;
  14880. };
  14881. helpers$1.almostWhole = function(x, epsilon) {
  14882. var rounded = Math.round(x);
  14883. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  14884. };
  14885. helpers$1.max = function(array) {
  14886. return array.reduce(function(max, value) {
  14887. if (!isNaN(value)) {
  14888. return Math.max(max, value);
  14889. }
  14890. return max;
  14891. }, Number.NEGATIVE_INFINITY);
  14892. };
  14893. helpers$1.min = function(array) {
  14894. return array.reduce(function(min, value) {
  14895. if (!isNaN(value)) {
  14896. return Math.min(min, value);
  14897. }
  14898. return min;
  14899. }, Number.POSITIVE_INFINITY);
  14900. };
  14901. helpers$1.sign = Math.sign ?
  14902. function(x) {
  14903. return Math.sign(x);
  14904. } :
  14905. function(x) {
  14906. x = +x; // convert to a number
  14907. if (x === 0 || isNaN(x)) {
  14908. return x;
  14909. }
  14910. return x > 0 ? 1 : -1;
  14911. };
  14912. helpers$1.toRadians = function(degrees) {
  14913. return degrees * (Math.PI / 180);
  14914. };
  14915. helpers$1.toDegrees = function(radians) {
  14916. return radians * (180 / Math.PI);
  14917. };
  14918. /**
  14919. * Returns the number of decimal places
  14920. * i.e. the number of digits after the decimal point, of the value of this Number.
  14921. * @param {number} x - A number.
  14922. * @returns {number} The number of decimal places.
  14923. * @private
  14924. */
  14925. helpers$1._decimalPlaces = function(x) {
  14926. if (!helpers$1.isFinite(x)) {
  14927. return;
  14928. }
  14929. var e = 1;
  14930. var p = 0;
  14931. while (Math.round(x * e) / e !== x) {
  14932. e *= 10;
  14933. p++;
  14934. }
  14935. return p;
  14936. };
  14937. // Gets the angle from vertical upright to the point about a centre.
  14938. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  14939. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  14940. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  14941. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  14942. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  14943. if (angle < (-0.5 * Math.PI)) {
  14944. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  14945. }
  14946. return {
  14947. angle: angle,
  14948. distance: radialDistanceFromCenter
  14949. };
  14950. };
  14951. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  14952. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  14953. };
  14954. /**
  14955. * Provided for backward compatibility, not available anymore
  14956. * @function Chart.helpers.aliasPixel
  14957. * @deprecated since version 2.8.0
  14958. * @todo remove at version 3
  14959. */
  14960. helpers$1.aliasPixel = function(pixelWidth) {
  14961. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  14962. };
  14963. /**
  14964. * Returns the aligned pixel value to avoid anti-aliasing blur
  14965. * @param {Chart} chart - The chart instance.
  14966. * @param {number} pixel - A pixel value.
  14967. * @param {number} width - The width of the element.
  14968. * @returns {number} The aligned pixel value.
  14969. * @private
  14970. */
  14971. helpers$1._alignPixel = function(chart, pixel, width) {
  14972. var devicePixelRatio = chart.currentDevicePixelRatio;
  14973. var halfWidth = width / 2;
  14974. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  14975. };
  14976. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  14977. // Props to Rob Spencer at scaled innovation for his post on splining between points
  14978. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  14979. // This function must also respect "skipped" points
  14980. var previous = firstPoint.skip ? middlePoint : firstPoint;
  14981. var current = middlePoint;
  14982. var next = afterPoint.skip ? middlePoint : afterPoint;
  14983. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  14984. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  14985. var s01 = d01 / (d01 + d12);
  14986. var s12 = d12 / (d01 + d12);
  14987. // If all points are the same, s01 & s02 will be inf
  14988. s01 = isNaN(s01) ? 0 : s01;
  14989. s12 = isNaN(s12) ? 0 : s12;
  14990. var fa = t * s01; // scaling factor for triangle Ta
  14991. var fb = t * s12;
  14992. return {
  14993. previous: {
  14994. x: current.x - fa * (next.x - previous.x),
  14995. y: current.y - fa * (next.y - previous.y)
  14996. },
  14997. next: {
  14998. x: current.x + fb * (next.x - previous.x),
  14999. y: current.y + fb * (next.y - previous.y)
  15000. }
  15001. };
  15002. };
  15003. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  15004. helpers$1.splineCurveMonotone = function(points) {
  15005. // This function calculates Bézier control points in a similar way than |splineCurve|,
  15006. // but preserves monotonicity of the provided data and ensures no local extremums are added
  15007. // between the dataset discrete points due to the interpolation.
  15008. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  15009. var pointsWithTangents = (points || []).map(function(point) {
  15010. return {
  15011. model: point._model,
  15012. deltaK: 0,
  15013. mK: 0
  15014. };
  15015. });
  15016. // Calculate slopes (deltaK) and initialize tangents (mK)
  15017. var pointsLen = pointsWithTangents.length;
  15018. var i, pointBefore, pointCurrent, pointAfter;
  15019. for (i = 0; i < pointsLen; ++i) {
  15020. pointCurrent = pointsWithTangents[i];
  15021. if (pointCurrent.model.skip) {
  15022. continue;
  15023. }
  15024. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  15025. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  15026. if (pointAfter && !pointAfter.model.skip) {
  15027. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  15028. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  15029. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  15030. }
  15031. if (!pointBefore || pointBefore.model.skip) {
  15032. pointCurrent.mK = pointCurrent.deltaK;
  15033. } else if (!pointAfter || pointAfter.model.skip) {
  15034. pointCurrent.mK = pointBefore.deltaK;
  15035. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  15036. pointCurrent.mK = 0;
  15037. } else {
  15038. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  15039. }
  15040. }
  15041. // Adjust tangents to ensure monotonic properties
  15042. var alphaK, betaK, tauK, squaredMagnitude;
  15043. for (i = 0; i < pointsLen - 1; ++i) {
  15044. pointCurrent = pointsWithTangents[i];
  15045. pointAfter = pointsWithTangents[i + 1];
  15046. if (pointCurrent.model.skip || pointAfter.model.skip) {
  15047. continue;
  15048. }
  15049. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  15050. pointCurrent.mK = pointAfter.mK = 0;
  15051. continue;
  15052. }
  15053. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  15054. betaK = pointAfter.mK / pointCurrent.deltaK;
  15055. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  15056. if (squaredMagnitude <= 9) {
  15057. continue;
  15058. }
  15059. tauK = 3 / Math.sqrt(squaredMagnitude);
  15060. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  15061. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  15062. }
  15063. // Compute control points
  15064. var deltaX;
  15065. for (i = 0; i < pointsLen; ++i) {
  15066. pointCurrent = pointsWithTangents[i];
  15067. if (pointCurrent.model.skip) {
  15068. continue;
  15069. }
  15070. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  15071. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  15072. if (pointBefore && !pointBefore.model.skip) {
  15073. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  15074. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  15075. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  15076. }
  15077. if (pointAfter && !pointAfter.model.skip) {
  15078. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  15079. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  15080. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  15081. }
  15082. }
  15083. };
  15084. helpers$1.nextItem = function(collection, index, loop) {
  15085. if (loop) {
  15086. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  15087. }
  15088. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  15089. };
  15090. helpers$1.previousItem = function(collection, index, loop) {
  15091. if (loop) {
  15092. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  15093. }
  15094. return index <= 0 ? collection[0] : collection[index - 1];
  15095. };
  15096. // Implementation of the nice number algorithm used in determining where axis labels will go
  15097. helpers$1.niceNum = function(range, round) {
  15098. var exponent = Math.floor(helpers$1.log10(range));
  15099. var fraction = range / Math.pow(10, exponent);
  15100. var niceFraction;
  15101. if (round) {
  15102. if (fraction < 1.5) {
  15103. niceFraction = 1;
  15104. } else if (fraction < 3) {
  15105. niceFraction = 2;
  15106. } else if (fraction < 7) {
  15107. niceFraction = 5;
  15108. } else {
  15109. niceFraction = 10;
  15110. }
  15111. } else if (fraction <= 1.0) {
  15112. niceFraction = 1;
  15113. } else if (fraction <= 2) {
  15114. niceFraction = 2;
  15115. } else if (fraction <= 5) {
  15116. niceFraction = 5;
  15117. } else {
  15118. niceFraction = 10;
  15119. }
  15120. return niceFraction * Math.pow(10, exponent);
  15121. };
  15122. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  15123. helpers$1.requestAnimFrame = (function() {
  15124. if (typeof window === 'undefined') {
  15125. return function(callback) {
  15126. callback();
  15127. };
  15128. }
  15129. return window.requestAnimationFrame ||
  15130. window.webkitRequestAnimationFrame ||
  15131. window.mozRequestAnimationFrame ||
  15132. window.oRequestAnimationFrame ||
  15133. window.msRequestAnimationFrame ||
  15134. function(callback) {
  15135. return window.setTimeout(callback, 1000 / 60);
  15136. };
  15137. }());
  15138. // -- DOM methods
  15139. helpers$1.getRelativePosition = function(evt, chart) {
  15140. var mouseX, mouseY;
  15141. var e = evt.originalEvent || evt;
  15142. var canvas = evt.target || evt.srcElement;
  15143. var boundingRect = canvas.getBoundingClientRect();
  15144. var touches = e.touches;
  15145. if (touches && touches.length > 0) {
  15146. mouseX = touches[0].clientX;
  15147. mouseY = touches[0].clientY;
  15148. } else {
  15149. mouseX = e.clientX;
  15150. mouseY = e.clientY;
  15151. }
  15152. // Scale mouse coordinates into canvas coordinates
  15153. // by following the pattern laid out by 'jerryj' in the comments of
  15154. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  15155. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  15156. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  15157. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  15158. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  15159. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  15160. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  15161. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  15162. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  15163. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  15164. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  15165. return {
  15166. x: mouseX,
  15167. y: mouseY
  15168. };
  15169. };
  15170. // Private helper function to convert max-width/max-height values that may be percentages into a number
  15171. function parseMaxStyle(styleValue, node, parentProperty) {
  15172. var valueInPixels;
  15173. if (typeof styleValue === 'string') {
  15174. valueInPixels = parseInt(styleValue, 10);
  15175. if (styleValue.indexOf('%') !== -1) {
  15176. // percentage * size in dimension
  15177. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  15178. }
  15179. } else {
  15180. valueInPixels = styleValue;
  15181. }
  15182. return valueInPixels;
  15183. }
  15184. /**
  15185. * Returns if the given value contains an effective constraint.
  15186. * @private
  15187. */
  15188. function isConstrainedValue(value) {
  15189. return value !== undefined && value !== null && value !== 'none';
  15190. }
  15191. /**
  15192. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  15193. * @param {HTMLElement} domNode - the node to check the constraint on
  15194. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  15195. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  15196. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  15197. */
  15198. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  15199. var view = document.defaultView;
  15200. var parentNode = helpers$1._getParentNode(domNode);
  15201. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  15202. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  15203. var hasCNode = isConstrainedValue(constrainedNode);
  15204. var hasCContainer = isConstrainedValue(constrainedContainer);
  15205. var infinity = Number.POSITIVE_INFINITY;
  15206. if (hasCNode || hasCContainer) {
  15207. return Math.min(
  15208. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  15209. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  15210. }
  15211. return 'none';
  15212. }
  15213. // returns Number or undefined if no constraint
  15214. helpers$1.getConstraintWidth = function(domNode) {
  15215. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  15216. };
  15217. // returns Number or undefined if no constraint
  15218. helpers$1.getConstraintHeight = function(domNode) {
  15219. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  15220. };
  15221. /**
  15222. * @private
  15223. */
  15224. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  15225. padding = helpers$1.getStyle(container, padding);
  15226. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  15227. };
  15228. /**
  15229. * @private
  15230. */
  15231. helpers$1._getParentNode = function(domNode) {
  15232. var parent = domNode.parentNode;
  15233. if (parent && parent.toString() === '[object ShadowRoot]') {
  15234. parent = parent.host;
  15235. }
  15236. return parent;
  15237. };
  15238. helpers$1.getMaximumWidth = function(domNode) {
  15239. var container = helpers$1._getParentNode(domNode);
  15240. if (!container) {
  15241. return domNode.clientWidth;
  15242. }
  15243. var clientWidth = container.clientWidth;
  15244. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  15245. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  15246. var w = clientWidth - paddingLeft - paddingRight;
  15247. var cw = helpers$1.getConstraintWidth(domNode);
  15248. return isNaN(cw) ? w : Math.min(w, cw);
  15249. };
  15250. helpers$1.getMaximumHeight = function(domNode) {
  15251. var container = helpers$1._getParentNode(domNode);
  15252. if (!container) {
  15253. return domNode.clientHeight;
  15254. }
  15255. var clientHeight = container.clientHeight;
  15256. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  15257. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  15258. var h = clientHeight - paddingTop - paddingBottom;
  15259. var ch = helpers$1.getConstraintHeight(domNode);
  15260. return isNaN(ch) ? h : Math.min(h, ch);
  15261. };
  15262. helpers$1.getStyle = function(el, property) {
  15263. return el.currentStyle ?
  15264. el.currentStyle[property] :
  15265. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  15266. };
  15267. helpers$1.retinaScale = function(chart, forceRatio) {
  15268. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  15269. if (pixelRatio === 1) {
  15270. return;
  15271. }
  15272. var canvas = chart.canvas;
  15273. var height = chart.height;
  15274. var width = chart.width;
  15275. canvas.height = height * pixelRatio;
  15276. canvas.width = width * pixelRatio;
  15277. chart.ctx.scale(pixelRatio, pixelRatio);
  15278. // If no style has been set on the canvas, the render size is used as display size,
  15279. // making the chart visually bigger, so let's enforce it to the "correct" values.
  15280. // See https://github.com/chartjs/Chart.js/issues/3575
  15281. if (!canvas.style.height && !canvas.style.width) {
  15282. canvas.style.height = height + 'px';
  15283. canvas.style.width = width + 'px';
  15284. }
  15285. };
  15286. // -- Canvas methods
  15287. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  15288. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  15289. };
  15290. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  15291. cache = cache || {};
  15292. var data = cache.data = cache.data || {};
  15293. var gc = cache.garbageCollect = cache.garbageCollect || [];
  15294. if (cache.font !== font) {
  15295. data = cache.data = {};
  15296. gc = cache.garbageCollect = [];
  15297. cache.font = font;
  15298. }
  15299. ctx.font = font;
  15300. var longest = 0;
  15301. var ilen = arrayOfThings.length;
  15302. var i, j, jlen, thing, nestedThing;
  15303. for (i = 0; i < ilen; i++) {
  15304. thing = arrayOfThings[i];
  15305. // Undefined strings and arrays should not be measured
  15306. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  15307. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  15308. } else if (helpers$1.isArray(thing)) {
  15309. // if it is an array lets measure each element
  15310. // to do maybe simplify this function a bit so we can do this more recursively?
  15311. for (j = 0, jlen = thing.length; j < jlen; j++) {
  15312. nestedThing = thing[j];
  15313. // Undefined strings and arrays should not be measured
  15314. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  15315. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  15316. }
  15317. }
  15318. }
  15319. }
  15320. var gcLen = gc.length / 2;
  15321. if (gcLen > arrayOfThings.length) {
  15322. for (i = 0; i < gcLen; i++) {
  15323. delete data[gc[i]];
  15324. }
  15325. gc.splice(0, gcLen);
  15326. }
  15327. return longest;
  15328. };
  15329. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  15330. var textWidth = data[string];
  15331. if (!textWidth) {
  15332. textWidth = data[string] = ctx.measureText(string).width;
  15333. gc.push(string);
  15334. }
  15335. if (textWidth > longest) {
  15336. longest = textWidth;
  15337. }
  15338. return longest;
  15339. };
  15340. /**
  15341. * @deprecated
  15342. */
  15343. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  15344. var numberOfLines = 1;
  15345. helpers$1.each(arrayOfThings, function(thing) {
  15346. if (helpers$1.isArray(thing)) {
  15347. if (thing.length > numberOfLines) {
  15348. numberOfLines = thing.length;
  15349. }
  15350. }
  15351. });
  15352. return numberOfLines;
  15353. };
  15354. helpers$1.color = !chartjsColor ?
  15355. function(value) {
  15356. console.error('Color.js not found!');
  15357. return value;
  15358. } :
  15359. function(value) {
  15360. /* global CanvasGradient */
  15361. if (value instanceof CanvasGradient) {
  15362. value = core_defaults.global.defaultColor;
  15363. }
  15364. return chartjsColor(value);
  15365. };
  15366. helpers$1.getHoverColor = function(colorValue) {
  15367. /* global CanvasPattern */
  15368. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  15369. colorValue :
  15370. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  15371. };
  15372. };
  15373. function abstract() {
  15374. throw new Error(
  15375. 'This method is not implemented: either no adapter can ' +
  15376. 'be found or an incomplete integration was provided.'
  15377. );
  15378. }
  15379. /**
  15380. * Date adapter (current used by the time scale)
  15381. * @namespace Chart._adapters._date
  15382. * @memberof Chart._adapters
  15383. * @private
  15384. */
  15385. /**
  15386. * Currently supported unit string values.
  15387. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  15388. * @memberof Chart._adapters._date
  15389. * @name Unit
  15390. */
  15391. /**
  15392. * @class
  15393. */
  15394. function DateAdapter(options) {
  15395. this.options = options || {};
  15396. }
  15397. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  15398. /**
  15399. * Returns a map of time formats for the supported formatting units defined
  15400. * in Unit as well as 'datetime' representing a detailed date/time string.
  15401. * @returns {{string: string}}
  15402. */
  15403. formats: abstract,
  15404. /**
  15405. * Parses the given `value` and return the associated timestamp.
  15406. * @param {any} value - the value to parse (usually comes from the data)
  15407. * @param {string} [format] - the expected data format
  15408. * @returns {(number|null)}
  15409. * @function
  15410. */
  15411. parse: abstract,
  15412. /**
  15413. * Returns the formatted date in the specified `format` for a given `timestamp`.
  15414. * @param {number} timestamp - the timestamp to format
  15415. * @param {string} format - the date/time token
  15416. * @return {string}
  15417. * @function
  15418. */
  15419. format: abstract,
  15420. /**
  15421. * Adds the specified `amount` of `unit` to the given `timestamp`.
  15422. * @param {number} timestamp - the input timestamp
  15423. * @param {number} amount - the amount to add
  15424. * @param {Unit} unit - the unit as string
  15425. * @return {number}
  15426. * @function
  15427. */
  15428. add: abstract,
  15429. /**
  15430. * Returns the number of `unit` between the given timestamps.
  15431. * @param {number} max - the input timestamp (reference)
  15432. * @param {number} min - the timestamp to substract
  15433. * @param {Unit} unit - the unit as string
  15434. * @return {number}
  15435. * @function
  15436. */
  15437. diff: abstract,
  15438. /**
  15439. * Returns start of `unit` for the given `timestamp`.
  15440. * @param {number} timestamp - the input timestamp
  15441. * @param {Unit} unit - the unit as string
  15442. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  15443. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  15444. * @function
  15445. */
  15446. startOf: abstract,
  15447. /**
  15448. * Returns end of `unit` for the given `timestamp`.
  15449. * @param {number} timestamp - the input timestamp
  15450. * @param {Unit} unit - the unit as string
  15451. * @function
  15452. */
  15453. endOf: abstract,
  15454. // DEPRECATIONS
  15455. /**
  15456. * Provided for backward compatibility for scale.getValueForPixel(),
  15457. * this method should be overridden only by the moment adapter.
  15458. * @deprecated since version 2.8.0
  15459. * @todo remove at version 3
  15460. * @private
  15461. */
  15462. _create: function(value) {
  15463. return value;
  15464. }
  15465. });
  15466. DateAdapter.override = function(members) {
  15467. helpers$1.extend(DateAdapter.prototype, members);
  15468. };
  15469. var _date = DateAdapter;
  15470. var core_adapters = {
  15471. _date: _date
  15472. };
  15473. /**
  15474. * Namespace to hold static tick generation functions
  15475. * @namespace Chart.Ticks
  15476. */
  15477. var core_ticks = {
  15478. /**
  15479. * Namespace to hold formatters for different types of ticks
  15480. * @namespace Chart.Ticks.formatters
  15481. */
  15482. formatters: {
  15483. /**
  15484. * Formatter for value labels
  15485. * @method Chart.Ticks.formatters.values
  15486. * @param value the value to display
  15487. * @return {string|string[]} the label to display
  15488. */
  15489. values: function(value) {
  15490. return helpers$1.isArray(value) ? value : '' + value;
  15491. },
  15492. /**
  15493. * Formatter for linear numeric ticks
  15494. * @method Chart.Ticks.formatters.linear
  15495. * @param tickValue {number} the value to be formatted
  15496. * @param index {number} the position of the tickValue parameter in the ticks array
  15497. * @param ticks {number[]} the list of ticks being converted
  15498. * @return {string} string representation of the tickValue parameter
  15499. */
  15500. linear: function(tickValue, index, ticks) {
  15501. // If we have lots of ticks, don't use the ones
  15502. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  15503. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  15504. if (Math.abs(delta) > 1) {
  15505. if (tickValue !== Math.floor(tickValue)) {
  15506. // not an integer
  15507. delta = tickValue - Math.floor(tickValue);
  15508. }
  15509. }
  15510. var logDelta = helpers$1.log10(Math.abs(delta));
  15511. var tickString = '';
  15512. if (tickValue !== 0) {
  15513. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  15514. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  15515. var logTick = helpers$1.log10(Math.abs(tickValue));
  15516. var numExponential = Math.floor(logTick) - Math.floor(logDelta);
  15517. numExponential = Math.max(Math.min(numExponential, 20), 0);
  15518. tickString = tickValue.toExponential(numExponential);
  15519. } else {
  15520. var numDecimal = -1 * Math.floor(logDelta);
  15521. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  15522. tickString = tickValue.toFixed(numDecimal);
  15523. }
  15524. } else {
  15525. tickString = '0'; // never show decimal places for 0
  15526. }
  15527. return tickString;
  15528. },
  15529. logarithmic: function(tickValue, index, ticks) {
  15530. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  15531. if (tickValue === 0) {
  15532. return '0';
  15533. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  15534. return tickValue.toExponential();
  15535. }
  15536. return '';
  15537. }
  15538. }
  15539. };
  15540. var isArray = helpers$1.isArray;
  15541. var isNullOrUndef = helpers$1.isNullOrUndef;
  15542. var valueOrDefault$a = helpers$1.valueOrDefault;
  15543. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  15544. core_defaults._set('scale', {
  15545. display: true,
  15546. position: 'left',
  15547. offset: false,
  15548. // grid line settings
  15549. gridLines: {
  15550. display: true,
  15551. color: 'rgba(0,0,0,0.1)',
  15552. lineWidth: 1,
  15553. drawBorder: true,
  15554. drawOnChartArea: true,
  15555. drawTicks: true,
  15556. tickMarkLength: 10,
  15557. zeroLineWidth: 1,
  15558. zeroLineColor: 'rgba(0,0,0,0.25)',
  15559. zeroLineBorderDash: [],
  15560. zeroLineBorderDashOffset: 0.0,
  15561. offsetGridLines: false,
  15562. borderDash: [],
  15563. borderDashOffset: 0.0
  15564. },
  15565. // scale label
  15566. scaleLabel: {
  15567. // display property
  15568. display: false,
  15569. // actual label
  15570. labelString: '',
  15571. // top/bottom padding
  15572. padding: {
  15573. top: 4,
  15574. bottom: 4
  15575. }
  15576. },
  15577. // label settings
  15578. ticks: {
  15579. beginAtZero: false,
  15580. minRotation: 0,
  15581. maxRotation: 50,
  15582. mirror: false,
  15583. padding: 0,
  15584. reverse: false,
  15585. display: true,
  15586. autoSkip: true,
  15587. autoSkipPadding: 0,
  15588. labelOffset: 0,
  15589. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  15590. callback: core_ticks.formatters.values,
  15591. minor: {},
  15592. major: {}
  15593. }
  15594. });
  15595. /** Returns a new array containing numItems from arr */
  15596. function sample(arr, numItems) {
  15597. var result = [];
  15598. var increment = arr.length / numItems;
  15599. var i = 0;
  15600. var len = arr.length;
  15601. for (; i < len; i += increment) {
  15602. result.push(arr[Math.floor(i)]);
  15603. }
  15604. return result;
  15605. }
  15606. function getPixelForGridLine(scale, index, offsetGridLines) {
  15607. var length = scale.getTicks().length;
  15608. var validIndex = Math.min(index, length - 1);
  15609. var lineValue = scale.getPixelForTick(validIndex);
  15610. var start = scale._startPixel;
  15611. var end = scale._endPixel;
  15612. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  15613. var offset;
  15614. if (offsetGridLines) {
  15615. if (length === 1) {
  15616. offset = Math.max(lineValue - start, end - lineValue);
  15617. } else if (index === 0) {
  15618. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  15619. } else {
  15620. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  15621. }
  15622. lineValue += validIndex < index ? offset : -offset;
  15623. // Return undefined if the pixel is out of the range
  15624. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  15625. return;
  15626. }
  15627. }
  15628. return lineValue;
  15629. }
  15630. function garbageCollect(caches, length) {
  15631. helpers$1.each(caches, function(cache) {
  15632. var gc = cache.gc;
  15633. var gcLen = gc.length / 2;
  15634. var i;
  15635. if (gcLen > length) {
  15636. for (i = 0; i < gcLen; ++i) {
  15637. delete cache.data[gc[i]];
  15638. }
  15639. gc.splice(0, gcLen);
  15640. }
  15641. });
  15642. }
  15643. /**
  15644. * Returns {width, height, offset} objects for the first, last, widest, highest tick
  15645. * labels where offset indicates the anchor point offset from the top in pixels.
  15646. */
  15647. function computeLabelSizes(ctx, tickFonts, ticks, caches) {
  15648. var length = ticks.length;
  15649. var widths = [];
  15650. var heights = [];
  15651. var offsets = [];
  15652. var widestLabelSize = 0;
  15653. var highestLabelSize = 0;
  15654. var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
  15655. for (i = 0; i < length; ++i) {
  15656. label = ticks[i].label;
  15657. tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
  15658. ctx.font = fontString = tickFont.string;
  15659. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  15660. lineHeight = tickFont.lineHeight;
  15661. width = height = 0;
  15662. // Undefined labels and arrays should not be measured
  15663. if (!isNullOrUndef(label) && !isArray(label)) {
  15664. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);
  15665. height = lineHeight;
  15666. } else if (isArray(label)) {
  15667. // if it is an array let's measure each element
  15668. for (j = 0, jlen = label.length; j < jlen; ++j) {
  15669. nestedLabel = label[j];
  15670. // Undefined labels and arrays should not be measured
  15671. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  15672. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  15673. height += lineHeight;
  15674. }
  15675. }
  15676. }
  15677. widths.push(width);
  15678. heights.push(height);
  15679. offsets.push(lineHeight / 2);
  15680. widestLabelSize = Math.max(width, widestLabelSize);
  15681. highestLabelSize = Math.max(height, highestLabelSize);
  15682. }
  15683. garbageCollect(caches, length);
  15684. widest = widths.indexOf(widestLabelSize);
  15685. highest = heights.indexOf(highestLabelSize);
  15686. function valueAt(idx) {
  15687. return {
  15688. width: widths[idx] || 0,
  15689. height: heights[idx] || 0,
  15690. offset: offsets[idx] || 0
  15691. };
  15692. }
  15693. return {
  15694. first: valueAt(0),
  15695. last: valueAt(length - 1),
  15696. widest: valueAt(widest),
  15697. highest: valueAt(highest)
  15698. };
  15699. }
  15700. function getTickMarkLength(options) {
  15701. return options.drawTicks ? options.tickMarkLength : 0;
  15702. }
  15703. function getScaleLabelHeight(options) {
  15704. var font, padding;
  15705. if (!options.display) {
  15706. return 0;
  15707. }
  15708. font = helpers$1.options._parseFont(options);
  15709. padding = helpers$1.options.toPadding(options.padding);
  15710. return font.lineHeight + padding.height;
  15711. }
  15712. function parseFontOptions(options, nestedOpts) {
  15713. return helpers$1.extend(helpers$1.options._parseFont({
  15714. fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),
  15715. fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),
  15716. fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),
  15717. lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)
  15718. }), {
  15719. color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])
  15720. });
  15721. }
  15722. function parseTickFontOptions(options) {
  15723. var minor = parseFontOptions(options, options.minor);
  15724. var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
  15725. return {minor: minor, major: major};
  15726. }
  15727. function nonSkipped(ticksToFilter) {
  15728. var filtered = [];
  15729. var item, index, len;
  15730. for (index = 0, len = ticksToFilter.length; index < len; ++index) {
  15731. item = ticksToFilter[index];
  15732. if (typeof item._index !== 'undefined') {
  15733. filtered.push(item);
  15734. }
  15735. }
  15736. return filtered;
  15737. }
  15738. function getEvenSpacing(arr) {
  15739. var len = arr.length;
  15740. var i, diff;
  15741. if (len < 2) {
  15742. return false;
  15743. }
  15744. for (diff = arr[0], i = 1; i < len; ++i) {
  15745. if (arr[i] - arr[i - 1] !== diff) {
  15746. return false;
  15747. }
  15748. }
  15749. return diff;
  15750. }
  15751. function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
  15752. var evenMajorSpacing = getEvenSpacing(majorIndices);
  15753. var spacing = (ticks.length - 1) / ticksLimit;
  15754. var factors, factor, i, ilen;
  15755. // If the major ticks are evenly spaced apart, place the minor ticks
  15756. // so that they divide the major ticks into even chunks
  15757. if (!evenMajorSpacing) {
  15758. return Math.max(spacing, 1);
  15759. }
  15760. factors = helpers$1.math._factorize(evenMajorSpacing);
  15761. for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
  15762. factor = factors[i];
  15763. if (factor > spacing) {
  15764. return factor;
  15765. }
  15766. }
  15767. return Math.max(spacing, 1);
  15768. }
  15769. function getMajorIndices(ticks) {
  15770. var result = [];
  15771. var i, ilen;
  15772. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  15773. if (ticks[i].major) {
  15774. result.push(i);
  15775. }
  15776. }
  15777. return result;
  15778. }
  15779. function skipMajors(ticks, majorIndices, spacing) {
  15780. var count = 0;
  15781. var next = majorIndices[0];
  15782. var i, tick;
  15783. spacing = Math.ceil(spacing);
  15784. for (i = 0; i < ticks.length; i++) {
  15785. tick = ticks[i];
  15786. if (i === next) {
  15787. tick._index = i;
  15788. count++;
  15789. next = majorIndices[count * spacing];
  15790. } else {
  15791. delete tick.label;
  15792. }
  15793. }
  15794. }
  15795. function skip(ticks, spacing, majorStart, majorEnd) {
  15796. var start = valueOrDefault$a(majorStart, 0);
  15797. var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);
  15798. var count = 0;
  15799. var length, i, tick, next;
  15800. spacing = Math.ceil(spacing);
  15801. if (majorEnd) {
  15802. length = majorEnd - majorStart;
  15803. spacing = length / Math.floor(length / spacing);
  15804. }
  15805. next = start;
  15806. while (next < 0) {
  15807. count++;
  15808. next = Math.round(start + count * spacing);
  15809. }
  15810. for (i = Math.max(start, 0); i < end; i++) {
  15811. tick = ticks[i];
  15812. if (i === next) {
  15813. tick._index = i;
  15814. count++;
  15815. next = Math.round(start + count * spacing);
  15816. } else {
  15817. delete tick.label;
  15818. }
  15819. }
  15820. }
  15821. var Scale = core_element.extend({
  15822. zeroLineIndex: 0,
  15823. /**
  15824. * Get the padding needed for the scale
  15825. * @method getPadding
  15826. * @private
  15827. * @returns {Padding} the necessary padding
  15828. */
  15829. getPadding: function() {
  15830. var me = this;
  15831. return {
  15832. left: me.paddingLeft || 0,
  15833. top: me.paddingTop || 0,
  15834. right: me.paddingRight || 0,
  15835. bottom: me.paddingBottom || 0
  15836. };
  15837. },
  15838. /**
  15839. * Returns the scale tick objects ({label, major})
  15840. * @since 2.7
  15841. */
  15842. getTicks: function() {
  15843. return this._ticks;
  15844. },
  15845. /**
  15846. * @private
  15847. */
  15848. _getLabels: function() {
  15849. var data = this.chart.data;
  15850. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  15851. },
  15852. // These methods are ordered by lifecyle. Utilities then follow.
  15853. // Any function defined here is inherited by all scale types.
  15854. // Any function can be extended by the scale type
  15855. /**
  15856. * Provided for backward compatibility, not available anymore
  15857. * @function Chart.Scale.mergeTicksOptions
  15858. * @deprecated since version 2.8.0
  15859. * @todo remove at version 3
  15860. */
  15861. mergeTicksOptions: function() {
  15862. // noop
  15863. },
  15864. beforeUpdate: function() {
  15865. helpers$1.callback(this.options.beforeUpdate, [this]);
  15866. },
  15867. /**
  15868. * @param {number} maxWidth - the max width in pixels
  15869. * @param {number} maxHeight - the max height in pixels
  15870. * @param {object} margins - the space between the edge of the other scales and edge of the chart
  15871. * This space comes from two sources:
  15872. * - padding - space that's required to show the labels at the edges of the scale
  15873. * - thickness of scales or legends in another orientation
  15874. */
  15875. update: function(maxWidth, maxHeight, margins) {
  15876. var me = this;
  15877. var tickOpts = me.options.ticks;
  15878. var sampleSize = tickOpts.sampleSize;
  15879. var i, ilen, labels, ticks, samplingEnabled;
  15880. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  15881. me.beforeUpdate();
  15882. // Absorb the master measurements
  15883. me.maxWidth = maxWidth;
  15884. me.maxHeight = maxHeight;
  15885. me.margins = helpers$1.extend({
  15886. left: 0,
  15887. right: 0,
  15888. top: 0,
  15889. bottom: 0
  15890. }, margins);
  15891. me._ticks = null;
  15892. me.ticks = null;
  15893. me._labelSizes = null;
  15894. me._maxLabelLines = 0;
  15895. me.longestLabelWidth = 0;
  15896. me.longestTextCache = me.longestTextCache || {};
  15897. me._gridLineItems = null;
  15898. me._labelItems = null;
  15899. // Dimensions
  15900. me.beforeSetDimensions();
  15901. me.setDimensions();
  15902. me.afterSetDimensions();
  15903. // Data min/max
  15904. me.beforeDataLimits();
  15905. me.determineDataLimits();
  15906. me.afterDataLimits();
  15907. // Ticks - `this.ticks` is now DEPRECATED!
  15908. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  15909. // and must not be accessed directly from outside this class. `this.ticks` being
  15910. // around for long time and not marked as private, we can't change its structure
  15911. // without unexpected breaking changes. If you need to access the scale ticks,
  15912. // use scale.getTicks() instead.
  15913. me.beforeBuildTicks();
  15914. // New implementations should return an array of objects but for BACKWARD COMPAT,
  15915. // we still support no return (`this.ticks` internally set by calling this method).
  15916. ticks = me.buildTicks() || [];
  15917. // Allow modification of ticks in callback.
  15918. ticks = me.afterBuildTicks(ticks) || ticks;
  15919. // Ensure ticks contains ticks in new tick format
  15920. if ((!ticks || !ticks.length) && me.ticks) {
  15921. ticks = [];
  15922. for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
  15923. ticks.push({
  15924. value: me.ticks[i],
  15925. major: false
  15926. });
  15927. }
  15928. }
  15929. me._ticks = ticks;
  15930. // Compute tick rotation and fit using a sampled subset of labels
  15931. // We generally don't need to compute the size of every single label for determining scale size
  15932. samplingEnabled = sampleSize < ticks.length;
  15933. labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);
  15934. // _configure is called twice, once here, once from core.controller.updateLayout.
  15935. // Here we haven't been positioned yet, but dimensions are correct.
  15936. // Variables set in _configure are needed for calculateTickRotation, and
  15937. // it's ok that coordinates are not correct there, only dimensions matter.
  15938. me._configure();
  15939. // Tick Rotation
  15940. me.beforeCalculateTickRotation();
  15941. me.calculateTickRotation();
  15942. me.afterCalculateTickRotation();
  15943. me.beforeFit();
  15944. me.fit();
  15945. me.afterFit();
  15946. // Auto-skip
  15947. me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;
  15948. if (samplingEnabled) {
  15949. // Generate labels using all non-skipped ticks
  15950. labels = me._convertTicksToLabels(me._ticksToDraw);
  15951. }
  15952. me.ticks = labels; // BACKWARD COMPATIBILITY
  15953. // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
  15954. me.afterUpdate();
  15955. // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
  15956. // make maxWidth and maxHeight private
  15957. return me.minSize;
  15958. },
  15959. /**
  15960. * @private
  15961. */
  15962. _configure: function() {
  15963. var me = this;
  15964. var reversePixels = me.options.ticks.reverse;
  15965. var startPixel, endPixel;
  15966. if (me.isHorizontal()) {
  15967. startPixel = me.left;
  15968. endPixel = me.right;
  15969. } else {
  15970. startPixel = me.top;
  15971. endPixel = me.bottom;
  15972. // by default vertical scales are from bottom to top, so pixels are reversed
  15973. reversePixels = !reversePixels;
  15974. }
  15975. me._startPixel = startPixel;
  15976. me._endPixel = endPixel;
  15977. me._reversePixels = reversePixels;
  15978. me._length = endPixel - startPixel;
  15979. },
  15980. afterUpdate: function() {
  15981. helpers$1.callback(this.options.afterUpdate, [this]);
  15982. },
  15983. //
  15984. beforeSetDimensions: function() {
  15985. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  15986. },
  15987. setDimensions: function() {
  15988. var me = this;
  15989. // Set the unconstrained dimension before label rotation
  15990. if (me.isHorizontal()) {
  15991. // Reset position before calculating rotation
  15992. me.width = me.maxWidth;
  15993. me.left = 0;
  15994. me.right = me.width;
  15995. } else {
  15996. me.height = me.maxHeight;
  15997. // Reset position before calculating rotation
  15998. me.top = 0;
  15999. me.bottom = me.height;
  16000. }
  16001. // Reset padding
  16002. me.paddingLeft = 0;
  16003. me.paddingTop = 0;
  16004. me.paddingRight = 0;
  16005. me.paddingBottom = 0;
  16006. },
  16007. afterSetDimensions: function() {
  16008. helpers$1.callback(this.options.afterSetDimensions, [this]);
  16009. },
  16010. // Data limits
  16011. beforeDataLimits: function() {
  16012. helpers$1.callback(this.options.beforeDataLimits, [this]);
  16013. },
  16014. determineDataLimits: helpers$1.noop,
  16015. afterDataLimits: function() {
  16016. helpers$1.callback(this.options.afterDataLimits, [this]);
  16017. },
  16018. //
  16019. beforeBuildTicks: function() {
  16020. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  16021. },
  16022. buildTicks: helpers$1.noop,
  16023. afterBuildTicks: function(ticks) {
  16024. var me = this;
  16025. // ticks is empty for old axis implementations here
  16026. if (isArray(ticks) && ticks.length) {
  16027. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  16028. }
  16029. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  16030. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  16031. return ticks;
  16032. },
  16033. beforeTickToLabelConversion: function() {
  16034. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  16035. },
  16036. convertTicksToLabels: function() {
  16037. var me = this;
  16038. // Convert ticks to strings
  16039. var tickOpts = me.options.ticks;
  16040. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  16041. },
  16042. afterTickToLabelConversion: function() {
  16043. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  16044. },
  16045. //
  16046. beforeCalculateTickRotation: function() {
  16047. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  16048. },
  16049. calculateTickRotation: function() {
  16050. var me = this;
  16051. var options = me.options;
  16052. var tickOpts = options.ticks;
  16053. var numTicks = me.getTicks().length;
  16054. var minRotation = tickOpts.minRotation || 0;
  16055. var maxRotation = tickOpts.maxRotation;
  16056. var labelRotation = minRotation;
  16057. var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
  16058. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  16059. me.labelRotation = minRotation;
  16060. return;
  16061. }
  16062. labelSizes = me._getLabelSizes();
  16063. maxLabelWidth = labelSizes.widest.width;
  16064. maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
  16065. // Estimate the width of each grid based on the canvas width, the maximum
  16066. // label width and the number of tick intervals
  16067. maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
  16068. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  16069. // Allow 3 pixels x2 padding either side for label readability
  16070. if (maxLabelWidth + 6 > tickWidth) {
  16071. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  16072. maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
  16073. - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
  16074. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  16075. labelRotation = helpers$1.toDegrees(Math.min(
  16076. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  16077. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  16078. ));
  16079. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  16080. }
  16081. me.labelRotation = labelRotation;
  16082. },
  16083. afterCalculateTickRotation: function() {
  16084. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  16085. },
  16086. //
  16087. beforeFit: function() {
  16088. helpers$1.callback(this.options.beforeFit, [this]);
  16089. },
  16090. fit: function() {
  16091. var me = this;
  16092. // Reset
  16093. var minSize = me.minSize = {
  16094. width: 0,
  16095. height: 0
  16096. };
  16097. var chart = me.chart;
  16098. var opts = me.options;
  16099. var tickOpts = opts.ticks;
  16100. var scaleLabelOpts = opts.scaleLabel;
  16101. var gridLineOpts = opts.gridLines;
  16102. var display = me._isVisible();
  16103. var isBottom = opts.position === 'bottom';
  16104. var isHorizontal = me.isHorizontal();
  16105. // Width
  16106. if (isHorizontal) {
  16107. minSize.width = me.maxWidth;
  16108. } else if (display) {
  16109. minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  16110. }
  16111. // height
  16112. if (!isHorizontal) {
  16113. minSize.height = me.maxHeight; // fill all the height
  16114. } else if (display) {
  16115. minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  16116. }
  16117. // Don't bother fitting the ticks if we are not showing the labels
  16118. if (tickOpts.display && display) {
  16119. var tickFonts = parseTickFontOptions(tickOpts);
  16120. var labelSizes = me._getLabelSizes();
  16121. var firstLabelSize = labelSizes.first;
  16122. var lastLabelSize = labelSizes.last;
  16123. var widestLabelSize = labelSizes.widest;
  16124. var highestLabelSize = labelSizes.highest;
  16125. var lineSpace = tickFonts.minor.lineHeight * 0.4;
  16126. var tickPadding = tickOpts.padding;
  16127. if (isHorizontal) {
  16128. // A horizontal axis is more constrained by the height.
  16129. var isRotated = me.labelRotation !== 0;
  16130. var angleRadians = helpers$1.toRadians(me.labelRotation);
  16131. var cosRotation = Math.cos(angleRadians);
  16132. var sinRotation = Math.sin(angleRadians);
  16133. var labelHeight = sinRotation * widestLabelSize.width
  16134. + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
  16135. + (isRotated ? 0 : lineSpace); // padding
  16136. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  16137. var offsetLeft = me.getPixelForTick(0) - me.left;
  16138. var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
  16139. var paddingLeft, paddingRight;
  16140. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  16141. // which means that the right padding is dominated by the font height
  16142. if (isRotated) {
  16143. paddingLeft = isBottom ?
  16144. cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
  16145. sinRotation * (firstLabelSize.height - firstLabelSize.offset);
  16146. paddingRight = isBottom ?
  16147. sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
  16148. cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
  16149. } else {
  16150. paddingLeft = firstLabelSize.width / 2;
  16151. paddingRight = lastLabelSize.width / 2;
  16152. }
  16153. // Adjust padding taking into account changes in offsets
  16154. // and add 3 px to move away from canvas edges
  16155. me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
  16156. me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
  16157. } else {
  16158. // A vertical axis is more constrained by the width. Labels are the
  16159. // dominant factor here, so get that length first and account for padding
  16160. var labelWidth = tickOpts.mirror ? 0 :
  16161. // use lineSpace for consistency with horizontal axis
  16162. // tickPadding is not implemented for horizontal
  16163. widestLabelSize.width + tickPadding + lineSpace;
  16164. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
  16165. me.paddingTop = firstLabelSize.height / 2;
  16166. me.paddingBottom = lastLabelSize.height / 2;
  16167. }
  16168. }
  16169. me.handleMargins();
  16170. if (isHorizontal) {
  16171. me.width = me._length = chart.width - me.margins.left - me.margins.right;
  16172. me.height = minSize.height;
  16173. } else {
  16174. me.width = minSize.width;
  16175. me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
  16176. }
  16177. },
  16178. /**
  16179. * Handle margins and padding interactions
  16180. * @private
  16181. */
  16182. handleMargins: function() {
  16183. var me = this;
  16184. if (me.margins) {
  16185. me.margins.left = Math.max(me.paddingLeft, me.margins.left);
  16186. me.margins.top = Math.max(me.paddingTop, me.margins.top);
  16187. me.margins.right = Math.max(me.paddingRight, me.margins.right);
  16188. me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
  16189. }
  16190. },
  16191. afterFit: function() {
  16192. helpers$1.callback(this.options.afterFit, [this]);
  16193. },
  16194. // Shared Methods
  16195. isHorizontal: function() {
  16196. var pos = this.options.position;
  16197. return pos === 'top' || pos === 'bottom';
  16198. },
  16199. isFullWidth: function() {
  16200. return this.options.fullWidth;
  16201. },
  16202. // 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
  16203. getRightValue: function(rawValue) {
  16204. // Null and undefined values first
  16205. if (isNullOrUndef(rawValue)) {
  16206. return NaN;
  16207. }
  16208. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  16209. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  16210. return NaN;
  16211. }
  16212. // If it is in fact an object, dive in one more level
  16213. if (rawValue) {
  16214. if (this.isHorizontal()) {
  16215. if (rawValue.x !== undefined) {
  16216. return this.getRightValue(rawValue.x);
  16217. }
  16218. } else if (rawValue.y !== undefined) {
  16219. return this.getRightValue(rawValue.y);
  16220. }
  16221. }
  16222. // Value is good, return it
  16223. return rawValue;
  16224. },
  16225. _convertTicksToLabels: function(ticks) {
  16226. var me = this;
  16227. var labels, i, ilen;
  16228. me.ticks = ticks.map(function(tick) {
  16229. return tick.value;
  16230. });
  16231. me.beforeTickToLabelConversion();
  16232. // New implementations should return the formatted tick labels but for BACKWARD
  16233. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  16234. // this method and supposed to contain only string values).
  16235. labels = me.convertTicksToLabels(ticks) || me.ticks;
  16236. me.afterTickToLabelConversion();
  16237. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  16238. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  16239. ticks[i].label = labels[i];
  16240. }
  16241. return labels;
  16242. },
  16243. /**
  16244. * @private
  16245. */
  16246. _getLabelSizes: function() {
  16247. var me = this;
  16248. var labelSizes = me._labelSizes;
  16249. if (!labelSizes) {
  16250. me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
  16251. me.longestLabelWidth = labelSizes.widest.width;
  16252. }
  16253. return labelSizes;
  16254. },
  16255. /**
  16256. * @private
  16257. */
  16258. _parseValue: function(value) {
  16259. var start, end, min, max;
  16260. if (isArray(value)) {
  16261. start = +this.getRightValue(value[0]);
  16262. end = +this.getRightValue(value[1]);
  16263. min = Math.min(start, end);
  16264. max = Math.max(start, end);
  16265. } else {
  16266. value = +this.getRightValue(value);
  16267. start = undefined;
  16268. end = value;
  16269. min = value;
  16270. max = value;
  16271. }
  16272. return {
  16273. min: min,
  16274. max: max,
  16275. start: start,
  16276. end: end
  16277. };
  16278. },
  16279. /**
  16280. * @private
  16281. */
  16282. _getScaleLabel: function(rawValue) {
  16283. var v = this._parseValue(rawValue);
  16284. if (v.start !== undefined) {
  16285. return '[' + v.start + ', ' + v.end + ']';
  16286. }
  16287. return +this.getRightValue(rawValue);
  16288. },
  16289. /**
  16290. * Used to get the value to display in the tooltip for the data at the given index
  16291. * @param index
  16292. * @param datasetIndex
  16293. */
  16294. getLabelForIndex: helpers$1.noop,
  16295. /**
  16296. * Returns the location of the given data point. Value can either be an index or a numerical value
  16297. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16298. * @param value
  16299. * @param index
  16300. * @param datasetIndex
  16301. */
  16302. getPixelForValue: helpers$1.noop,
  16303. /**
  16304. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  16305. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16306. * @param pixel
  16307. */
  16308. getValueForPixel: helpers$1.noop,
  16309. /**
  16310. * Returns the location of the tick at the given index
  16311. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16312. */
  16313. getPixelForTick: function(index) {
  16314. var me = this;
  16315. var offset = me.options.offset;
  16316. var numTicks = me._ticks.length;
  16317. var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
  16318. return index < 0 || index > numTicks - 1
  16319. ? null
  16320. : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
  16321. },
  16322. /**
  16323. * Utility for getting the pixel location of a percentage of scale
  16324. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16325. */
  16326. getPixelForDecimal: function(decimal) {
  16327. var me = this;
  16328. if (me._reversePixels) {
  16329. decimal = 1 - decimal;
  16330. }
  16331. return me._startPixel + decimal * me._length;
  16332. },
  16333. getDecimalForPixel: function(pixel) {
  16334. var decimal = (pixel - this._startPixel) / this._length;
  16335. return this._reversePixels ? 1 - decimal : decimal;
  16336. },
  16337. /**
  16338. * Returns the pixel for the minimum chart value
  16339. * The coordinate (0, 0) is at the upper-left corner of the canvas
  16340. */
  16341. getBasePixel: function() {
  16342. return this.getPixelForValue(this.getBaseValue());
  16343. },
  16344. getBaseValue: function() {
  16345. var me = this;
  16346. var min = me.min;
  16347. var max = me.max;
  16348. return me.beginAtZero ? 0 :
  16349. min < 0 && max < 0 ? max :
  16350. min > 0 && max > 0 ? min :
  16351. 0;
  16352. },
  16353. /**
  16354. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  16355. * @private
  16356. */
  16357. _autoSkip: function(ticks) {
  16358. var me = this;
  16359. var tickOpts = me.options.ticks;
  16360. var axisLength = me._length;
  16361. var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;
  16362. var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  16363. var numMajorIndices = majorIndices.length;
  16364. var first = majorIndices[0];
  16365. var last = majorIndices[numMajorIndices - 1];
  16366. var i, ilen, spacing, avgMajorSpacing;
  16367. // If there are too many major ticks to display them all
  16368. if (numMajorIndices > ticksLimit) {
  16369. skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);
  16370. return nonSkipped(ticks);
  16371. }
  16372. spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
  16373. if (numMajorIndices > 0) {
  16374. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  16375. skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);
  16376. }
  16377. avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;
  16378. skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  16379. skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  16380. return nonSkipped(ticks);
  16381. }
  16382. skip(ticks, spacing);
  16383. return nonSkipped(ticks);
  16384. },
  16385. /**
  16386. * @private
  16387. */
  16388. _tickSize: function() {
  16389. var me = this;
  16390. var optionTicks = me.options.ticks;
  16391. // Calculate space needed by label in axis direction.
  16392. var rot = helpers$1.toRadians(me.labelRotation);
  16393. var cos = Math.abs(Math.cos(rot));
  16394. var sin = Math.abs(Math.sin(rot));
  16395. var labelSizes = me._getLabelSizes();
  16396. var padding = optionTicks.autoSkipPadding || 0;
  16397. var w = labelSizes ? labelSizes.widest.width + padding : 0;
  16398. var h = labelSizes ? labelSizes.highest.height + padding : 0;
  16399. // Calculate space needed for 1 tick in axis direction.
  16400. return me.isHorizontal()
  16401. ? h * cos > w * sin ? w / cos : h / sin
  16402. : h * sin < w * cos ? h / cos : w / sin;
  16403. },
  16404. /**
  16405. * @private
  16406. */
  16407. _isVisible: function() {
  16408. var me = this;
  16409. var chart = me.chart;
  16410. var display = me.options.display;
  16411. var i, ilen, meta;
  16412. if (display !== 'auto') {
  16413. return !!display;
  16414. }
  16415. // When 'auto', the scale is visible if at least one associated dataset is visible.
  16416. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  16417. if (chart.isDatasetVisible(i)) {
  16418. meta = chart.getDatasetMeta(i);
  16419. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  16420. return true;
  16421. }
  16422. }
  16423. }
  16424. return false;
  16425. },
  16426. /**
  16427. * @private
  16428. */
  16429. _computeGridLineItems: function(chartArea) {
  16430. var me = this;
  16431. var chart = me.chart;
  16432. var options = me.options;
  16433. var gridLines = options.gridLines;
  16434. var position = options.position;
  16435. var offsetGridLines = gridLines.offsetGridLines;
  16436. var isHorizontal = me.isHorizontal();
  16437. var ticks = me._ticksToDraw;
  16438. var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
  16439. var tl = getTickMarkLength(gridLines);
  16440. var items = [];
  16441. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  16442. var axisHalfWidth = axisWidth / 2;
  16443. var alignPixel = helpers$1._alignPixel;
  16444. var alignBorderValue = function(pixel) {
  16445. return alignPixel(chart, pixel, axisWidth);
  16446. };
  16447. var borderValue, i, tick, lineValue, alignedLineValue;
  16448. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
  16449. if (position === 'top') {
  16450. borderValue = alignBorderValue(me.bottom);
  16451. ty1 = me.bottom - tl;
  16452. ty2 = borderValue - axisHalfWidth;
  16453. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  16454. y2 = chartArea.bottom;
  16455. } else if (position === 'bottom') {
  16456. borderValue = alignBorderValue(me.top);
  16457. y1 = chartArea.top;
  16458. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  16459. ty1 = borderValue + axisHalfWidth;
  16460. ty2 = me.top + tl;
  16461. } else if (position === 'left') {
  16462. borderValue = alignBorderValue(me.right);
  16463. tx1 = me.right - tl;
  16464. tx2 = borderValue - axisHalfWidth;
  16465. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  16466. x2 = chartArea.right;
  16467. } else {
  16468. borderValue = alignBorderValue(me.left);
  16469. x1 = chartArea.left;
  16470. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  16471. tx1 = borderValue + axisHalfWidth;
  16472. tx2 = me.left + tl;
  16473. }
  16474. for (i = 0; i < ticksLength; ++i) {
  16475. tick = ticks[i] || {};
  16476. // autoskipper skipped this tick (#4635)
  16477. if (isNullOrUndef(tick.label) && i < ticks.length) {
  16478. continue;
  16479. }
  16480. if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
  16481. // Draw the first index specially
  16482. lineWidth = gridLines.zeroLineWidth;
  16483. lineColor = gridLines.zeroLineColor;
  16484. borderDash = gridLines.zeroLineBorderDash || [];
  16485. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  16486. } else {
  16487. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);
  16488. lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');
  16489. borderDash = gridLines.borderDash || [];
  16490. borderDashOffset = gridLines.borderDashOffset || 0.0;
  16491. }
  16492. lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
  16493. // Skip if the pixel is out of the range
  16494. if (lineValue === undefined) {
  16495. continue;
  16496. }
  16497. alignedLineValue = alignPixel(chart, lineValue, lineWidth);
  16498. if (isHorizontal) {
  16499. tx1 = tx2 = x1 = x2 = alignedLineValue;
  16500. } else {
  16501. ty1 = ty2 = y1 = y2 = alignedLineValue;
  16502. }
  16503. items.push({
  16504. tx1: tx1,
  16505. ty1: ty1,
  16506. tx2: tx2,
  16507. ty2: ty2,
  16508. x1: x1,
  16509. y1: y1,
  16510. x2: x2,
  16511. y2: y2,
  16512. width: lineWidth,
  16513. color: lineColor,
  16514. borderDash: borderDash,
  16515. borderDashOffset: borderDashOffset,
  16516. });
  16517. }
  16518. items.ticksLength = ticksLength;
  16519. items.borderValue = borderValue;
  16520. return items;
  16521. },
  16522. /**
  16523. * @private
  16524. */
  16525. _computeLabelItems: function() {
  16526. var me = this;
  16527. var options = me.options;
  16528. var optionTicks = options.ticks;
  16529. var position = options.position;
  16530. var isMirrored = optionTicks.mirror;
  16531. var isHorizontal = me.isHorizontal();
  16532. var ticks = me._ticksToDraw;
  16533. var fonts = parseTickFontOptions(optionTicks);
  16534. var tickPadding = optionTicks.padding;
  16535. var tl = getTickMarkLength(options.gridLines);
  16536. var rotation = -helpers$1.toRadians(me.labelRotation);
  16537. var items = [];
  16538. var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  16539. if (position === 'top') {
  16540. y = me.bottom - tl - tickPadding;
  16541. textAlign = !rotation ? 'center' : 'left';
  16542. } else if (position === 'bottom') {
  16543. y = me.top + tl + tickPadding;
  16544. textAlign = !rotation ? 'center' : 'right';
  16545. } else if (position === 'left') {
  16546. x = me.right - (isMirrored ? 0 : tl) - tickPadding;
  16547. textAlign = isMirrored ? 'left' : 'right';
  16548. } else {
  16549. x = me.left + (isMirrored ? 0 : tl) + tickPadding;
  16550. textAlign = isMirrored ? 'right' : 'left';
  16551. }
  16552. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  16553. tick = ticks[i];
  16554. label = tick.label;
  16555. // autoskipper skipped this tick (#4635)
  16556. if (isNullOrUndef(label)) {
  16557. continue;
  16558. }
  16559. pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
  16560. font = tick.major ? fonts.major : fonts.minor;
  16561. lineHeight = font.lineHeight;
  16562. lineCount = isArray(label) ? label.length : 1;
  16563. if (isHorizontal) {
  16564. x = pixel;
  16565. textOffset = position === 'top'
  16566. ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight
  16567. : (!rotation ? 0.5 : 0) * lineHeight;
  16568. } else {
  16569. y = pixel;
  16570. textOffset = (1 - lineCount) * lineHeight / 2;
  16571. }
  16572. items.push({
  16573. x: x,
  16574. y: y,
  16575. rotation: rotation,
  16576. label: label,
  16577. font: font,
  16578. textOffset: textOffset,
  16579. textAlign: textAlign
  16580. });
  16581. }
  16582. return items;
  16583. },
  16584. /**
  16585. * @private
  16586. */
  16587. _drawGrid: function(chartArea) {
  16588. var me = this;
  16589. var gridLines = me.options.gridLines;
  16590. if (!gridLines.display) {
  16591. return;
  16592. }
  16593. var ctx = me.ctx;
  16594. var chart = me.chart;
  16595. var alignPixel = helpers$1._alignPixel;
  16596. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  16597. var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  16598. var width, color, i, ilen, item;
  16599. for (i = 0, ilen = items.length; i < ilen; ++i) {
  16600. item = items[i];
  16601. width = item.width;
  16602. color = item.color;
  16603. if (width && color) {
  16604. ctx.save();
  16605. ctx.lineWidth = width;
  16606. ctx.strokeStyle = color;
  16607. if (ctx.setLineDash) {
  16608. ctx.setLineDash(item.borderDash);
  16609. ctx.lineDashOffset = item.borderDashOffset;
  16610. }
  16611. ctx.beginPath();
  16612. if (gridLines.drawTicks) {
  16613. ctx.moveTo(item.tx1, item.ty1);
  16614. ctx.lineTo(item.tx2, item.ty2);
  16615. }
  16616. if (gridLines.drawOnChartArea) {
  16617. ctx.moveTo(item.x1, item.y1);
  16618. ctx.lineTo(item.x2, item.y2);
  16619. }
  16620. ctx.stroke();
  16621. ctx.restore();
  16622. }
  16623. }
  16624. if (axisWidth) {
  16625. // Draw the line at the edge of the axis
  16626. var firstLineWidth = axisWidth;
  16627. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);
  16628. var borderValue = items.borderValue;
  16629. var x1, x2, y1, y2;
  16630. if (me.isHorizontal()) {
  16631. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  16632. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  16633. y1 = y2 = borderValue;
  16634. } else {
  16635. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  16636. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  16637. x1 = x2 = borderValue;
  16638. }
  16639. ctx.lineWidth = axisWidth;
  16640. ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  16641. ctx.beginPath();
  16642. ctx.moveTo(x1, y1);
  16643. ctx.lineTo(x2, y2);
  16644. ctx.stroke();
  16645. }
  16646. },
  16647. /**
  16648. * @private
  16649. */
  16650. _drawLabels: function() {
  16651. var me = this;
  16652. var optionTicks = me.options.ticks;
  16653. if (!optionTicks.display) {
  16654. return;
  16655. }
  16656. var ctx = me.ctx;
  16657. var items = me._labelItems || (me._labelItems = me._computeLabelItems());
  16658. var i, j, ilen, jlen, item, tickFont, label, y;
  16659. for (i = 0, ilen = items.length; i < ilen; ++i) {
  16660. item = items[i];
  16661. tickFont = item.font;
  16662. // Make sure we draw text in the correct color and font
  16663. ctx.save();
  16664. ctx.translate(item.x, item.y);
  16665. ctx.rotate(item.rotation);
  16666. ctx.font = tickFont.string;
  16667. ctx.fillStyle = tickFont.color;
  16668. ctx.textBaseline = 'middle';
  16669. ctx.textAlign = item.textAlign;
  16670. label = item.label;
  16671. y = item.textOffset;
  16672. if (isArray(label)) {
  16673. for (j = 0, jlen = label.length; j < jlen; ++j) {
  16674. // We just make sure the multiline element is a string here..
  16675. ctx.fillText('' + label[j], 0, y);
  16676. y += tickFont.lineHeight;
  16677. }
  16678. } else {
  16679. ctx.fillText(label, 0, y);
  16680. }
  16681. ctx.restore();
  16682. }
  16683. },
  16684. /**
  16685. * @private
  16686. */
  16687. _drawTitle: function() {
  16688. var me = this;
  16689. var ctx = me.ctx;
  16690. var options = me.options;
  16691. var scaleLabel = options.scaleLabel;
  16692. if (!scaleLabel.display) {
  16693. return;
  16694. }
  16695. var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);
  16696. var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);
  16697. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  16698. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  16699. var position = options.position;
  16700. var rotation = 0;
  16701. var scaleLabelX, scaleLabelY;
  16702. if (me.isHorizontal()) {
  16703. scaleLabelX = me.left + me.width / 2; // midpoint of the width
  16704. scaleLabelY = position === 'bottom'
  16705. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  16706. : me.top + halfLineHeight + scaleLabelPadding.top;
  16707. } else {
  16708. var isLeft = position === 'left';
  16709. scaleLabelX = isLeft
  16710. ? me.left + halfLineHeight + scaleLabelPadding.top
  16711. : me.right - halfLineHeight - scaleLabelPadding.top;
  16712. scaleLabelY = me.top + me.height / 2;
  16713. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  16714. }
  16715. ctx.save();
  16716. ctx.translate(scaleLabelX, scaleLabelY);
  16717. ctx.rotate(rotation);
  16718. ctx.textAlign = 'center';
  16719. ctx.textBaseline = 'middle';
  16720. ctx.fillStyle = scaleLabelFontColor; // render in correct colour
  16721. ctx.font = scaleLabelFont.string;
  16722. ctx.fillText(scaleLabel.labelString, 0, 0);
  16723. ctx.restore();
  16724. },
  16725. draw: function(chartArea) {
  16726. var me = this;
  16727. if (!me._isVisible()) {
  16728. return;
  16729. }
  16730. me._drawGrid(chartArea);
  16731. me._drawTitle();
  16732. me._drawLabels();
  16733. },
  16734. /**
  16735. * @private
  16736. */
  16737. _layers: function() {
  16738. var me = this;
  16739. var opts = me.options;
  16740. var tz = opts.ticks && opts.ticks.z || 0;
  16741. var gz = opts.gridLines && opts.gridLines.z || 0;
  16742. if (!me._isVisible() || tz === gz || me.draw !== me._draw) {
  16743. // backward compatibility: draw has been overridden by custom scale
  16744. return [{
  16745. z: tz,
  16746. draw: function() {
  16747. me.draw.apply(me, arguments);
  16748. }
  16749. }];
  16750. }
  16751. return [{
  16752. z: gz,
  16753. draw: function() {
  16754. me._drawGrid.apply(me, arguments);
  16755. me._drawTitle.apply(me, arguments);
  16756. }
  16757. }, {
  16758. z: tz,
  16759. draw: function() {
  16760. me._drawLabels.apply(me, arguments);
  16761. }
  16762. }];
  16763. },
  16764. /**
  16765. * @private
  16766. */
  16767. _getMatchingVisibleMetas: function(type) {
  16768. var me = this;
  16769. var isHorizontal = me.isHorizontal();
  16770. return me.chart._getSortedVisibleDatasetMetas()
  16771. .filter(function(meta) {
  16772. return (!type || meta.type === type)
  16773. && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);
  16774. });
  16775. }
  16776. });
  16777. Scale.prototype._draw = Scale.prototype.draw;
  16778. var core_scale = Scale;
  16779. var isNullOrUndef$1 = helpers$1.isNullOrUndef;
  16780. var defaultConfig = {
  16781. position: 'bottom'
  16782. };
  16783. var scale_category = core_scale.extend({
  16784. determineDataLimits: function() {
  16785. var me = this;
  16786. var labels = me._getLabels();
  16787. var ticksOpts = me.options.ticks;
  16788. var min = ticksOpts.min;
  16789. var max = ticksOpts.max;
  16790. var minIndex = 0;
  16791. var maxIndex = labels.length - 1;
  16792. var findIndex;
  16793. if (min !== undefined) {
  16794. // user specified min value
  16795. findIndex = labels.indexOf(min);
  16796. if (findIndex >= 0) {
  16797. minIndex = findIndex;
  16798. }
  16799. }
  16800. if (max !== undefined) {
  16801. // user specified max value
  16802. findIndex = labels.indexOf(max);
  16803. if (findIndex >= 0) {
  16804. maxIndex = findIndex;
  16805. }
  16806. }
  16807. me.minIndex = minIndex;
  16808. me.maxIndex = maxIndex;
  16809. me.min = labels[minIndex];
  16810. me.max = labels[maxIndex];
  16811. },
  16812. buildTicks: function() {
  16813. var me = this;
  16814. var labels = me._getLabels();
  16815. var minIndex = me.minIndex;
  16816. var maxIndex = me.maxIndex;
  16817. // If we are viewing some subset of labels, slice the original array
  16818. me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);
  16819. },
  16820. getLabelForIndex: function(index, datasetIndex) {
  16821. var me = this;
  16822. var chart = me.chart;
  16823. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  16824. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  16825. }
  16826. return me._getLabels()[index];
  16827. },
  16828. _configure: function() {
  16829. var me = this;
  16830. var offset = me.options.offset;
  16831. var ticks = me.ticks;
  16832. core_scale.prototype._configure.call(me);
  16833. if (!me.isHorizontal()) {
  16834. // For backward compatibility, vertical category scale reverse is inverted.
  16835. me._reversePixels = !me._reversePixels;
  16836. }
  16837. if (!ticks) {
  16838. return;
  16839. }
  16840. me._startValue = me.minIndex - (offset ? 0.5 : 0);
  16841. me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);
  16842. },
  16843. // Used to get data value locations. Value can either be an index or a numerical value
  16844. getPixelForValue: function(value, index, datasetIndex) {
  16845. var me = this;
  16846. var valueCategory, labels, idx;
  16847. if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {
  16848. value = me.chart.data.datasets[datasetIndex].data[index];
  16849. }
  16850. // If value is a data object, then index is the index in the data array,
  16851. // not the index of the scale. We need to change that.
  16852. if (!isNullOrUndef$1(value)) {
  16853. valueCategory = me.isHorizontal() ? value.x : value.y;
  16854. }
  16855. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  16856. labels = me._getLabels();
  16857. value = helpers$1.valueOrDefault(valueCategory, value);
  16858. idx = labels.indexOf(value);
  16859. index = idx !== -1 ? idx : index;
  16860. if (isNaN(index)) {
  16861. index = value;
  16862. }
  16863. }
  16864. return me.getPixelForDecimal((index - me._startValue) / me._valueRange);
  16865. },
  16866. getPixelForTick: function(index) {
  16867. var ticks = this.ticks;
  16868. return index < 0 || index > ticks.length - 1
  16869. ? null
  16870. : this.getPixelForValue(ticks[index], index + this.minIndex);
  16871. },
  16872. getValueForPixel: function(pixel) {
  16873. var me = this;
  16874. var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  16875. return Math.min(Math.max(value, 0), me.ticks.length - 1);
  16876. },
  16877. getBasePixel: function() {
  16878. return this.bottom;
  16879. }
  16880. });
  16881. // INTERNAL: static default options, registered in src/index.js
  16882. var _defaults = defaultConfig;
  16883. scale_category._defaults = _defaults;
  16884. var noop = helpers$1.noop;
  16885. var isNullOrUndef$2 = helpers$1.isNullOrUndef;
  16886. /**
  16887. * Generate a set of linear ticks
  16888. * @param generationOptions the options used to generate the ticks
  16889. * @param dataRange the range of the data
  16890. * @returns {number[]} array of tick values
  16891. */
  16892. function generateTicks(generationOptions, dataRange) {
  16893. var ticks = [];
  16894. // To get a "nice" value for the tick spacing, we will use the appropriately named
  16895. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  16896. // for details.
  16897. var MIN_SPACING = 1e-14;
  16898. var stepSize = generationOptions.stepSize;
  16899. var unit = stepSize || 1;
  16900. var maxNumSpaces = generationOptions.maxTicks - 1;
  16901. var min = generationOptions.min;
  16902. var max = generationOptions.max;
  16903. var precision = generationOptions.precision;
  16904. var rmin = dataRange.min;
  16905. var rmax = dataRange.max;
  16906. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  16907. var factor, niceMin, niceMax, numSpaces;
  16908. // Beyond MIN_SPACING floating point numbers being to lose precision
  16909. // such that we can't do the math necessary to generate ticks
  16910. if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {
  16911. return [rmin, rmax];
  16912. }
  16913. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  16914. if (numSpaces > maxNumSpaces) {
  16915. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  16916. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  16917. }
  16918. if (stepSize || isNullOrUndef$2(precision)) {
  16919. // If a precision is not specified, calculate factor based on spacing
  16920. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  16921. } else {
  16922. // If the user specified a precision, round to that number of decimal places
  16923. factor = Math.pow(10, precision);
  16924. spacing = Math.ceil(spacing * factor) / factor;
  16925. }
  16926. niceMin = Math.floor(rmin / spacing) * spacing;
  16927. niceMax = Math.ceil(rmax / spacing) * spacing;
  16928. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  16929. if (stepSize) {
  16930. // If very close to our whole number, use it.
  16931. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  16932. niceMin = min;
  16933. }
  16934. if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  16935. niceMax = max;
  16936. }
  16937. }
  16938. numSpaces = (niceMax - niceMin) / spacing;
  16939. // If very close to our rounded value, use it.
  16940. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  16941. numSpaces = Math.round(numSpaces);
  16942. } else {
  16943. numSpaces = Math.ceil(numSpaces);
  16944. }
  16945. niceMin = Math.round(niceMin * factor) / factor;
  16946. niceMax = Math.round(niceMax * factor) / factor;
  16947. ticks.push(isNullOrUndef$2(min) ? niceMin : min);
  16948. for (var j = 1; j < numSpaces; ++j) {
  16949. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  16950. }
  16951. ticks.push(isNullOrUndef$2(max) ? niceMax : max);
  16952. return ticks;
  16953. }
  16954. var scale_linearbase = core_scale.extend({
  16955. getRightValue: function(value) {
  16956. if (typeof value === 'string') {
  16957. return +value;
  16958. }
  16959. return core_scale.prototype.getRightValue.call(this, value);
  16960. },
  16961. handleTickRangeOptions: function() {
  16962. var me = this;
  16963. var opts = me.options;
  16964. var tickOpts = opts.ticks;
  16965. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  16966. // do nothing since that would make the chart weird. If the user really wants a weird chart
  16967. // axis, they can manually override it
  16968. if (tickOpts.beginAtZero) {
  16969. var minSign = helpers$1.sign(me.min);
  16970. var maxSign = helpers$1.sign(me.max);
  16971. if (minSign < 0 && maxSign < 0) {
  16972. // move the top up to 0
  16973. me.max = 0;
  16974. } else if (minSign > 0 && maxSign > 0) {
  16975. // move the bottom down to 0
  16976. me.min = 0;
  16977. }
  16978. }
  16979. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  16980. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  16981. if (tickOpts.min !== undefined) {
  16982. me.min = tickOpts.min;
  16983. } else if (tickOpts.suggestedMin !== undefined) {
  16984. if (me.min === null) {
  16985. me.min = tickOpts.suggestedMin;
  16986. } else {
  16987. me.min = Math.min(me.min, tickOpts.suggestedMin);
  16988. }
  16989. }
  16990. if (tickOpts.max !== undefined) {
  16991. me.max = tickOpts.max;
  16992. } else if (tickOpts.suggestedMax !== undefined) {
  16993. if (me.max === null) {
  16994. me.max = tickOpts.suggestedMax;
  16995. } else {
  16996. me.max = Math.max(me.max, tickOpts.suggestedMax);
  16997. }
  16998. }
  16999. if (setMin !== setMax) {
  17000. // We set the min or the max but not both.
  17001. // So ensure that our range is good
  17002. // Inverted or 0 length range can happen when
  17003. // ticks.min is set, and no datasets are visible
  17004. if (me.min >= me.max) {
  17005. if (setMin) {
  17006. me.max = me.min + 1;
  17007. } else {
  17008. me.min = me.max - 1;
  17009. }
  17010. }
  17011. }
  17012. if (me.min === me.max) {
  17013. me.max++;
  17014. if (!tickOpts.beginAtZero) {
  17015. me.min--;
  17016. }
  17017. }
  17018. },
  17019. getTickLimit: function() {
  17020. var me = this;
  17021. var tickOpts = me.options.ticks;
  17022. var stepSize = tickOpts.stepSize;
  17023. var maxTicksLimit = tickOpts.maxTicksLimit;
  17024. var maxTicks;
  17025. if (stepSize) {
  17026. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  17027. } else {
  17028. maxTicks = me._computeTickLimit();
  17029. maxTicksLimit = maxTicksLimit || 11;
  17030. }
  17031. if (maxTicksLimit) {
  17032. maxTicks = Math.min(maxTicksLimit, maxTicks);
  17033. }
  17034. return maxTicks;
  17035. },
  17036. _computeTickLimit: function() {
  17037. return Number.POSITIVE_INFINITY;
  17038. },
  17039. handleDirectionalChanges: noop,
  17040. buildTicks: function() {
  17041. var me = this;
  17042. var opts = me.options;
  17043. var tickOpts = opts.ticks;
  17044. // Figure out what the max number of ticks we can support it is based on the size of
  17045. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  17046. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  17047. // the graph. Make sure we always have at least 2 ticks
  17048. var maxTicks = me.getTickLimit();
  17049. maxTicks = Math.max(2, maxTicks);
  17050. var numericGeneratorOptions = {
  17051. maxTicks: maxTicks,
  17052. min: tickOpts.min,
  17053. max: tickOpts.max,
  17054. precision: tickOpts.precision,
  17055. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  17056. };
  17057. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  17058. me.handleDirectionalChanges();
  17059. // At this point, we need to update our max and min given the tick values since we have expanded the
  17060. // range of the scale
  17061. me.max = helpers$1.max(ticks);
  17062. me.min = helpers$1.min(ticks);
  17063. if (tickOpts.reverse) {
  17064. ticks.reverse();
  17065. me.start = me.max;
  17066. me.end = me.min;
  17067. } else {
  17068. me.start = me.min;
  17069. me.end = me.max;
  17070. }
  17071. },
  17072. convertTicksToLabels: function() {
  17073. var me = this;
  17074. me.ticksAsNumbers = me.ticks.slice();
  17075. me.zeroLineIndex = me.ticks.indexOf(0);
  17076. core_scale.prototype.convertTicksToLabels.call(me);
  17077. },
  17078. _configure: function() {
  17079. var me = this;
  17080. var ticks = me.getTicks();
  17081. var start = me.min;
  17082. var end = me.max;
  17083. var offset;
  17084. core_scale.prototype._configure.call(me);
  17085. if (me.options.offset && ticks.length) {
  17086. offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  17087. start -= offset;
  17088. end += offset;
  17089. }
  17090. me._startValue = start;
  17091. me._endValue = end;
  17092. me._valueRange = end - start;
  17093. }
  17094. });
  17095. var defaultConfig$1 = {
  17096. position: 'left',
  17097. ticks: {
  17098. callback: core_ticks.formatters.linear
  17099. }
  17100. };
  17101. var DEFAULT_MIN = 0;
  17102. var DEFAULT_MAX = 1;
  17103. function getOrCreateStack(stacks, stacked, meta) {
  17104. var key = [
  17105. meta.type,
  17106. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  17107. stacked === undefined && meta.stack === undefined ? meta.index : '',
  17108. meta.stack
  17109. ].join('.');
  17110. if (stacks[key] === undefined) {
  17111. stacks[key] = {
  17112. pos: [],
  17113. neg: []
  17114. };
  17115. }
  17116. return stacks[key];
  17117. }
  17118. function stackData(scale, stacks, meta, data) {
  17119. var opts = scale.options;
  17120. var stacked = opts.stacked;
  17121. var stack = getOrCreateStack(stacks, stacked, meta);
  17122. var pos = stack.pos;
  17123. var neg = stack.neg;
  17124. var ilen = data.length;
  17125. var i, value;
  17126. for (i = 0; i < ilen; ++i) {
  17127. value = scale._parseValue(data[i]);
  17128. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  17129. continue;
  17130. }
  17131. pos[i] = pos[i] || 0;
  17132. neg[i] = neg[i] || 0;
  17133. if (opts.relativePoints) {
  17134. pos[i] = 100;
  17135. } else if (value.min < 0 || value.max < 0) {
  17136. neg[i] += value.min;
  17137. } else {
  17138. pos[i] += value.max;
  17139. }
  17140. }
  17141. }
  17142. function updateMinMax(scale, meta, data) {
  17143. var ilen = data.length;
  17144. var i, value;
  17145. for (i = 0; i < ilen; ++i) {
  17146. value = scale._parseValue(data[i]);
  17147. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  17148. continue;
  17149. }
  17150. scale.min = Math.min(scale.min, value.min);
  17151. scale.max = Math.max(scale.max, value.max);
  17152. }
  17153. }
  17154. var scale_linear = scale_linearbase.extend({
  17155. determineDataLimits: function() {
  17156. var me = this;
  17157. var opts = me.options;
  17158. var chart = me.chart;
  17159. var datasets = chart.data.datasets;
  17160. var metasets = me._getMatchingVisibleMetas();
  17161. var hasStacks = opts.stacked;
  17162. var stacks = {};
  17163. var ilen = metasets.length;
  17164. var i, meta, data, values;
  17165. me.min = Number.POSITIVE_INFINITY;
  17166. me.max = Number.NEGATIVE_INFINITY;
  17167. if (hasStacks === undefined) {
  17168. for (i = 0; !hasStacks && i < ilen; ++i) {
  17169. meta = metasets[i];
  17170. hasStacks = meta.stack !== undefined;
  17171. }
  17172. }
  17173. for (i = 0; i < ilen; ++i) {
  17174. meta = metasets[i];
  17175. data = datasets[meta.index].data;
  17176. if (hasStacks) {
  17177. stackData(me, stacks, meta, data);
  17178. } else {
  17179. updateMinMax(me, meta, data);
  17180. }
  17181. }
  17182. helpers$1.each(stacks, function(stackValues) {
  17183. values = stackValues.pos.concat(stackValues.neg);
  17184. me.min = Math.min(me.min, helpers$1.min(values));
  17185. me.max = Math.max(me.max, helpers$1.max(values));
  17186. });
  17187. me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  17188. me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  17189. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  17190. me.handleTickRangeOptions();
  17191. },
  17192. // Returns the maximum number of ticks based on the scale dimension
  17193. _computeTickLimit: function() {
  17194. var me = this;
  17195. var tickFont;
  17196. if (me.isHorizontal()) {
  17197. return Math.ceil(me.width / 40);
  17198. }
  17199. tickFont = helpers$1.options._parseFont(me.options.ticks);
  17200. return Math.ceil(me.height / tickFont.lineHeight);
  17201. },
  17202. // Called after the ticks are built. We need
  17203. handleDirectionalChanges: function() {
  17204. if (!this.isHorizontal()) {
  17205. // We are in a vertical orientation. The top value is the highest. So reverse the array
  17206. this.ticks.reverse();
  17207. }
  17208. },
  17209. getLabelForIndex: function(index, datasetIndex) {
  17210. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  17211. },
  17212. // Utils
  17213. getPixelForValue: function(value) {
  17214. var me = this;
  17215. return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);
  17216. },
  17217. getValueForPixel: function(pixel) {
  17218. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  17219. },
  17220. getPixelForTick: function(index) {
  17221. var ticks = this.ticksAsNumbers;
  17222. if (index < 0 || index > ticks.length - 1) {
  17223. return null;
  17224. }
  17225. return this.getPixelForValue(ticks[index]);
  17226. }
  17227. });
  17228. // INTERNAL: static default options, registered in src/index.js
  17229. var _defaults$1 = defaultConfig$1;
  17230. scale_linear._defaults = _defaults$1;
  17231. var valueOrDefault$b = helpers$1.valueOrDefault;
  17232. var log10 = helpers$1.math.log10;
  17233. /**
  17234. * Generate a set of logarithmic ticks
  17235. * @param generationOptions the options used to generate the ticks
  17236. * @param dataRange the range of the data
  17237. * @returns {number[]} array of tick values
  17238. */
  17239. function generateTicks$1(generationOptions, dataRange) {
  17240. var ticks = [];
  17241. var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  17242. var endExp = Math.floor(log10(dataRange.max));
  17243. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  17244. var exp, significand;
  17245. if (tickVal === 0) {
  17246. exp = Math.floor(log10(dataRange.minNotZero));
  17247. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  17248. ticks.push(tickVal);
  17249. tickVal = significand * Math.pow(10, exp);
  17250. } else {
  17251. exp = Math.floor(log10(tickVal));
  17252. significand = Math.floor(tickVal / Math.pow(10, exp));
  17253. }
  17254. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  17255. do {
  17256. ticks.push(tickVal);
  17257. ++significand;
  17258. if (significand === 10) {
  17259. significand = 1;
  17260. ++exp;
  17261. precision = exp >= 0 ? 1 : precision;
  17262. }
  17263. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  17264. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  17265. var lastTick = valueOrDefault$b(generationOptions.max, tickVal);
  17266. ticks.push(lastTick);
  17267. return ticks;
  17268. }
  17269. var defaultConfig$2 = {
  17270. position: 'left',
  17271. // label settings
  17272. ticks: {
  17273. callback: core_ticks.formatters.logarithmic
  17274. }
  17275. };
  17276. // TODO(v3): change this to positiveOrDefault
  17277. function nonNegativeOrDefault(value, defaultValue) {
  17278. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  17279. }
  17280. var scale_logarithmic = core_scale.extend({
  17281. determineDataLimits: function() {
  17282. var me = this;
  17283. var opts = me.options;
  17284. var chart = me.chart;
  17285. var datasets = chart.data.datasets;
  17286. var isHorizontal = me.isHorizontal();
  17287. function IDMatches(meta) {
  17288. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  17289. }
  17290. var datasetIndex, meta, value, data, i, ilen;
  17291. // Calculate Range
  17292. me.min = Number.POSITIVE_INFINITY;
  17293. me.max = Number.NEGATIVE_INFINITY;
  17294. me.minNotZero = Number.POSITIVE_INFINITY;
  17295. var hasStacks = opts.stacked;
  17296. if (hasStacks === undefined) {
  17297. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  17298. meta = chart.getDatasetMeta(datasetIndex);
  17299. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  17300. meta.stack !== undefined) {
  17301. hasStacks = true;
  17302. break;
  17303. }
  17304. }
  17305. }
  17306. if (opts.stacked || hasStacks) {
  17307. var valuesPerStack = {};
  17308. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  17309. meta = chart.getDatasetMeta(datasetIndex);
  17310. var key = [
  17311. meta.type,
  17312. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  17313. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  17314. meta.stack
  17315. ].join('.');
  17316. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  17317. if (valuesPerStack[key] === undefined) {
  17318. valuesPerStack[key] = [];
  17319. }
  17320. data = datasets[datasetIndex].data;
  17321. for (i = 0, ilen = data.length; i < ilen; i++) {
  17322. var values = valuesPerStack[key];
  17323. value = me._parseValue(data[i]);
  17324. // invalid, hidden and negative values are ignored
  17325. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  17326. continue;
  17327. }
  17328. values[i] = values[i] || 0;
  17329. values[i] += value.max;
  17330. }
  17331. }
  17332. }
  17333. helpers$1.each(valuesPerStack, function(valuesForType) {
  17334. if (valuesForType.length > 0) {
  17335. var minVal = helpers$1.min(valuesForType);
  17336. var maxVal = helpers$1.max(valuesForType);
  17337. me.min = Math.min(me.min, minVal);
  17338. me.max = Math.max(me.max, maxVal);
  17339. }
  17340. });
  17341. } else {
  17342. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  17343. meta = chart.getDatasetMeta(datasetIndex);
  17344. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  17345. data = datasets[datasetIndex].data;
  17346. for (i = 0, ilen = data.length; i < ilen; i++) {
  17347. value = me._parseValue(data[i]);
  17348. // invalid, hidden and negative values are ignored
  17349. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  17350. continue;
  17351. }
  17352. me.min = Math.min(value.min, me.min);
  17353. me.max = Math.max(value.max, me.max);
  17354. if (value.min !== 0) {
  17355. me.minNotZero = Math.min(value.min, me.minNotZero);
  17356. }
  17357. }
  17358. }
  17359. }
  17360. }
  17361. me.min = helpers$1.isFinite(me.min) ? me.min : null;
  17362. me.max = helpers$1.isFinite(me.max) ? me.max : null;
  17363. me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;
  17364. // Common base implementation to handle ticks.min, ticks.max
  17365. this.handleTickRangeOptions();
  17366. },
  17367. handleTickRangeOptions: function() {
  17368. var me = this;
  17369. var tickOpts = me.options.ticks;
  17370. var DEFAULT_MIN = 1;
  17371. var DEFAULT_MAX = 10;
  17372. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  17373. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  17374. if (me.min === me.max) {
  17375. if (me.min !== 0 && me.min !== null) {
  17376. me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);
  17377. me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);
  17378. } else {
  17379. me.min = DEFAULT_MIN;
  17380. me.max = DEFAULT_MAX;
  17381. }
  17382. }
  17383. if (me.min === null) {
  17384. me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);
  17385. }
  17386. if (me.max === null) {
  17387. me.max = me.min !== 0
  17388. ? Math.pow(10, Math.floor(log10(me.min)) + 1)
  17389. : DEFAULT_MAX;
  17390. }
  17391. if (me.minNotZero === null) {
  17392. if (me.min > 0) {
  17393. me.minNotZero = me.min;
  17394. } else if (me.max < 1) {
  17395. me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));
  17396. } else {
  17397. me.minNotZero = DEFAULT_MIN;
  17398. }
  17399. }
  17400. },
  17401. buildTicks: function() {
  17402. var me = this;
  17403. var tickOpts = me.options.ticks;
  17404. var reverse = !me.isHorizontal();
  17405. var generationOptions = {
  17406. min: nonNegativeOrDefault(tickOpts.min),
  17407. max: nonNegativeOrDefault(tickOpts.max)
  17408. };
  17409. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  17410. // At this point, we need to update our max and min given the tick values since we have expanded the
  17411. // range of the scale
  17412. me.max = helpers$1.max(ticks);
  17413. me.min = helpers$1.min(ticks);
  17414. if (tickOpts.reverse) {
  17415. reverse = !reverse;
  17416. me.start = me.max;
  17417. me.end = me.min;
  17418. } else {
  17419. me.start = me.min;
  17420. me.end = me.max;
  17421. }
  17422. if (reverse) {
  17423. ticks.reverse();
  17424. }
  17425. },
  17426. convertTicksToLabels: function() {
  17427. this.tickValues = this.ticks.slice();
  17428. core_scale.prototype.convertTicksToLabels.call(this);
  17429. },
  17430. // Get the correct tooltip label
  17431. getLabelForIndex: function(index, datasetIndex) {
  17432. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  17433. },
  17434. getPixelForTick: function(index) {
  17435. var ticks = this.tickValues;
  17436. if (index < 0 || index > ticks.length - 1) {
  17437. return null;
  17438. }
  17439. return this.getPixelForValue(ticks[index]);
  17440. },
  17441. /**
  17442. * Returns the value of the first tick.
  17443. * @param {number} value - The minimum not zero value.
  17444. * @return {number} The first tick value.
  17445. * @private
  17446. */
  17447. _getFirstTickValue: function(value) {
  17448. var exp = Math.floor(log10(value));
  17449. var significand = Math.floor(value / Math.pow(10, exp));
  17450. return significand * Math.pow(10, exp);
  17451. },
  17452. _configure: function() {
  17453. var me = this;
  17454. var start = me.min;
  17455. var offset = 0;
  17456. core_scale.prototype._configure.call(me);
  17457. if (start === 0) {
  17458. start = me._getFirstTickValue(me.minNotZero);
  17459. offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;
  17460. }
  17461. me._startValue = log10(start);
  17462. me._valueOffset = offset;
  17463. me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);
  17464. },
  17465. getPixelForValue: function(value) {
  17466. var me = this;
  17467. var decimal = 0;
  17468. value = +me.getRightValue(value);
  17469. if (value > me.min && value > 0) {
  17470. decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;
  17471. }
  17472. return me.getPixelForDecimal(decimal);
  17473. },
  17474. getValueForPixel: function(pixel) {
  17475. var me = this;
  17476. var decimal = me.getDecimalForPixel(pixel);
  17477. return decimal === 0 && me.min === 0
  17478. ? 0
  17479. : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);
  17480. }
  17481. });
  17482. // INTERNAL: static default options, registered in src/index.js
  17483. var _defaults$2 = defaultConfig$2;
  17484. scale_logarithmic._defaults = _defaults$2;
  17485. var valueOrDefault$c = helpers$1.valueOrDefault;
  17486. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  17487. var resolve$4 = helpers$1.options.resolve;
  17488. var defaultConfig$3 = {
  17489. display: true,
  17490. // Boolean - Whether to animate scaling the chart from the centre
  17491. animate: true,
  17492. position: 'chartArea',
  17493. angleLines: {
  17494. display: true,
  17495. color: 'rgba(0,0,0,0.1)',
  17496. lineWidth: 1,
  17497. borderDash: [],
  17498. borderDashOffset: 0.0
  17499. },
  17500. gridLines: {
  17501. circular: false
  17502. },
  17503. // label settings
  17504. ticks: {
  17505. // Boolean - Show a backdrop to the scale label
  17506. showLabelBackdrop: true,
  17507. // String - The colour of the label backdrop
  17508. backdropColor: 'rgba(255,255,255,0.75)',
  17509. // Number - The backdrop padding above & below the label in pixels
  17510. backdropPaddingY: 2,
  17511. // Number - The backdrop padding to the side of the label in pixels
  17512. backdropPaddingX: 2,
  17513. callback: core_ticks.formatters.linear
  17514. },
  17515. pointLabels: {
  17516. // Boolean - if true, show point labels
  17517. display: true,
  17518. // Number - Point label font size in pixels
  17519. fontSize: 10,
  17520. // Function - Used to convert point labels
  17521. callback: function(label) {
  17522. return label;
  17523. }
  17524. }
  17525. };
  17526. function getTickBackdropHeight(opts) {
  17527. var tickOpts = opts.ticks;
  17528. if (tickOpts.display && opts.display) {
  17529. return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  17530. }
  17531. return 0;
  17532. }
  17533. function measureLabelSize(ctx, lineHeight, label) {
  17534. if (helpers$1.isArray(label)) {
  17535. return {
  17536. w: helpers$1.longestText(ctx, ctx.font, label),
  17537. h: label.length * lineHeight
  17538. };
  17539. }
  17540. return {
  17541. w: ctx.measureText(label).width,
  17542. h: lineHeight
  17543. };
  17544. }
  17545. function determineLimits(angle, pos, size, min, max) {
  17546. if (angle === min || angle === max) {
  17547. return {
  17548. start: pos - (size / 2),
  17549. end: pos + (size / 2)
  17550. };
  17551. } else if (angle < min || angle > max) {
  17552. return {
  17553. start: pos - size,
  17554. end: pos
  17555. };
  17556. }
  17557. return {
  17558. start: pos,
  17559. end: pos + size
  17560. };
  17561. }
  17562. /**
  17563. * Helper function to fit a radial linear scale with point labels
  17564. */
  17565. function fitWithPointLabels(scale) {
  17566. // Right, this is really confusing and there is a lot of maths going on here
  17567. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  17568. //
  17569. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  17570. //
  17571. // Solution:
  17572. //
  17573. // We assume the radius of the polygon is half the size of the canvas at first
  17574. // at each index we check if the text overlaps.
  17575. //
  17576. // Where it does, we store that angle and that index.
  17577. //
  17578. // After finding the largest index and angle we calculate how much we need to remove
  17579. // from the shape radius to move the point inwards by that x.
  17580. //
  17581. // We average the left and right distances to get the maximum shape radius that can fit in the box
  17582. // along with labels.
  17583. //
  17584. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  17585. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  17586. //
  17587. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  17588. // and position it in the most space efficient manner
  17589. //
  17590. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  17591. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  17592. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  17593. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  17594. var furthestLimits = {
  17595. l: 0,
  17596. r: scale.width,
  17597. t: 0,
  17598. b: scale.height - scale.paddingTop
  17599. };
  17600. var furthestAngles = {};
  17601. var i, textSize, pointPosition;
  17602. scale.ctx.font = plFont.string;
  17603. scale._pointLabelSizes = [];
  17604. var valueCount = scale.chart.data.labels.length;
  17605. for (i = 0; i < valueCount; i++) {
  17606. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  17607. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
  17608. scale._pointLabelSizes[i] = textSize;
  17609. // Add quarter circle to make degree 0 mean top of circle
  17610. var angleRadians = scale.getIndexAngle(i);
  17611. var angle = helpers$1.toDegrees(angleRadians) % 360;
  17612. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  17613. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  17614. if (hLimits.start < furthestLimits.l) {
  17615. furthestLimits.l = hLimits.start;
  17616. furthestAngles.l = angleRadians;
  17617. }
  17618. if (hLimits.end > furthestLimits.r) {
  17619. furthestLimits.r = hLimits.end;
  17620. furthestAngles.r = angleRadians;
  17621. }
  17622. if (vLimits.start < furthestLimits.t) {
  17623. furthestLimits.t = vLimits.start;
  17624. furthestAngles.t = angleRadians;
  17625. }
  17626. if (vLimits.end > furthestLimits.b) {
  17627. furthestLimits.b = vLimits.end;
  17628. furthestAngles.b = angleRadians;
  17629. }
  17630. }
  17631. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  17632. }
  17633. function getTextAlignForAngle(angle) {
  17634. if (angle === 0 || angle === 180) {
  17635. return 'center';
  17636. } else if (angle < 180) {
  17637. return 'left';
  17638. }
  17639. return 'right';
  17640. }
  17641. function fillText(ctx, text, position, lineHeight) {
  17642. var y = position.y + lineHeight / 2;
  17643. var i, ilen;
  17644. if (helpers$1.isArray(text)) {
  17645. for (i = 0, ilen = text.length; i < ilen; ++i) {
  17646. ctx.fillText(text[i], position.x, y);
  17647. y += lineHeight;
  17648. }
  17649. } else {
  17650. ctx.fillText(text, position.x, y);
  17651. }
  17652. }
  17653. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  17654. if (angle === 90 || angle === 270) {
  17655. position.y -= (textSize.h / 2);
  17656. } else if (angle > 270 || angle < 90) {
  17657. position.y -= textSize.h;
  17658. }
  17659. }
  17660. function drawPointLabels(scale) {
  17661. var ctx = scale.ctx;
  17662. var opts = scale.options;
  17663. var pointLabelOpts = opts.pointLabels;
  17664. var tickBackdropHeight = getTickBackdropHeight(opts);
  17665. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  17666. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  17667. ctx.save();
  17668. ctx.font = plFont.string;
  17669. ctx.textBaseline = 'middle';
  17670. for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
  17671. // Extra pixels out for some label spacing
  17672. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  17673. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  17674. // Keep this in loop since we may support array properties here
  17675. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  17676. ctx.fillStyle = pointLabelFontColor;
  17677. var angleRadians = scale.getIndexAngle(i);
  17678. var angle = helpers$1.toDegrees(angleRadians);
  17679. ctx.textAlign = getTextAlignForAngle(angle);
  17680. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  17681. fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
  17682. }
  17683. ctx.restore();
  17684. }
  17685. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  17686. var ctx = scale.ctx;
  17687. var circular = gridLineOpts.circular;
  17688. var valueCount = scale.chart.data.labels.length;
  17689. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  17690. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  17691. var pointPosition;
  17692. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  17693. return;
  17694. }
  17695. ctx.save();
  17696. ctx.strokeStyle = lineColor;
  17697. ctx.lineWidth = lineWidth;
  17698. if (ctx.setLineDash) {
  17699. ctx.setLineDash(gridLineOpts.borderDash || []);
  17700. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  17701. }
  17702. ctx.beginPath();
  17703. if (circular) {
  17704. // Draw circular arcs between the points
  17705. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  17706. } else {
  17707. // Draw straight lines connecting each index
  17708. pointPosition = scale.getPointPosition(0, radius);
  17709. ctx.moveTo(pointPosition.x, pointPosition.y);
  17710. for (var i = 1; i < valueCount; i++) {
  17711. pointPosition = scale.getPointPosition(i, radius);
  17712. ctx.lineTo(pointPosition.x, pointPosition.y);
  17713. }
  17714. }
  17715. ctx.closePath();
  17716. ctx.stroke();
  17717. ctx.restore();
  17718. }
  17719. function numberOrZero(param) {
  17720. return helpers$1.isNumber(param) ? param : 0;
  17721. }
  17722. var scale_radialLinear = scale_linearbase.extend({
  17723. setDimensions: function() {
  17724. var me = this;
  17725. // Set the unconstrained dimension before label rotation
  17726. me.width = me.maxWidth;
  17727. me.height = me.maxHeight;
  17728. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  17729. me.xCenter = Math.floor(me.width / 2);
  17730. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  17731. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  17732. },
  17733. determineDataLimits: function() {
  17734. var me = this;
  17735. var chart = me.chart;
  17736. var min = Number.POSITIVE_INFINITY;
  17737. var max = Number.NEGATIVE_INFINITY;
  17738. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  17739. if (chart.isDatasetVisible(datasetIndex)) {
  17740. var meta = chart.getDatasetMeta(datasetIndex);
  17741. helpers$1.each(dataset.data, function(rawValue, index) {
  17742. var value = +me.getRightValue(rawValue);
  17743. if (isNaN(value) || meta.data[index].hidden) {
  17744. return;
  17745. }
  17746. min = Math.min(value, min);
  17747. max = Math.max(value, max);
  17748. });
  17749. }
  17750. });
  17751. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  17752. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  17753. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  17754. me.handleTickRangeOptions();
  17755. },
  17756. // Returns the maximum number of ticks based on the scale dimension
  17757. _computeTickLimit: function() {
  17758. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  17759. },
  17760. convertTicksToLabels: function() {
  17761. var me = this;
  17762. scale_linearbase.prototype.convertTicksToLabels.call(me);
  17763. // Point labels
  17764. me.pointLabels = me.chart.data.labels.map(function() {
  17765. var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);
  17766. return label || label === 0 ? label : '';
  17767. });
  17768. },
  17769. getLabelForIndex: function(index, datasetIndex) {
  17770. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  17771. },
  17772. fit: function() {
  17773. var me = this;
  17774. var opts = me.options;
  17775. if (opts.display && opts.pointLabels.display) {
  17776. fitWithPointLabels(me);
  17777. } else {
  17778. me.setCenterPoint(0, 0, 0, 0);
  17779. }
  17780. },
  17781. /**
  17782. * Set radius reductions and determine new radius and center point
  17783. * @private
  17784. */
  17785. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  17786. var me = this;
  17787. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  17788. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  17789. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  17790. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  17791. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  17792. radiusReductionRight = numberOrZero(radiusReductionRight);
  17793. radiusReductionTop = numberOrZero(radiusReductionTop);
  17794. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  17795. me.drawingArea = Math.min(
  17796. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  17797. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  17798. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  17799. },
  17800. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  17801. var me = this;
  17802. var maxRight = me.width - rightMovement - me.drawingArea;
  17803. var maxLeft = leftMovement + me.drawingArea;
  17804. var maxTop = topMovement + me.drawingArea;
  17805. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  17806. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  17807. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  17808. },
  17809. getIndexAngle: function(index) {
  17810. var chart = this.chart;
  17811. var angleMultiplier = 360 / chart.data.labels.length;
  17812. var options = chart.options || {};
  17813. var startAngle = options.startAngle || 0;
  17814. // Start from the top instead of right, so remove a quarter of the circle
  17815. var angle = (index * angleMultiplier + startAngle) % 360;
  17816. return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;
  17817. },
  17818. getDistanceFromCenterForValue: function(value) {
  17819. var me = this;
  17820. if (helpers$1.isNullOrUndef(value)) {
  17821. return NaN;
  17822. }
  17823. // Take into account half font size + the yPadding of the top value
  17824. var scalingFactor = me.drawingArea / (me.max - me.min);
  17825. if (me.options.ticks.reverse) {
  17826. return (me.max - value) * scalingFactor;
  17827. }
  17828. return (value - me.min) * scalingFactor;
  17829. },
  17830. getPointPosition: function(index, distanceFromCenter) {
  17831. var me = this;
  17832. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  17833. return {
  17834. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  17835. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  17836. };
  17837. },
  17838. getPointPositionForValue: function(index, value) {
  17839. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  17840. },
  17841. getBasePosition: function(index) {
  17842. var me = this;
  17843. var min = me.min;
  17844. var max = me.max;
  17845. return me.getPointPositionForValue(index || 0,
  17846. me.beginAtZero ? 0 :
  17847. min < 0 && max < 0 ? max :
  17848. min > 0 && max > 0 ? min :
  17849. 0);
  17850. },
  17851. /**
  17852. * @private
  17853. */
  17854. _drawGrid: function() {
  17855. var me = this;
  17856. var ctx = me.ctx;
  17857. var opts = me.options;
  17858. var gridLineOpts = opts.gridLines;
  17859. var angleLineOpts = opts.angleLines;
  17860. var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  17861. var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);
  17862. var i, offset, position;
  17863. if (opts.pointLabels.display) {
  17864. drawPointLabels(me);
  17865. }
  17866. if (gridLineOpts.display) {
  17867. helpers$1.each(me.ticks, function(label, index) {
  17868. if (index !== 0) {
  17869. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  17870. drawRadiusLine(me, gridLineOpts, offset, index);
  17871. }
  17872. });
  17873. }
  17874. if (angleLineOpts.display && lineWidth && lineColor) {
  17875. ctx.save();
  17876. ctx.lineWidth = lineWidth;
  17877. ctx.strokeStyle = lineColor;
  17878. if (ctx.setLineDash) {
  17879. ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  17880. ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  17881. }
  17882. for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
  17883. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  17884. position = me.getPointPosition(i, offset);
  17885. ctx.beginPath();
  17886. ctx.moveTo(me.xCenter, me.yCenter);
  17887. ctx.lineTo(position.x, position.y);
  17888. ctx.stroke();
  17889. }
  17890. ctx.restore();
  17891. }
  17892. },
  17893. /**
  17894. * @private
  17895. */
  17896. _drawLabels: function() {
  17897. var me = this;
  17898. var ctx = me.ctx;
  17899. var opts = me.options;
  17900. var tickOpts = opts.ticks;
  17901. if (!tickOpts.display) {
  17902. return;
  17903. }
  17904. var startAngle = me.getIndexAngle(0);
  17905. var tickFont = helpers$1.options._parseFont(tickOpts);
  17906. var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  17907. var offset, width;
  17908. ctx.save();
  17909. ctx.font = tickFont.string;
  17910. ctx.translate(me.xCenter, me.yCenter);
  17911. ctx.rotate(startAngle);
  17912. ctx.textAlign = 'center';
  17913. ctx.textBaseline = 'middle';
  17914. helpers$1.each(me.ticks, function(label, index) {
  17915. if (index === 0 && !tickOpts.reverse) {
  17916. return;
  17917. }
  17918. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  17919. if (tickOpts.showLabelBackdrop) {
  17920. width = ctx.measureText(label).width;
  17921. ctx.fillStyle = tickOpts.backdropColor;
  17922. ctx.fillRect(
  17923. -width / 2 - tickOpts.backdropPaddingX,
  17924. -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  17925. width + tickOpts.backdropPaddingX * 2,
  17926. tickFont.size + tickOpts.backdropPaddingY * 2
  17927. );
  17928. }
  17929. ctx.fillStyle = tickFontColor;
  17930. ctx.fillText(label, 0, -offset);
  17931. });
  17932. ctx.restore();
  17933. },
  17934. /**
  17935. * @private
  17936. */
  17937. _drawTitle: helpers$1.noop
  17938. });
  17939. // INTERNAL: static default options, registered in src/index.js
  17940. var _defaults$3 = defaultConfig$3;
  17941. scale_radialLinear._defaults = _defaults$3;
  17942. var deprecated$1 = helpers$1._deprecated;
  17943. var resolve$5 = helpers$1.options.resolve;
  17944. var valueOrDefault$d = helpers$1.valueOrDefault;
  17945. // Integer constants are from the ES6 spec.
  17946. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  17947. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  17948. var INTERVALS = {
  17949. millisecond: {
  17950. common: true,
  17951. size: 1,
  17952. steps: 1000
  17953. },
  17954. second: {
  17955. common: true,
  17956. size: 1000,
  17957. steps: 60
  17958. },
  17959. minute: {
  17960. common: true,
  17961. size: 60000,
  17962. steps: 60
  17963. },
  17964. hour: {
  17965. common: true,
  17966. size: 3600000,
  17967. steps: 24
  17968. },
  17969. day: {
  17970. common: true,
  17971. size: 86400000,
  17972. steps: 30
  17973. },
  17974. week: {
  17975. common: false,
  17976. size: 604800000,
  17977. steps: 4
  17978. },
  17979. month: {
  17980. common: true,
  17981. size: 2.628e9,
  17982. steps: 12
  17983. },
  17984. quarter: {
  17985. common: false,
  17986. size: 7.884e9,
  17987. steps: 4
  17988. },
  17989. year: {
  17990. common: true,
  17991. size: 3.154e10
  17992. }
  17993. };
  17994. var UNITS = Object.keys(INTERVALS);
  17995. function sorter(a, b) {
  17996. return a - b;
  17997. }
  17998. function arrayUnique(items) {
  17999. var hash = {};
  18000. var out = [];
  18001. var i, ilen, item;
  18002. for (i = 0, ilen = items.length; i < ilen; ++i) {
  18003. item = items[i];
  18004. if (!hash[item]) {
  18005. hash[item] = true;
  18006. out.push(item);
  18007. }
  18008. }
  18009. return out;
  18010. }
  18011. function getMin(options) {
  18012. return helpers$1.valueOrDefault(options.time.min, options.ticks.min);
  18013. }
  18014. function getMax(options) {
  18015. return helpers$1.valueOrDefault(options.time.max, options.ticks.max);
  18016. }
  18017. /**
  18018. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  18019. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  18020. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  18021. * extremity (left + width or top + height). Note that it would be more optimized to directly
  18022. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  18023. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  18024. *
  18025. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  18026. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  18027. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  18028. * If 'series', timestamps will be positioned at the same distance from each other. In this
  18029. * case, only timestamps that break the time linearity are registered, meaning that in the
  18030. * best case, all timestamps are linear, the table contains only min and max.
  18031. */
  18032. function buildLookupTable(timestamps, min, max, distribution) {
  18033. if (distribution === 'linear' || !timestamps.length) {
  18034. return [
  18035. {time: min, pos: 0},
  18036. {time: max, pos: 1}
  18037. ];
  18038. }
  18039. var table = [];
  18040. var items = [min];
  18041. var i, ilen, prev, curr, next;
  18042. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  18043. curr = timestamps[i];
  18044. if (curr > min && curr < max) {
  18045. items.push(curr);
  18046. }
  18047. }
  18048. items.push(max);
  18049. for (i = 0, ilen = items.length; i < ilen; ++i) {
  18050. next = items[i + 1];
  18051. prev = items[i - 1];
  18052. curr = items[i];
  18053. // only add points that breaks the scale linearity
  18054. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  18055. table.push({time: curr, pos: i / (ilen - 1)});
  18056. }
  18057. }
  18058. return table;
  18059. }
  18060. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  18061. function lookup(table, key, value) {
  18062. var lo = 0;
  18063. var hi = table.length - 1;
  18064. var mid, i0, i1;
  18065. while (lo >= 0 && lo <= hi) {
  18066. mid = (lo + hi) >> 1;
  18067. i0 = table[mid - 1] || null;
  18068. i1 = table[mid];
  18069. if (!i0) {
  18070. // given value is outside table (before first item)
  18071. return {lo: null, hi: i1};
  18072. } else if (i1[key] < value) {
  18073. lo = mid + 1;
  18074. } else if (i0[key] > value) {
  18075. hi = mid - 1;
  18076. } else {
  18077. return {lo: i0, hi: i1};
  18078. }
  18079. }
  18080. // given value is outside table (after last item)
  18081. return {lo: i1, hi: null};
  18082. }
  18083. /**
  18084. * Linearly interpolates the given source `value` using the table items `skey` values and
  18085. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  18086. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  18087. * index [0, 1] or [n - 1, n] are used for the interpolation.
  18088. */
  18089. function interpolate$1(table, skey, sval, tkey) {
  18090. var range = lookup(table, skey, sval);
  18091. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  18092. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  18093. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  18094. var span = next[skey] - prev[skey];
  18095. var ratio = span ? (sval - prev[skey]) / span : 0;
  18096. var offset = (next[tkey] - prev[tkey]) * ratio;
  18097. return prev[tkey] + offset;
  18098. }
  18099. function toTimestamp(scale, input) {
  18100. var adapter = scale._adapter;
  18101. var options = scale.options.time;
  18102. var parser = options.parser;
  18103. var format = parser || options.format;
  18104. var value = input;
  18105. if (typeof parser === 'function') {
  18106. value = parser(value);
  18107. }
  18108. // Only parse if its not a timestamp already
  18109. if (!helpers$1.isFinite(value)) {
  18110. value = typeof format === 'string'
  18111. ? adapter.parse(value, format)
  18112. : adapter.parse(value);
  18113. }
  18114. if (value !== null) {
  18115. return +value;
  18116. }
  18117. // Labels are in an incompatible format and no `parser` has been provided.
  18118. // The user might still use the deprecated `format` option for parsing.
  18119. if (!parser && typeof format === 'function') {
  18120. value = format(input);
  18121. // `format` could return something else than a timestamp, if so, parse it
  18122. if (!helpers$1.isFinite(value)) {
  18123. value = adapter.parse(value);
  18124. }
  18125. }
  18126. return value;
  18127. }
  18128. function parse(scale, input) {
  18129. if (helpers$1.isNullOrUndef(input)) {
  18130. return null;
  18131. }
  18132. var options = scale.options.time;
  18133. var value = toTimestamp(scale, scale.getRightValue(input));
  18134. if (value === null) {
  18135. return value;
  18136. }
  18137. if (options.round) {
  18138. value = +scale._adapter.startOf(value, options.round);
  18139. }
  18140. return value;
  18141. }
  18142. /**
  18143. * Figures out what unit results in an appropriate number of auto-generated ticks
  18144. */
  18145. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  18146. var ilen = UNITS.length;
  18147. var i, interval, factor;
  18148. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  18149. interval = INTERVALS[UNITS[i]];
  18150. factor = interval.steps ? interval.steps : MAX_INTEGER;
  18151. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  18152. return UNITS[i];
  18153. }
  18154. }
  18155. return UNITS[ilen - 1];
  18156. }
  18157. /**
  18158. * Figures out what unit to format a set of ticks with
  18159. */
  18160. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  18161. var i, unit;
  18162. for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  18163. unit = UNITS[i];
  18164. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  18165. return unit;
  18166. }
  18167. }
  18168. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  18169. }
  18170. function determineMajorUnit(unit) {
  18171. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  18172. if (INTERVALS[UNITS[i]].common) {
  18173. return UNITS[i];
  18174. }
  18175. }
  18176. }
  18177. /**
  18178. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  18179. * `minor` unit using the given scale time `options`.
  18180. * Important: this method can return ticks outside the min and max range, it's the
  18181. * responsibility of the calling code to clamp values if needed.
  18182. */
  18183. function generate(scale, min, max, capacity) {
  18184. var adapter = scale._adapter;
  18185. var options = scale.options;
  18186. var timeOpts = options.time;
  18187. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  18188. var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
  18189. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  18190. var first = min;
  18191. var ticks = [];
  18192. var time;
  18193. // For 'week' unit, handle the first day of week option
  18194. if (weekday) {
  18195. first = +adapter.startOf(first, 'isoWeek', weekday);
  18196. }
  18197. // Align first ticks on unit
  18198. first = +adapter.startOf(first, weekday ? 'day' : minor);
  18199. // Prevent browser from freezing in case user options request millions of milliseconds
  18200. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  18201. throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
  18202. }
  18203. for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {
  18204. ticks.push(time);
  18205. }
  18206. if (time === max || options.bounds === 'ticks') {
  18207. ticks.push(time);
  18208. }
  18209. return ticks;
  18210. }
  18211. /**
  18212. * Returns the start and end offsets from edges in the form of {start, end}
  18213. * where each value is a relative width to the scale and ranges between 0 and 1.
  18214. * They add extra margins on the both sides by scaling down the original scale.
  18215. * Offsets are added when the `offset` option is true.
  18216. */
  18217. function computeOffsets(table, ticks, min, max, options) {
  18218. var start = 0;
  18219. var end = 0;
  18220. var first, last;
  18221. if (options.offset && ticks.length) {
  18222. first = interpolate$1(table, 'time', ticks[0], 'pos');
  18223. if (ticks.length === 1) {
  18224. start = 1 - first;
  18225. } else {
  18226. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  18227. }
  18228. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  18229. if (ticks.length === 1) {
  18230. end = last;
  18231. } else {
  18232. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  18233. }
  18234. }
  18235. return {start: start, end: end, factor: 1 / (start + 1 + end)};
  18236. }
  18237. function setMajorTicks(scale, ticks, map, majorUnit) {
  18238. var adapter = scale._adapter;
  18239. var first = +adapter.startOf(ticks[0].value, majorUnit);
  18240. var last = ticks[ticks.length - 1].value;
  18241. var major, index;
  18242. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  18243. index = map[major];
  18244. if (index >= 0) {
  18245. ticks[index].major = true;
  18246. }
  18247. }
  18248. return ticks;
  18249. }
  18250. function ticksFromTimestamps(scale, values, majorUnit) {
  18251. var ticks = [];
  18252. var map = {};
  18253. var ilen = values.length;
  18254. var i, value;
  18255. for (i = 0; i < ilen; ++i) {
  18256. value = values[i];
  18257. map[value] = i;
  18258. ticks.push({
  18259. value: value,
  18260. major: false
  18261. });
  18262. }
  18263. // We set the major ticks separately from the above loop because calling startOf for every tick
  18264. // is expensive when there is a large number of ticks
  18265. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  18266. }
  18267. var defaultConfig$4 = {
  18268. position: 'bottom',
  18269. /**
  18270. * Data distribution along the scale:
  18271. * - 'linear': data are spread according to their time (distances can vary),
  18272. * - 'series': data are spread at the same distance from each other.
  18273. * @see https://github.com/chartjs/Chart.js/pull/4507
  18274. * @since 2.7.0
  18275. */
  18276. distribution: 'linear',
  18277. /**
  18278. * Scale boundary strategy (bypassed by min/max time options)
  18279. * - `data`: make sure data are fully visible, ticks outside are removed
  18280. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  18281. * @see https://github.com/chartjs/Chart.js/pull/4556
  18282. * @since 2.7.0
  18283. */
  18284. bounds: 'data',
  18285. adapters: {},
  18286. time: {
  18287. 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
  18288. unit: false, // false == automatic or override with week, month, year, etc.
  18289. round: false, // none, or override with week, month, year, etc.
  18290. displayFormat: false, // DEPRECATED
  18291. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  18292. minUnit: 'millisecond',
  18293. displayFormats: {}
  18294. },
  18295. ticks: {
  18296. autoSkip: false,
  18297. /**
  18298. * Ticks generation input values:
  18299. * - 'auto': generates "optimal" ticks based on scale size and time options.
  18300. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  18301. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  18302. * @see https://github.com/chartjs/Chart.js/pull/4507
  18303. * @since 2.7.0
  18304. */
  18305. source: 'auto',
  18306. major: {
  18307. enabled: false
  18308. }
  18309. }
  18310. };
  18311. var scale_time = core_scale.extend({
  18312. initialize: function() {
  18313. this.mergeTicksOptions();
  18314. core_scale.prototype.initialize.call(this);
  18315. },
  18316. update: function() {
  18317. var me = this;
  18318. var options = me.options;
  18319. var time = options.time || (options.time = {});
  18320. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  18321. // DEPRECATIONS: output a message only one time per update
  18322. deprecated$1('time scale', time.format, 'time.format', 'time.parser');
  18323. deprecated$1('time scale', time.min, 'time.min', 'ticks.min');
  18324. deprecated$1('time scale', time.max, 'time.max', 'ticks.max');
  18325. // Backward compatibility: before introducing adapter, `displayFormats` was
  18326. // supposed to contain *all* unit/string pairs but this can't be resolved
  18327. // when loading the scale (adapters are loaded afterward), so let's populate
  18328. // missing formats on update
  18329. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  18330. return core_scale.prototype.update.apply(me, arguments);
  18331. },
  18332. /**
  18333. * Allows data to be referenced via 't' attribute
  18334. */
  18335. getRightValue: function(rawValue) {
  18336. if (rawValue && rawValue.t !== undefined) {
  18337. rawValue = rawValue.t;
  18338. }
  18339. return core_scale.prototype.getRightValue.call(this, rawValue);
  18340. },
  18341. determineDataLimits: function() {
  18342. var me = this;
  18343. var chart = me.chart;
  18344. var adapter = me._adapter;
  18345. var options = me.options;
  18346. var unit = options.time.unit || 'day';
  18347. var min = MAX_INTEGER;
  18348. var max = MIN_INTEGER;
  18349. var timestamps = [];
  18350. var datasets = [];
  18351. var labels = [];
  18352. var i, j, ilen, jlen, data, timestamp, labelsAdded;
  18353. var dataLabels = me._getLabels();
  18354. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  18355. labels.push(parse(me, dataLabels[i]));
  18356. }
  18357. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  18358. if (chart.isDatasetVisible(i)) {
  18359. data = chart.data.datasets[i].data;
  18360. // Let's consider that all data have the same format.
  18361. if (helpers$1.isObject(data[0])) {
  18362. datasets[i] = [];
  18363. for (j = 0, jlen = data.length; j < jlen; ++j) {
  18364. timestamp = parse(me, data[j]);
  18365. timestamps.push(timestamp);
  18366. datasets[i][j] = timestamp;
  18367. }
  18368. } else {
  18369. datasets[i] = labels.slice(0);
  18370. if (!labelsAdded) {
  18371. timestamps = timestamps.concat(labels);
  18372. labelsAdded = true;
  18373. }
  18374. }
  18375. } else {
  18376. datasets[i] = [];
  18377. }
  18378. }
  18379. if (labels.length) {
  18380. min = Math.min(min, labels[0]);
  18381. max = Math.max(max, labels[labels.length - 1]);
  18382. }
  18383. if (timestamps.length) {
  18384. timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);
  18385. min = Math.min(min, timestamps[0]);
  18386. max = Math.max(max, timestamps[timestamps.length - 1]);
  18387. }
  18388. min = parse(me, getMin(options)) || min;
  18389. max = parse(me, getMax(options)) || max;
  18390. // In case there is no valid min/max, set limits based on unit time option
  18391. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  18392. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  18393. // Make sure that max is strictly higher than min (required by the lookup table)
  18394. me.min = Math.min(min, max);
  18395. me.max = Math.max(min + 1, max);
  18396. // PRIVATE
  18397. me._table = [];
  18398. me._timestamps = {
  18399. data: timestamps,
  18400. datasets: datasets,
  18401. labels: labels
  18402. };
  18403. },
  18404. buildTicks: function() {
  18405. var me = this;
  18406. var min = me.min;
  18407. var max = me.max;
  18408. var options = me.options;
  18409. var tickOpts = options.ticks;
  18410. var timeOpts = options.time;
  18411. var timestamps = me._timestamps;
  18412. var ticks = [];
  18413. var capacity = me.getLabelCapacity(min);
  18414. var source = tickOpts.source;
  18415. var distribution = options.distribution;
  18416. var i, ilen, timestamp;
  18417. if (source === 'data' || (source === 'auto' && distribution === 'series')) {
  18418. timestamps = timestamps.data;
  18419. } else if (source === 'labels') {
  18420. timestamps = timestamps.labels;
  18421. } else {
  18422. timestamps = generate(me, min, max, capacity);
  18423. }
  18424. if (options.bounds === 'ticks' && timestamps.length) {
  18425. min = timestamps[0];
  18426. max = timestamps[timestamps.length - 1];
  18427. }
  18428. // Enforce limits with user min/max options
  18429. min = parse(me, getMin(options)) || min;
  18430. max = parse(me, getMax(options)) || max;
  18431. // Remove ticks outside the min/max range
  18432. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  18433. timestamp = timestamps[i];
  18434. if (timestamp >= min && timestamp <= max) {
  18435. ticks.push(timestamp);
  18436. }
  18437. }
  18438. me.min = min;
  18439. me.max = max;
  18440. // PRIVATE
  18441. // determineUnitForFormatting relies on the number of ticks so we don't use it when
  18442. // autoSkip is enabled because we don't yet know what the final number of ticks will be
  18443. me._unit = timeOpts.unit || (tickOpts.autoSkip
  18444. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
  18445. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  18446. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  18447. : determineMajorUnit(me._unit);
  18448. me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
  18449. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  18450. if (tickOpts.reverse) {
  18451. ticks.reverse();
  18452. }
  18453. return ticksFromTimestamps(me, ticks, me._majorUnit);
  18454. },
  18455. getLabelForIndex: function(index, datasetIndex) {
  18456. var me = this;
  18457. var adapter = me._adapter;
  18458. var data = me.chart.data;
  18459. var timeOpts = me.options.time;
  18460. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  18461. var value = data.datasets[datasetIndex].data[index];
  18462. if (helpers$1.isObject(value)) {
  18463. label = me.getRightValue(value);
  18464. }
  18465. if (timeOpts.tooltipFormat) {
  18466. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  18467. }
  18468. if (typeof label === 'string') {
  18469. return label;
  18470. }
  18471. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  18472. },
  18473. /**
  18474. * Function to format an individual tick mark
  18475. * @private
  18476. */
  18477. tickFormatFunction: function(time, index, ticks, format) {
  18478. var me = this;
  18479. var adapter = me._adapter;
  18480. var options = me.options;
  18481. var formats = options.time.displayFormats;
  18482. var minorFormat = formats[me._unit];
  18483. var majorUnit = me._majorUnit;
  18484. var majorFormat = formats[majorUnit];
  18485. var tick = ticks[index];
  18486. var tickOpts = options.ticks;
  18487. var major = majorUnit && majorFormat && tick && tick.major;
  18488. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  18489. var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;
  18490. var formatter = resolve$5([
  18491. nestedTickOpts.callback,
  18492. nestedTickOpts.userCallback,
  18493. tickOpts.callback,
  18494. tickOpts.userCallback
  18495. ]);
  18496. return formatter ? formatter(label, index, ticks) : label;
  18497. },
  18498. convertTicksToLabels: function(ticks) {
  18499. var labels = [];
  18500. var i, ilen;
  18501. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  18502. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  18503. }
  18504. return labels;
  18505. },
  18506. /**
  18507. * @private
  18508. */
  18509. getPixelForOffset: function(time) {
  18510. var me = this;
  18511. var offsets = me._offsets;
  18512. var pos = interpolate$1(me._table, 'time', time, 'pos');
  18513. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  18514. },
  18515. getPixelForValue: function(value, index, datasetIndex) {
  18516. var me = this;
  18517. var time = null;
  18518. if (index !== undefined && datasetIndex !== undefined) {
  18519. time = me._timestamps.datasets[datasetIndex][index];
  18520. }
  18521. if (time === null) {
  18522. time = parse(me, value);
  18523. }
  18524. if (time !== null) {
  18525. return me.getPixelForOffset(time);
  18526. }
  18527. },
  18528. getPixelForTick: function(index) {
  18529. var ticks = this.getTicks();
  18530. return index >= 0 && index < ticks.length ?
  18531. this.getPixelForOffset(ticks[index].value) :
  18532. null;
  18533. },
  18534. getValueForPixel: function(pixel) {
  18535. var me = this;
  18536. var offsets = me._offsets;
  18537. var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  18538. var time = interpolate$1(me._table, 'pos', pos, 'time');
  18539. // DEPRECATION, we should return time directly
  18540. return me._adapter._create(time);
  18541. },
  18542. /**
  18543. * @private
  18544. */
  18545. _getLabelSize: function(label) {
  18546. var me = this;
  18547. var ticksOpts = me.options.ticks;
  18548. var tickLabelWidth = me.ctx.measureText(label).width;
  18549. var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  18550. var cosRotation = Math.cos(angle);
  18551. var sinRotation = Math.sin(angle);
  18552. var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  18553. return {
  18554. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  18555. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  18556. };
  18557. },
  18558. /**
  18559. * Crude approximation of what the label width might be
  18560. * @private
  18561. */
  18562. getLabelWidth: function(label) {
  18563. return this._getLabelSize(label).w;
  18564. },
  18565. /**
  18566. * @private
  18567. */
  18568. getLabelCapacity: function(exampleTime) {
  18569. var me = this;
  18570. var timeOpts = me.options.time;
  18571. var displayFormats = timeOpts.displayFormats;
  18572. // pick the longest format (milliseconds) for guestimation
  18573. var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  18574. var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  18575. var size = me._getLabelSize(exampleLabel);
  18576. var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);
  18577. if (me.options.offset) {
  18578. capacity--;
  18579. }
  18580. return capacity > 0 ? capacity : 1;
  18581. }
  18582. });
  18583. // INTERNAL: static default options, registered in src/index.js
  18584. var _defaults$4 = defaultConfig$4;
  18585. scale_time._defaults = _defaults$4;
  18586. var scales = {
  18587. category: scale_category,
  18588. linear: scale_linear,
  18589. logarithmic: scale_logarithmic,
  18590. radialLinear: scale_radialLinear,
  18591. time: scale_time
  18592. };
  18593. var FORMATS = {
  18594. datetime: 'MMM D, YYYY, h:mm:ss a',
  18595. millisecond: 'h:mm:ss.SSS a',
  18596. second: 'h:mm:ss a',
  18597. minute: 'h:mm a',
  18598. hour: 'hA',
  18599. day: 'MMM D',
  18600. week: 'll',
  18601. month: 'MMM YYYY',
  18602. quarter: '[Q]Q - YYYY',
  18603. year: 'YYYY'
  18604. };
  18605. core_adapters._date.override(typeof moment === 'function' ? {
  18606. _id: 'moment', // DEBUG ONLY
  18607. formats: function() {
  18608. return FORMATS;
  18609. },
  18610. parse: function(value, format) {
  18611. if (typeof value === 'string' && typeof format === 'string') {
  18612. value = moment(value, format);
  18613. } else if (!(value instanceof moment)) {
  18614. value = moment(value);
  18615. }
  18616. return value.isValid() ? value.valueOf() : null;
  18617. },
  18618. format: function(time, format) {
  18619. return moment(time).format(format);
  18620. },
  18621. add: function(time, amount, unit) {
  18622. return moment(time).add(amount, unit).valueOf();
  18623. },
  18624. diff: function(max, min, unit) {
  18625. return moment(max).diff(moment(min), unit);
  18626. },
  18627. startOf: function(time, unit, weekday) {
  18628. time = moment(time);
  18629. if (unit === 'isoWeek') {
  18630. return time.isoWeekday(weekday).valueOf();
  18631. }
  18632. return time.startOf(unit).valueOf();
  18633. },
  18634. endOf: function(time, unit) {
  18635. return moment(time).endOf(unit).valueOf();
  18636. },
  18637. // DEPRECATIONS
  18638. /**
  18639. * Provided for backward compatibility with scale.getValueForPixel().
  18640. * @deprecated since version 2.8.0
  18641. * @todo remove at version 3
  18642. * @private
  18643. */
  18644. _create: function(time) {
  18645. return moment(time);
  18646. },
  18647. } : {});
  18648. core_defaults._set('global', {
  18649. plugins: {
  18650. filler: {
  18651. propagate: true
  18652. }
  18653. }
  18654. });
  18655. var mappers = {
  18656. dataset: function(source) {
  18657. var index = source.fill;
  18658. var chart = source.chart;
  18659. var meta = chart.getDatasetMeta(index);
  18660. var visible = meta && chart.isDatasetVisible(index);
  18661. var points = (visible && meta.dataset._children) || [];
  18662. var length = points.length || 0;
  18663. return !length ? null : function(point, i) {
  18664. return (i < length && points[i]._view) || null;
  18665. };
  18666. },
  18667. boundary: function(source) {
  18668. var boundary = source.boundary;
  18669. var x = boundary ? boundary.x : null;
  18670. var y = boundary ? boundary.y : null;
  18671. if (helpers$1.isArray(boundary)) {
  18672. return function(point, i) {
  18673. return boundary[i];
  18674. };
  18675. }
  18676. return function(point) {
  18677. return {
  18678. x: x === null ? point.x : x,
  18679. y: y === null ? point.y : y,
  18680. };
  18681. };
  18682. }
  18683. };
  18684. // @todo if (fill[0] === '#')
  18685. function decodeFill(el, index, count) {
  18686. var model = el._model || {};
  18687. var fill = model.fill;
  18688. var target;
  18689. if (fill === undefined) {
  18690. fill = !!model.backgroundColor;
  18691. }
  18692. if (fill === false || fill === null) {
  18693. return false;
  18694. }
  18695. if (fill === true) {
  18696. return 'origin';
  18697. }
  18698. target = parseFloat(fill, 10);
  18699. if (isFinite(target) && Math.floor(target) === target) {
  18700. if (fill[0] === '-' || fill[0] === '+') {
  18701. target = index + target;
  18702. }
  18703. if (target === index || target < 0 || target >= count) {
  18704. return false;
  18705. }
  18706. return target;
  18707. }
  18708. switch (fill) {
  18709. // compatibility
  18710. case 'bottom':
  18711. return 'start';
  18712. case 'top':
  18713. return 'end';
  18714. case 'zero':
  18715. return 'origin';
  18716. // supported boundaries
  18717. case 'origin':
  18718. case 'start':
  18719. case 'end':
  18720. return fill;
  18721. // invalid fill values
  18722. default:
  18723. return false;
  18724. }
  18725. }
  18726. function computeLinearBoundary(source) {
  18727. var model = source.el._model || {};
  18728. var scale = source.el._scale || {};
  18729. var fill = source.fill;
  18730. var target = null;
  18731. var horizontal;
  18732. if (isFinite(fill)) {
  18733. return null;
  18734. }
  18735. // Backward compatibility: until v3, we still need to support boundary values set on
  18736. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  18737. // controllers might still use it (e.g. the Smith chart).
  18738. if (fill === 'start') {
  18739. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  18740. } else if (fill === 'end') {
  18741. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  18742. } else if (model.scaleZero !== undefined) {
  18743. target = model.scaleZero;
  18744. } else if (scale.getBasePixel) {
  18745. target = scale.getBasePixel();
  18746. }
  18747. if (target !== undefined && target !== null) {
  18748. if (target.x !== undefined && target.y !== undefined) {
  18749. return target;
  18750. }
  18751. if (helpers$1.isFinite(target)) {
  18752. horizontal = scale.isHorizontal();
  18753. return {
  18754. x: horizontal ? target : null,
  18755. y: horizontal ? null : target
  18756. };
  18757. }
  18758. }
  18759. return null;
  18760. }
  18761. function computeCircularBoundary(source) {
  18762. var scale = source.el._scale;
  18763. var options = scale.options;
  18764. var length = scale.chart.data.labels.length;
  18765. var fill = source.fill;
  18766. var target = [];
  18767. var start, end, center, i, point;
  18768. if (!length) {
  18769. return null;
  18770. }
  18771. start = options.ticks.reverse ? scale.max : scale.min;
  18772. end = options.ticks.reverse ? scale.min : scale.max;
  18773. center = scale.getPointPositionForValue(0, start);
  18774. for (i = 0; i < length; ++i) {
  18775. point = fill === 'start' || fill === 'end'
  18776. ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)
  18777. : scale.getBasePosition(i);
  18778. if (options.gridLines.circular) {
  18779. point.cx = center.x;
  18780. point.cy = center.y;
  18781. point.angle = scale.getIndexAngle(i) - Math.PI / 2;
  18782. }
  18783. target.push(point);
  18784. }
  18785. return target;
  18786. }
  18787. function computeBoundary(source) {
  18788. var scale = source.el._scale || {};
  18789. if (scale.getPointPositionForValue) {
  18790. return computeCircularBoundary(source);
  18791. }
  18792. return computeLinearBoundary(source);
  18793. }
  18794. function resolveTarget(sources, index, propagate) {
  18795. var source = sources[index];
  18796. var fill = source.fill;
  18797. var visited = [index];
  18798. var target;
  18799. if (!propagate) {
  18800. return fill;
  18801. }
  18802. while (fill !== false && visited.indexOf(fill) === -1) {
  18803. if (!isFinite(fill)) {
  18804. return fill;
  18805. }
  18806. target = sources[fill];
  18807. if (!target) {
  18808. return false;
  18809. }
  18810. if (target.visible) {
  18811. return fill;
  18812. }
  18813. visited.push(fill);
  18814. fill = target.fill;
  18815. }
  18816. return false;
  18817. }
  18818. function createMapper(source) {
  18819. var fill = source.fill;
  18820. var type = 'dataset';
  18821. if (fill === false) {
  18822. return null;
  18823. }
  18824. if (!isFinite(fill)) {
  18825. type = 'boundary';
  18826. }
  18827. return mappers[type](source);
  18828. }
  18829. function isDrawable(point) {
  18830. return point && !point.skip;
  18831. }
  18832. function drawArea(ctx, curve0, curve1, len0, len1) {
  18833. var i, cx, cy, r;
  18834. if (!len0 || !len1) {
  18835. return;
  18836. }
  18837. // building first area curve (normal)
  18838. ctx.moveTo(curve0[0].x, curve0[0].y);
  18839. for (i = 1; i < len0; ++i) {
  18840. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  18841. }
  18842. if (curve1[0].angle !== undefined) {
  18843. cx = curve1[0].cx;
  18844. cy = curve1[0].cy;
  18845. r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));
  18846. for (i = len1 - 1; i > 0; --i) {
  18847. ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);
  18848. }
  18849. return;
  18850. }
  18851. // joining the two area curves
  18852. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  18853. // building opposite area curve (reverse)
  18854. for (i = len1 - 1; i > 0; --i) {
  18855. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  18856. }
  18857. }
  18858. function doFill(ctx, points, mapper, view, color, loop) {
  18859. var count = points.length;
  18860. var span = view.spanGaps;
  18861. var curve0 = [];
  18862. var curve1 = [];
  18863. var len0 = 0;
  18864. var len1 = 0;
  18865. var i, ilen, index, p0, p1, d0, d1, loopOffset;
  18866. ctx.beginPath();
  18867. for (i = 0, ilen = count; i < ilen; ++i) {
  18868. index = i % count;
  18869. p0 = points[index]._view;
  18870. p1 = mapper(p0, index, view);
  18871. d0 = isDrawable(p0);
  18872. d1 = isDrawable(p1);
  18873. if (loop && loopOffset === undefined && d0) {
  18874. loopOffset = i + 1;
  18875. ilen = count + loopOffset;
  18876. }
  18877. if (d0 && d1) {
  18878. len0 = curve0.push(p0);
  18879. len1 = curve1.push(p1);
  18880. } else if (len0 && len1) {
  18881. if (!span) {
  18882. drawArea(ctx, curve0, curve1, len0, len1);
  18883. len0 = len1 = 0;
  18884. curve0 = [];
  18885. curve1 = [];
  18886. } else {
  18887. if (d0) {
  18888. curve0.push(p0);
  18889. }
  18890. if (d1) {
  18891. curve1.push(p1);
  18892. }
  18893. }
  18894. }
  18895. }
  18896. drawArea(ctx, curve0, curve1, len0, len1);
  18897. ctx.closePath();
  18898. ctx.fillStyle = color;
  18899. ctx.fill();
  18900. }
  18901. var plugin_filler = {
  18902. id: 'filler',
  18903. afterDatasetsUpdate: function(chart, options) {
  18904. var count = (chart.data.datasets || []).length;
  18905. var propagate = options.propagate;
  18906. var sources = [];
  18907. var meta, i, el, source;
  18908. for (i = 0; i < count; ++i) {
  18909. meta = chart.getDatasetMeta(i);
  18910. el = meta.dataset;
  18911. source = null;
  18912. if (el && el._model && el instanceof elements.Line) {
  18913. source = {
  18914. visible: chart.isDatasetVisible(i),
  18915. fill: decodeFill(el, i, count),
  18916. chart: chart,
  18917. el: el
  18918. };
  18919. }
  18920. meta.$filler = source;
  18921. sources.push(source);
  18922. }
  18923. for (i = 0; i < count; ++i) {
  18924. source = sources[i];
  18925. if (!source) {
  18926. continue;
  18927. }
  18928. source.fill = resolveTarget(sources, i, propagate);
  18929. source.boundary = computeBoundary(source);
  18930. source.mapper = createMapper(source);
  18931. }
  18932. },
  18933. beforeDatasetsDraw: function(chart) {
  18934. var metasets = chart._getSortedVisibleDatasetMetas();
  18935. var ctx = chart.ctx;
  18936. var meta, i, el, view, points, mapper, color;
  18937. for (i = metasets.length - 1; i >= 0; --i) {
  18938. meta = metasets[i].$filler;
  18939. if (!meta || !meta.visible) {
  18940. continue;
  18941. }
  18942. el = meta.el;
  18943. view = el._view;
  18944. points = el._children || [];
  18945. mapper = meta.mapper;
  18946. color = view.backgroundColor || core_defaults.global.defaultColor;
  18947. if (mapper && color && points.length) {
  18948. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  18949. doFill(ctx, points, mapper, view, color, el._loop);
  18950. helpers$1.canvas.unclipArea(ctx);
  18951. }
  18952. }
  18953. }
  18954. };
  18955. var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;
  18956. var noop$1 = helpers$1.noop;
  18957. var valueOrDefault$e = helpers$1.valueOrDefault;
  18958. core_defaults._set('global', {
  18959. legend: {
  18960. display: true,
  18961. position: 'top',
  18962. align: 'center',
  18963. fullWidth: true,
  18964. reverse: false,
  18965. weight: 1000,
  18966. // a callback that will handle
  18967. onClick: function(e, legendItem) {
  18968. var index = legendItem.datasetIndex;
  18969. var ci = this.chart;
  18970. var meta = ci.getDatasetMeta(index);
  18971. // See controller.isDatasetVisible comment
  18972. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  18973. // We hid a dataset ... rerender the chart
  18974. ci.update();
  18975. },
  18976. onHover: null,
  18977. onLeave: null,
  18978. labels: {
  18979. boxWidth: 40,
  18980. padding: 10,
  18981. // Generates labels shown in the legend
  18982. // Valid properties to return:
  18983. // text : text to display
  18984. // fillStyle : fill of coloured box
  18985. // strokeStyle: stroke of coloured box
  18986. // hidden : if this legend item refers to a hidden item
  18987. // lineCap : cap style for line
  18988. // lineDash
  18989. // lineDashOffset :
  18990. // lineJoin :
  18991. // lineWidth :
  18992. generateLabels: function(chart) {
  18993. var datasets = chart.data.datasets;
  18994. var options = chart.options.legend || {};
  18995. var usePointStyle = options.labels && options.labels.usePointStyle;
  18996. return chart._getSortedDatasetMetas().map(function(meta) {
  18997. var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  18998. return {
  18999. text: datasets[meta.index].label,
  19000. fillStyle: style.backgroundColor,
  19001. hidden: !chart.isDatasetVisible(meta.index),
  19002. lineCap: style.borderCapStyle,
  19003. lineDash: style.borderDash,
  19004. lineDashOffset: style.borderDashOffset,
  19005. lineJoin: style.borderJoinStyle,
  19006. lineWidth: style.borderWidth,
  19007. strokeStyle: style.borderColor,
  19008. pointStyle: style.pointStyle,
  19009. rotation: style.rotation,
  19010. // Below is extra data used for toggling the datasets
  19011. datasetIndex: meta.index
  19012. };
  19013. }, this);
  19014. }
  19015. }
  19016. },
  19017. legendCallback: function(chart) {
  19018. var list = document.createElement('ul');
  19019. var datasets = chart.data.datasets;
  19020. var i, ilen, listItem, listItemSpan;
  19021. list.setAttribute('class', chart.id + '-legend');
  19022. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  19023. listItem = list.appendChild(document.createElement('li'));
  19024. listItemSpan = listItem.appendChild(document.createElement('span'));
  19025. listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
  19026. if (datasets[i].label) {
  19027. listItem.appendChild(document.createTextNode(datasets[i].label));
  19028. }
  19029. }
  19030. return list.outerHTML;
  19031. }
  19032. });
  19033. /**
  19034. * Helper function to get the box width based on the usePointStyle option
  19035. * @param {object} labelopts - the label options on the legend
  19036. * @param {number} fontSize - the label font size
  19037. * @return {number} width of the color box area
  19038. */
  19039. function getBoxWidth(labelOpts, fontSize) {
  19040. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  19041. fontSize :
  19042. labelOpts.boxWidth;
  19043. }
  19044. /**
  19045. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  19046. */
  19047. var Legend = core_element.extend({
  19048. initialize: function(config) {
  19049. var me = this;
  19050. helpers$1.extend(me, config);
  19051. // Contains hit boxes for each dataset (in dataset order)
  19052. me.legendHitBoxes = [];
  19053. /**
  19054. * @private
  19055. */
  19056. me._hoveredItem = null;
  19057. // Are we in doughnut mode which has a different data type
  19058. me.doughnutMode = false;
  19059. },
  19060. // These methods are ordered by lifecycle. Utilities then follow.
  19061. // Any function defined here is inherited by all legend types.
  19062. // Any function can be extended by the legend type
  19063. beforeUpdate: noop$1,
  19064. update: function(maxWidth, maxHeight, margins) {
  19065. var me = this;
  19066. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  19067. me.beforeUpdate();
  19068. // Absorb the master measurements
  19069. me.maxWidth = maxWidth;
  19070. me.maxHeight = maxHeight;
  19071. me.margins = margins;
  19072. // Dimensions
  19073. me.beforeSetDimensions();
  19074. me.setDimensions();
  19075. me.afterSetDimensions();
  19076. // Labels
  19077. me.beforeBuildLabels();
  19078. me.buildLabels();
  19079. me.afterBuildLabels();
  19080. // Fit
  19081. me.beforeFit();
  19082. me.fit();
  19083. me.afterFit();
  19084. //
  19085. me.afterUpdate();
  19086. return me.minSize;
  19087. },
  19088. afterUpdate: noop$1,
  19089. //
  19090. beforeSetDimensions: noop$1,
  19091. setDimensions: function() {
  19092. var me = this;
  19093. // Set the unconstrained dimension before label rotation
  19094. if (me.isHorizontal()) {
  19095. // Reset position before calculating rotation
  19096. me.width = me.maxWidth;
  19097. me.left = 0;
  19098. me.right = me.width;
  19099. } else {
  19100. me.height = me.maxHeight;
  19101. // Reset position before calculating rotation
  19102. me.top = 0;
  19103. me.bottom = me.height;
  19104. }
  19105. // Reset padding
  19106. me.paddingLeft = 0;
  19107. me.paddingTop = 0;
  19108. me.paddingRight = 0;
  19109. me.paddingBottom = 0;
  19110. // Reset minSize
  19111. me.minSize = {
  19112. width: 0,
  19113. height: 0
  19114. };
  19115. },
  19116. afterSetDimensions: noop$1,
  19117. //
  19118. beforeBuildLabels: noop$1,
  19119. buildLabels: function() {
  19120. var me = this;
  19121. var labelOpts = me.options.labels || {};
  19122. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  19123. if (labelOpts.filter) {
  19124. legendItems = legendItems.filter(function(item) {
  19125. return labelOpts.filter(item, me.chart.data);
  19126. });
  19127. }
  19128. if (me.options.reverse) {
  19129. legendItems.reverse();
  19130. }
  19131. me.legendItems = legendItems;
  19132. },
  19133. afterBuildLabels: noop$1,
  19134. //
  19135. beforeFit: noop$1,
  19136. fit: function() {
  19137. var me = this;
  19138. var opts = me.options;
  19139. var labelOpts = opts.labels;
  19140. var display = opts.display;
  19141. var ctx = me.ctx;
  19142. var labelFont = helpers$1.options._parseFont(labelOpts);
  19143. var fontSize = labelFont.size;
  19144. // Reset hit boxes
  19145. var hitboxes = me.legendHitBoxes = [];
  19146. var minSize = me.minSize;
  19147. var isHorizontal = me.isHorizontal();
  19148. if (isHorizontal) {
  19149. minSize.width = me.maxWidth; // fill all the width
  19150. minSize.height = display ? 10 : 0;
  19151. } else {
  19152. minSize.width = display ? 10 : 0;
  19153. minSize.height = me.maxHeight; // fill all the height
  19154. }
  19155. // Increase sizes here
  19156. if (!display) {
  19157. me.width = minSize.width = me.height = minSize.height = 0;
  19158. return;
  19159. }
  19160. ctx.font = labelFont.string;
  19161. if (isHorizontal) {
  19162. // Labels
  19163. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  19164. var lineWidths = me.lineWidths = [0];
  19165. var totalHeight = 0;
  19166. ctx.textAlign = 'left';
  19167. ctx.textBaseline = 'middle';
  19168. helpers$1.each(me.legendItems, function(legendItem, i) {
  19169. var boxWidth = getBoxWidth(labelOpts, fontSize);
  19170. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  19171. if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {
  19172. totalHeight += fontSize + labelOpts.padding;
  19173. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  19174. }
  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: width,
  19180. height: fontSize
  19181. };
  19182. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  19183. });
  19184. minSize.height += totalHeight;
  19185. } else {
  19186. var vPadding = labelOpts.padding;
  19187. var columnWidths = me.columnWidths = [];
  19188. var columnHeights = me.columnHeights = [];
  19189. var totalWidth = labelOpts.padding;
  19190. var currentColWidth = 0;
  19191. var currentColHeight = 0;
  19192. helpers$1.each(me.legendItems, function(legendItem, i) {
  19193. var boxWidth = getBoxWidth(labelOpts, fontSize);
  19194. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  19195. // If too tall, go to new column
  19196. if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) {
  19197. totalWidth += currentColWidth + labelOpts.padding;
  19198. columnWidths.push(currentColWidth); // previous column width
  19199. columnHeights.push(currentColHeight);
  19200. currentColWidth = 0;
  19201. currentColHeight = 0;
  19202. }
  19203. // Get max width
  19204. currentColWidth = Math.max(currentColWidth, itemWidth);
  19205. currentColHeight += fontSize + vPadding;
  19206. // Store the hitbox width and height here. Final position will be updated in `draw`
  19207. hitboxes[i] = {
  19208. left: 0,
  19209. top: 0,
  19210. width: itemWidth,
  19211. height: fontSize
  19212. };
  19213. });
  19214. totalWidth += currentColWidth;
  19215. columnWidths.push(currentColWidth);
  19216. columnHeights.push(currentColHeight);
  19217. minSize.width += totalWidth;
  19218. }
  19219. me.width = minSize.width;
  19220. me.height = minSize.height;
  19221. },
  19222. afterFit: noop$1,
  19223. // Shared Methods
  19224. isHorizontal: function() {
  19225. return this.options.position === 'top' || this.options.position === 'bottom';
  19226. },
  19227. // Actually draw the legend on the canvas
  19228. draw: function() {
  19229. var me = this;
  19230. var opts = me.options;
  19231. var labelOpts = opts.labels;
  19232. var globalDefaults = core_defaults.global;
  19233. var defaultColor = globalDefaults.defaultColor;
  19234. var lineDefault = globalDefaults.elements.line;
  19235. var legendHeight = me.height;
  19236. var columnHeights = me.columnHeights;
  19237. var legendWidth = me.width;
  19238. var lineWidths = me.lineWidths;
  19239. if (!opts.display) {
  19240. return;
  19241. }
  19242. var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);
  19243. var ctx = me.ctx;
  19244. var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);
  19245. var labelFont = helpers$1.options._parseFont(labelOpts);
  19246. var fontSize = labelFont.size;
  19247. var cursor;
  19248. // Canvas setup
  19249. ctx.textAlign = rtlHelper.textAlign('left');
  19250. ctx.textBaseline = 'middle';
  19251. ctx.lineWidth = 0.5;
  19252. ctx.strokeStyle = fontColor; // for strikethrough effect
  19253. ctx.fillStyle = fontColor; // render in correct colour
  19254. ctx.font = labelFont.string;
  19255. var boxWidth = getBoxWidth(labelOpts, fontSize);
  19256. var hitboxes = me.legendHitBoxes;
  19257. // current position
  19258. var drawLegendBox = function(x, y, legendItem) {
  19259. if (isNaN(boxWidth) || boxWidth <= 0) {
  19260. return;
  19261. }
  19262. // Set the ctx for the box
  19263. ctx.save();
  19264. var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);
  19265. ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);
  19266. ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);
  19267. ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  19268. ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);
  19269. ctx.lineWidth = lineWidth;
  19270. ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);
  19271. if (ctx.setLineDash) {
  19272. // IE 9 and 10 do not support line dash
  19273. ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));
  19274. }
  19275. if (labelOpts && labelOpts.usePointStyle) {
  19276. // Recalculate x and y for drawPoint() because its expecting
  19277. // x and y to be center of figure (instead of top left)
  19278. var radius = boxWidth * Math.SQRT2 / 2;
  19279. var centerX = rtlHelper.xPlus(x, boxWidth / 2);
  19280. var centerY = y + fontSize / 2;
  19281. // Draw pointStyle as legend symbol
  19282. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
  19283. } else {
  19284. // Draw box as legend symbol
  19285. ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  19286. if (lineWidth !== 0) {
  19287. ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  19288. }
  19289. }
  19290. ctx.restore();
  19291. };
  19292. var fillText = function(x, y, legendItem, textWidth) {
  19293. var halfFontSize = fontSize / 2;
  19294. var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
  19295. var yMiddle = y + halfFontSize;
  19296. ctx.fillText(legendItem.text, xLeft, yMiddle);
  19297. if (legendItem.hidden) {
  19298. // Strikethrough the text if hidden
  19299. ctx.beginPath();
  19300. ctx.lineWidth = 2;
  19301. ctx.moveTo(xLeft, yMiddle);
  19302. ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);
  19303. ctx.stroke();
  19304. }
  19305. };
  19306. var alignmentOffset = function(dimension, blockSize) {
  19307. switch (opts.align) {
  19308. case 'start':
  19309. return labelOpts.padding;
  19310. case 'end':
  19311. return dimension - blockSize;
  19312. default: // center
  19313. return (dimension - blockSize + labelOpts.padding) / 2;
  19314. }
  19315. };
  19316. // Horizontal
  19317. var isHorizontal = me.isHorizontal();
  19318. if (isHorizontal) {
  19319. cursor = {
  19320. x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
  19321. y: me.top + labelOpts.padding,
  19322. line: 0
  19323. };
  19324. } else {
  19325. cursor = {
  19326. x: me.left + labelOpts.padding,
  19327. y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
  19328. line: 0
  19329. };
  19330. }
  19331. helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);
  19332. var itemHeight = fontSize + labelOpts.padding;
  19333. helpers$1.each(me.legendItems, function(legendItem, i) {
  19334. var textWidth = ctx.measureText(legendItem.text).width;
  19335. var width = boxWidth + (fontSize / 2) + textWidth;
  19336. var x = cursor.x;
  19337. var y = cursor.y;
  19338. rtlHelper.setWidth(me.minSize.width);
  19339. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  19340. // instead of me.right and me.bottom because me.width and me.height
  19341. // may have been changed since me.minSize was calculated
  19342. if (isHorizontal) {
  19343. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  19344. y = cursor.y += itemHeight;
  19345. cursor.line++;
  19346. x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
  19347. }
  19348. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  19349. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  19350. cursor.line++;
  19351. y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
  19352. }
  19353. var realX = rtlHelper.x(x);
  19354. drawLegendBox(realX, y, legendItem);
  19355. hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);
  19356. hitboxes[i].top = y;
  19357. // Fill the actual label
  19358. fillText(realX, y, legendItem, textWidth);
  19359. if (isHorizontal) {
  19360. cursor.x += width + labelOpts.padding;
  19361. } else {
  19362. cursor.y += itemHeight;
  19363. }
  19364. });
  19365. helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);
  19366. },
  19367. /**
  19368. * @private
  19369. */
  19370. _getLegendItemAt: function(x, y) {
  19371. var me = this;
  19372. var i, hitBox, lh;
  19373. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  19374. // See if we are touching one of the dataset boxes
  19375. lh = me.legendHitBoxes;
  19376. for (i = 0; i < lh.length; ++i) {
  19377. hitBox = lh[i];
  19378. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  19379. // Touching an element
  19380. return me.legendItems[i];
  19381. }
  19382. }
  19383. }
  19384. return null;
  19385. },
  19386. /**
  19387. * Handle an event
  19388. * @private
  19389. * @param {IEvent} event - The event to handle
  19390. */
  19391. handleEvent: function(e) {
  19392. var me = this;
  19393. var opts = me.options;
  19394. var type = e.type === 'mouseup' ? 'click' : e.type;
  19395. var hoveredItem;
  19396. if (type === 'mousemove') {
  19397. if (!opts.onHover && !opts.onLeave) {
  19398. return;
  19399. }
  19400. } else if (type === 'click') {
  19401. if (!opts.onClick) {
  19402. return;
  19403. }
  19404. } else {
  19405. return;
  19406. }
  19407. // Chart event already has relative position in it
  19408. hoveredItem = me._getLegendItemAt(e.x, e.y);
  19409. if (type === 'click') {
  19410. if (hoveredItem && opts.onClick) {
  19411. // use e.native for backwards compatibility
  19412. opts.onClick.call(me, e.native, hoveredItem);
  19413. }
  19414. } else {
  19415. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  19416. if (me._hoveredItem) {
  19417. opts.onLeave.call(me, e.native, me._hoveredItem);
  19418. }
  19419. me._hoveredItem = hoveredItem;
  19420. }
  19421. if (opts.onHover && hoveredItem) {
  19422. // use e.native for backwards compatibility
  19423. opts.onHover.call(me, e.native, hoveredItem);
  19424. }
  19425. }
  19426. }
  19427. });
  19428. function createNewLegendAndAttach(chart, legendOpts) {
  19429. var legend = new Legend({
  19430. ctx: chart.ctx,
  19431. options: legendOpts,
  19432. chart: chart
  19433. });
  19434. core_layouts.configure(chart, legend, legendOpts);
  19435. core_layouts.addBox(chart, legend);
  19436. chart.legend = legend;
  19437. }
  19438. var plugin_legend = {
  19439. id: 'legend',
  19440. /**
  19441. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  19442. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  19443. * the plugin, which one will be re-exposed in the chart.js file.
  19444. * https://github.com/chartjs/Chart.js/pull/2640
  19445. * @private
  19446. */
  19447. _element: Legend,
  19448. beforeInit: function(chart) {
  19449. var legendOpts = chart.options.legend;
  19450. if (legendOpts) {
  19451. createNewLegendAndAttach(chart, legendOpts);
  19452. }
  19453. },
  19454. beforeUpdate: function(chart) {
  19455. var legendOpts = chart.options.legend;
  19456. var legend = chart.legend;
  19457. if (legendOpts) {
  19458. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  19459. if (legend) {
  19460. core_layouts.configure(chart, legend, legendOpts);
  19461. legend.options = legendOpts;
  19462. } else {
  19463. createNewLegendAndAttach(chart, legendOpts);
  19464. }
  19465. } else if (legend) {
  19466. core_layouts.removeBox(chart, legend);
  19467. delete chart.legend;
  19468. }
  19469. },
  19470. afterEvent: function(chart, e) {
  19471. var legend = chart.legend;
  19472. if (legend) {
  19473. legend.handleEvent(e);
  19474. }
  19475. }
  19476. };
  19477. var noop$2 = helpers$1.noop;
  19478. core_defaults._set('global', {
  19479. title: {
  19480. display: false,
  19481. fontStyle: 'bold',
  19482. fullWidth: true,
  19483. padding: 10,
  19484. position: 'top',
  19485. text: '',
  19486. weight: 2000 // by default greater than legend (1000) to be above
  19487. }
  19488. });
  19489. /**
  19490. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  19491. */
  19492. var Title = core_element.extend({
  19493. initialize: function(config) {
  19494. var me = this;
  19495. helpers$1.extend(me, config);
  19496. // Contains hit boxes for each dataset (in dataset order)
  19497. me.legendHitBoxes = [];
  19498. },
  19499. // These methods are ordered by lifecycle. Utilities then follow.
  19500. beforeUpdate: noop$2,
  19501. update: function(maxWidth, maxHeight, margins) {
  19502. var me = this;
  19503. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  19504. me.beforeUpdate();
  19505. // Absorb the master measurements
  19506. me.maxWidth = maxWidth;
  19507. me.maxHeight = maxHeight;
  19508. me.margins = margins;
  19509. // Dimensions
  19510. me.beforeSetDimensions();
  19511. me.setDimensions();
  19512. me.afterSetDimensions();
  19513. // Labels
  19514. me.beforeBuildLabels();
  19515. me.buildLabels();
  19516. me.afterBuildLabels();
  19517. // Fit
  19518. me.beforeFit();
  19519. me.fit();
  19520. me.afterFit();
  19521. //
  19522. me.afterUpdate();
  19523. return me.minSize;
  19524. },
  19525. afterUpdate: noop$2,
  19526. //
  19527. beforeSetDimensions: noop$2,
  19528. setDimensions: function() {
  19529. var me = this;
  19530. // Set the unconstrained dimension before label rotation
  19531. if (me.isHorizontal()) {
  19532. // Reset position before calculating rotation
  19533. me.width = me.maxWidth;
  19534. me.left = 0;
  19535. me.right = me.width;
  19536. } else {
  19537. me.height = me.maxHeight;
  19538. // Reset position before calculating rotation
  19539. me.top = 0;
  19540. me.bottom = me.height;
  19541. }
  19542. // Reset padding
  19543. me.paddingLeft = 0;
  19544. me.paddingTop = 0;
  19545. me.paddingRight = 0;
  19546. me.paddingBottom = 0;
  19547. // Reset minSize
  19548. me.minSize = {
  19549. width: 0,
  19550. height: 0
  19551. };
  19552. },
  19553. afterSetDimensions: noop$2,
  19554. //
  19555. beforeBuildLabels: noop$2,
  19556. buildLabels: noop$2,
  19557. afterBuildLabels: noop$2,
  19558. //
  19559. beforeFit: noop$2,
  19560. fit: function() {
  19561. var me = this;
  19562. var opts = me.options;
  19563. var minSize = me.minSize = {};
  19564. var isHorizontal = me.isHorizontal();
  19565. var lineCount, textSize;
  19566. if (!opts.display) {
  19567. me.width = minSize.width = me.height = minSize.height = 0;
  19568. return;
  19569. }
  19570. lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  19571. textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;
  19572. me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
  19573. me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
  19574. },
  19575. afterFit: noop$2,
  19576. // Shared Methods
  19577. isHorizontal: function() {
  19578. var pos = this.options.position;
  19579. return pos === 'top' || pos === 'bottom';
  19580. },
  19581. // Actually draw the title block on the canvas
  19582. draw: function() {
  19583. var me = this;
  19584. var ctx = me.ctx;
  19585. var opts = me.options;
  19586. if (!opts.display) {
  19587. return;
  19588. }
  19589. var fontOpts = helpers$1.options._parseFont(opts);
  19590. var lineHeight = fontOpts.lineHeight;
  19591. var offset = lineHeight / 2 + opts.padding;
  19592. var rotation = 0;
  19593. var top = me.top;
  19594. var left = me.left;
  19595. var bottom = me.bottom;
  19596. var right = me.right;
  19597. var maxWidth, titleX, titleY;
  19598. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  19599. ctx.font = fontOpts.string;
  19600. // Horizontal
  19601. if (me.isHorizontal()) {
  19602. titleX = left + ((right - left) / 2); // midpoint of the width
  19603. titleY = top + offset;
  19604. maxWidth = right - left;
  19605. } else {
  19606. titleX = opts.position === 'left' ? left + offset : right - offset;
  19607. titleY = top + ((bottom - top) / 2);
  19608. maxWidth = bottom - top;
  19609. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  19610. }
  19611. ctx.save();
  19612. ctx.translate(titleX, titleY);
  19613. ctx.rotate(rotation);
  19614. ctx.textAlign = 'center';
  19615. ctx.textBaseline = 'middle';
  19616. var text = opts.text;
  19617. if (helpers$1.isArray(text)) {
  19618. var y = 0;
  19619. for (var i = 0; i < text.length; ++i) {
  19620. ctx.fillText(text[i], 0, y, maxWidth);
  19621. y += lineHeight;
  19622. }
  19623. } else {
  19624. ctx.fillText(text, 0, 0, maxWidth);
  19625. }
  19626. ctx.restore();
  19627. }
  19628. });
  19629. function createNewTitleBlockAndAttach(chart, titleOpts) {
  19630. var title = new Title({
  19631. ctx: chart.ctx,
  19632. options: titleOpts,
  19633. chart: chart
  19634. });
  19635. core_layouts.configure(chart, title, titleOpts);
  19636. core_layouts.addBox(chart, title);
  19637. chart.titleBlock = title;
  19638. }
  19639. var plugin_title = {
  19640. id: 'title',
  19641. /**
  19642. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  19643. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  19644. * the plugin, which one will be re-exposed in the chart.js file.
  19645. * https://github.com/chartjs/Chart.js/pull/2640
  19646. * @private
  19647. */
  19648. _element: Title,
  19649. beforeInit: function(chart) {
  19650. var titleOpts = chart.options.title;
  19651. if (titleOpts) {
  19652. createNewTitleBlockAndAttach(chart, titleOpts);
  19653. }
  19654. },
  19655. beforeUpdate: function(chart) {
  19656. var titleOpts = chart.options.title;
  19657. var titleBlock = chart.titleBlock;
  19658. if (titleOpts) {
  19659. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  19660. if (titleBlock) {
  19661. core_layouts.configure(chart, titleBlock, titleOpts);
  19662. titleBlock.options = titleOpts;
  19663. } else {
  19664. createNewTitleBlockAndAttach(chart, titleOpts);
  19665. }
  19666. } else if (titleBlock) {
  19667. core_layouts.removeBox(chart, titleBlock);
  19668. delete chart.titleBlock;
  19669. }
  19670. }
  19671. };
  19672. var plugins = {};
  19673. var filler = plugin_filler;
  19674. var legend = plugin_legend;
  19675. var title = plugin_title;
  19676. plugins.filler = filler;
  19677. plugins.legend = legend;
  19678. plugins.title = title;
  19679. /**
  19680. * @namespace Chart
  19681. */
  19682. core_controller.helpers = helpers$1;
  19683. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  19684. core_helpers();
  19685. core_controller._adapters = core_adapters;
  19686. core_controller.Animation = core_animation;
  19687. core_controller.animationService = core_animations;
  19688. core_controller.controllers = controllers;
  19689. core_controller.DatasetController = core_datasetController;
  19690. core_controller.defaults = core_defaults;
  19691. core_controller.Element = core_element;
  19692. core_controller.elements = elements;
  19693. core_controller.Interaction = core_interaction;
  19694. core_controller.layouts = core_layouts;
  19695. core_controller.platform = platform;
  19696. core_controller.plugins = core_plugins;
  19697. core_controller.Scale = core_scale;
  19698. core_controller.scaleService = core_scaleService;
  19699. core_controller.Ticks = core_ticks;
  19700. core_controller.Tooltip = core_tooltip;
  19701. // Register built-in scales
  19702. core_controller.helpers.each(scales, function(scale, type) {
  19703. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  19704. });
  19705. // Load to register built-in adapters (as side effects)
  19706. // Loading built-in plugins
  19707. for (var k in plugins) {
  19708. if (plugins.hasOwnProperty(k)) {
  19709. core_controller.plugins.register(plugins[k]);
  19710. }
  19711. }
  19712. core_controller.platform.initialize();
  19713. var src = core_controller;
  19714. if (typeof window !== 'undefined') {
  19715. window.Chart = core_controller;
  19716. }
  19717. // DEPRECATIONS
  19718. /**
  19719. * Provided for backward compatibility, not available anymore
  19720. * @namespace Chart.Chart
  19721. * @deprecated since version 2.8.0
  19722. * @todo remove at version 3
  19723. * @private
  19724. */
  19725. core_controller.Chart = core_controller;
  19726. /**
  19727. * Provided for backward compatibility, not available anymore
  19728. * @namespace Chart.Legend
  19729. * @deprecated since version 2.1.5
  19730. * @todo remove at version 3
  19731. * @private
  19732. */
  19733. core_controller.Legend = plugins.legend._element;
  19734. /**
  19735. * Provided for backward compatibility, not available anymore
  19736. * @namespace Chart.Title
  19737. * @deprecated since version 2.1.5
  19738. * @todo remove at version 3
  19739. * @private
  19740. */
  19741. core_controller.Title = plugins.title._element;
  19742. /**
  19743. * Provided for backward compatibility, use Chart.plugins instead
  19744. * @namespace Chart.pluginService
  19745. * @deprecated since version 2.1.5
  19746. * @todo remove at version 3
  19747. * @private
  19748. */
  19749. core_controller.pluginService = core_controller.plugins;
  19750. /**
  19751. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  19752. * effect, instead simply create/register plugins via plain JavaScript objects.
  19753. * @interface Chart.PluginBase
  19754. * @deprecated since version 2.5.0
  19755. * @todo remove at version 3
  19756. * @private
  19757. */
  19758. core_controller.PluginBase = core_controller.Element.extend({});
  19759. /**
  19760. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  19761. * @namespace Chart.canvasHelpers
  19762. * @deprecated since version 2.6.0
  19763. * @todo remove at version 3
  19764. * @private
  19765. */
  19766. core_controller.canvasHelpers = core_controller.helpers.canvas;
  19767. /**
  19768. * Provided for backward compatibility, use Chart.layouts instead.
  19769. * @namespace Chart.layoutService
  19770. * @deprecated since version 2.7.3
  19771. * @todo remove at version 3
  19772. * @private
  19773. */
  19774. core_controller.layoutService = core_controller.layouts;
  19775. /**
  19776. * Provided for backward compatibility, not available anymore.
  19777. * @namespace Chart.LinearScaleBase
  19778. * @deprecated since version 2.8
  19779. * @todo remove at version 3
  19780. * @private
  19781. */
  19782. core_controller.LinearScaleBase = scale_linearbase;
  19783. /**
  19784. * Provided for backward compatibility, instead we should create a new Chart
  19785. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  19786. * @deprecated since version 2.8.0
  19787. * @todo remove at version 3
  19788. */
  19789. core_controller.helpers.each(
  19790. [
  19791. 'Bar',
  19792. 'Bubble',
  19793. 'Doughnut',
  19794. 'Line',
  19795. 'PolarArea',
  19796. 'Radar',
  19797. 'Scatter'
  19798. ],
  19799. function(klass) {
  19800. core_controller[klass] = function(ctx, cfg) {
  19801. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  19802. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  19803. }));
  19804. };
  19805. }
  19806. );
  19807. return src;
  19808. })));
  19809. } (Chart$2));
  19810. return Chart$2.exports;
  19811. }
  19812. var ChartExports = requireChart();
  19813. var Chart = /*@__PURE__*/getDefaultExportFromCjs(ChartExports);
  19814. // Modify horizontalBar so that each dataset (fragments, timeRanges) draws on the same row (level, track or buffer)
  19815. Chart.controllers.horizontalBar.prototype.calculateBarValuePixels = function (datasetIndex, index, options) {
  19816. var chart = this.chart;
  19817. var scale = this._getValueScale();
  19818. var datasets = chart.data.datasets;
  19819. if (!datasets) {
  19820. throw new Error("Chart datasets are " + datasets);
  19821. }
  19822. scale._parseValue = scaleParseValue;
  19823. var obj = datasets[datasetIndex].data[index];
  19824. var value = scale._parseValue(obj);
  19825. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  19826. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  19827. var base = scale.getPixelForValue(start);
  19828. var head = scale.getPixelForValue(start + length);
  19829. var size = head - base;
  19830. return {
  19831. size: size,
  19832. base: base,
  19833. head: head,
  19834. center: head + size / 2
  19835. };
  19836. };
  19837. Chart.controllers.horizontalBar.prototype.calculateBarIndexPixels = function (datasetIndex, index, ruler, options) {
  19838. var rowHeight = options.barThickness;
  19839. var size = rowHeight * options.categoryPercentage;
  19840. var center = ruler.start + (datasetIndex * rowHeight + rowHeight / 2);
  19841. return {
  19842. base: center - size / 2,
  19843. head: center + size / 2,
  19844. center: center,
  19845. size: size
  19846. };
  19847. };
  19848. Chart.controllers.horizontalBar.prototype.draw = function () {
  19849. var rects = this.getMeta().data;
  19850. var len = rects.length;
  19851. var dataset = this.getDataset();
  19852. if (len !== dataset.data.length) {
  19853. // View does not match dataset (wait for redraw)
  19854. return;
  19855. }
  19856. var chart = this.chart;
  19857. var scale = this._getValueScale();
  19858. scale._parseValue = scaleParseValue;
  19859. var ctx = chart.ctx;
  19860. var chartArea = chart.chartArea;
  19861. Chart.helpers.canvas.clipArea(ctx, chartArea);
  19862. if (!this.lineHeight) {
  19863. this.lineHeight = Math.ceil(ctx.measureText('0').actualBoundingBoxAscent) + 2;
  19864. }
  19865. var lineHeight = this.lineHeight;
  19866. var range = 0;
  19867. for (var i = 0; i < len; ++i) {
  19868. var rect = rects[i];
  19869. var view = rect._view;
  19870. if (!intersects(view.base, view.x, chartArea.left, chartArea.right)) {
  19871. // Do not draw elements outside of the chart's viewport
  19872. continue;
  19873. }
  19874. var obj = dataset.data[i];
  19875. var val = scale._parseValue(obj);
  19876. if (!isNaN(val.min) && !isNaN(val.max)) {
  19877. var dataType = obj.dataType;
  19878. var stats = obj.stats;
  19879. var isPart = dataType === 'part';
  19880. var isFragmentHint = dataType === 'fragmentHint';
  19881. var isFragment = dataType === 'fragment' || isPart || isFragmentHint;
  19882. var isCue = dataType === 'cue';
  19883. if (isCue) {
  19884. view.y += view.height * 0.5 * (i % 2) - view.height * 0.25;
  19885. } else if (isPart) {
  19886. view.height -= 22;
  19887. }
  19888. var bounds = boundingRects(view);
  19889. var drawText = bounds.w > lineHeight * 1.5 && !isFragmentHint;
  19890. if (isFragment || isCue) {
  19891. if (drawText) {
  19892. view.borderWidth = 1;
  19893. if (i === 0) {
  19894. view.borderSkipped = false;
  19895. }
  19896. } else {
  19897. range = range || scale.getValueForPixel(chartArea.right) - scale.getValueForPixel(chartArea.left);
  19898. if (range > 300 || isCue) {
  19899. view.borderWidth = 0;
  19900. }
  19901. }
  19902. if (isFragmentHint) {
  19903. view.borderWidth = 0;
  19904. view.backgroundColor = 'rgba(0, 0, 0, 0.1)';
  19905. } else {
  19906. view.backgroundColor = "rgba(0, 0, 0, " + (0.05 + i % 2 / 12) + ")";
  19907. }
  19908. }
  19909. rect.draw();
  19910. if (isFragment) {
  19911. if (!stats) {
  19912. stats = {};
  19913. }
  19914. if (isPart) {
  19915. ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
  19916. ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
  19917. }
  19918. if (stats.aborted) {
  19919. ctx.fillStyle = 'rgba(100, 0, 0, 0.3)';
  19920. ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
  19921. }
  19922. if (stats.loaded && stats.total) {
  19923. ctx.fillStyle = 'rgba(50, 20, 100, 0.3)';
  19924. ctx.fillRect(bounds.x, bounds.y, bounds.w * stats.loaded / stats.total, bounds.h);
  19925. }
  19926. } else if (isCue) {
  19927. if (obj.active) {
  19928. ctx.fillStyle = 'rgba(100, 100, 10, 0.4)';
  19929. ctx.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
  19930. }
  19931. }
  19932. if (drawText) {
  19933. var start = val.start; // obj.start;
  19934. ctx.fillStyle = 'rgb(0, 0, 0)';
  19935. if (stats) {
  19936. var snBounds = _extends({}, bounds);
  19937. if (obj.cc) {
  19938. var ccLabel = "cc:" + obj.cc;
  19939. var ccWidth = Math.min(ctx.measureText(ccLabel).width + 2, snBounds.w / 2 - 2);
  19940. if (ccWidth) {
  19941. ctx.fillText(ccLabel, snBounds.x + 2, snBounds.y + lineHeight, snBounds.w / 2 - 4);
  19942. snBounds.x += ccWidth;
  19943. snBounds.w -= ccWidth;
  19944. }
  19945. }
  19946. var snLabel = isPart ? "part: " + obj.index : "sn: " + obj.sn;
  19947. var textWidth = Math.min(ctx.measureText(snLabel).width + 2, snBounds.w - 2);
  19948. ctx.fillText(snLabel, snBounds.x + snBounds.w - textWidth, snBounds.y + lineHeight, snBounds.w - 4);
  19949. }
  19950. if (isCue) {
  19951. var strLength = Math.min(30, Math.ceil(bounds.w / (lineHeight / 3)));
  19952. ctx.fillText(('' + obj.content).slice(0, strLength), bounds.x + 2, bounds.y + bounds.h - 3, bounds.w - 5);
  19953. } else if (!isPart) {
  19954. var _float = start !== (start | 0);
  19955. var fixedDigits = _float ? Math.min(5, Math.max(1, Math.floor(bounds.w / 10 - 1))) : 0;
  19956. var startString = hhmmss(start, fixedDigits);
  19957. ctx.fillText(startString, bounds.x + 2, bounds.y + bounds.h - 3, bounds.w - 5);
  19958. }
  19959. }
  19960. }
  19961. }
  19962. Chart.helpers.canvas.unclipArea(chart.ctx);
  19963. };
  19964. function applyChartInstanceOverrides(chart) {
  19965. Object.keys(chart.scales).forEach(function (axis) {
  19966. var scale = chart.scales[axis];
  19967. scale._parseValue = scaleParseValue;
  19968. });
  19969. }
  19970. function scaleParseValue(value) {
  19971. if (value === undefined) {
  19972. console.warn('Chart values undefined (update chart)');
  19973. return {};
  19974. }
  19975. var start;
  19976. var end;
  19977. var min;
  19978. var max;
  19979. if (Array.isArray(value)) {
  19980. start = +this.getRightValue(value[0]);
  19981. end = +this.getRightValue(value[1]);
  19982. min = Math.min(start, end);
  19983. max = Math.max(start, end);
  19984. } else {
  19985. start = +this.getRightValue(value.start);
  19986. if ('end' in value) {
  19987. end = +this.getRightValue(value.end);
  19988. } else {
  19989. end = +this.getRightValue(value.start + value.duration);
  19990. }
  19991. min = Math.min(start, end);
  19992. max = Math.max(start, end);
  19993. }
  19994. return {
  19995. min: min,
  19996. max: max,
  19997. start: start,
  19998. end: end
  19999. };
  20000. }
  20001. function intersects(x1, x2, x3, x4) {
  20002. return x2 > x3 && x1 < x4;
  20003. }
  20004. function boundingRects(vm) {
  20005. var half = vm.height / 2;
  20006. var left = Math.min(vm.x, vm.base);
  20007. var right = Math.max(vm.x, vm.base);
  20008. var top = vm.y - half;
  20009. var bottom = vm.y + half;
  20010. return {
  20011. x: left,
  20012. y: top,
  20013. w: right - left,
  20014. h: bottom - top
  20015. };
  20016. }
  20017. function hhmmss(value, fixedDigits) {
  20018. var h = value / 3600 | 0;
  20019. var m = (value / 60 | 0) % 60;
  20020. var s = value % 60;
  20021. return (h + ":" + pad(m, 2) + ":" + pad(s.toFixed(fixedDigits), fixedDigits ? fixedDigits + 3 : 2)).replace(/^(?:0+:?)*(\d.*?)(?:\.0*)?$/, '$1');
  20022. }
  20023. function pad(str, length) {
  20024. str = '' + str;
  20025. while (str.length < length) {
  20026. str = '0' + str;
  20027. }
  20028. return str;
  20029. }
  20030. var X_AXIS_SECONDS = 'x-axis-seconds';
  20031. var TimelineChart = /*#__PURE__*/function () {
  20032. function TimelineChart(canvas, chartJsOptions) {
  20033. var _this = this;
  20034. this.chart = void 0;
  20035. this.rafDebounceRequestId = -1;
  20036. this.imageDataBuffer = null;
  20037. this.media = null;
  20038. this.tracksChangeHandler = void 0;
  20039. this.cuesChangeHandler = void 0;
  20040. this.hidden = true;
  20041. this.zoom100 = 60;
  20042. var ctx = canvas.getContext('2d');
  20043. if (!ctx) {
  20044. throw new Error("Could not get CanvasRenderingContext2D from canvas: " + canvas);
  20045. }
  20046. var chart = this.chart = self.chart = new Chart(ctx, {
  20047. type: 'horizontalBar',
  20048. data: {
  20049. labels: [],
  20050. datasets: []
  20051. },
  20052. options: _extends(getChartOptions(), chartJsOptions),
  20053. plugins: [{
  20054. afterRender: function afterRender(chart) {
  20055. _this.imageDataBuffer = null;
  20056. _this.drawCurrentTime();
  20057. }
  20058. }]
  20059. });
  20060. applyChartInstanceOverrides(chart);
  20061. canvas.ondblclick = function (event) {
  20062. var chart = _this.chart;
  20063. var chartArea = chart.chartArea;
  20064. var element = chart.getElementAtEvent(event);
  20065. var pos = Chart.helpers.getRelativePosition(event, chart);
  20066. var scale = _this.chartScales[X_AXIS_SECONDS];
  20067. // zoom in when double clicking near elements in chart area
  20068. if (element.length || pos.x > chartArea.left) {
  20069. var amount = event.getModifierState('Shift') ? -1 : 0.5;
  20070. _this.zoom(scale, pos, amount);
  20071. } else {
  20072. scale.options.ticks.min = 0;
  20073. scale.options.ticks.max = _this.zoom100;
  20074. }
  20075. _this.update();
  20076. };
  20077. canvas.onwheel = function (event) {
  20078. if (event.deltaMode) {
  20079. // exit if wheel is in page or line scrolling mode
  20080. return;
  20081. }
  20082. var chart = _this.chart;
  20083. var chartArea = chart.chartArea;
  20084. var pos = Chart.helpers.getRelativePosition(event, chart);
  20085. // zoom when scrolling over chart elements
  20086. if (pos.x > chartArea.left - 11) {
  20087. var scale = _this.chartScales[X_AXIS_SECONDS];
  20088. if (event.deltaY) {
  20089. var direction = -event.deltaY / Math.abs(event.deltaY);
  20090. var normal = Math.min(333, Math.abs(event.deltaY)) / 1000;
  20091. var ease = 1 - (1 - normal) * (1 - normal);
  20092. _this.zoom(scale, pos, ease * direction);
  20093. } else if (event.deltaX) {
  20094. _this.pan(scale, event.deltaX / 10, scale.min, scale.max);
  20095. }
  20096. event.preventDefault();
  20097. }
  20098. };
  20099. var moved = false;
  20100. var gestureScale = 1;
  20101. canvas.onpointerdown = function (downEvent) {
  20102. if (!downEvent.isPrimary || gestureScale !== 1) {
  20103. return;
  20104. }
  20105. var chart = _this.chart;
  20106. var chartArea = chart.chartArea;
  20107. var pos = Chart.helpers.getRelativePosition(downEvent, chart);
  20108. // pan when dragging over chart elements
  20109. if (pos.x > chartArea.left) {
  20110. var scale = _this.chartScales[X_AXIS_SECONDS];
  20111. var startX = downEvent.clientX;
  20112. var min = scale.min,
  20113. max = scale.max;
  20114. var xToVal = (max - min) / scale.width;
  20115. moved = false;
  20116. canvas.setPointerCapture(downEvent.pointerId);
  20117. canvas.onpointermove = function (moveEvent) {
  20118. if (!downEvent.isPrimary || gestureScale !== 1) {
  20119. return;
  20120. }
  20121. var movedX = startX - moveEvent.clientX;
  20122. var movedValue = movedX * xToVal;
  20123. moved = moved || Math.abs(movedX) > 8;
  20124. _this.pan(scale, movedValue, min, max);
  20125. };
  20126. }
  20127. };
  20128. canvas.onpointerup = canvas.onpointercancel = function (upEvent) {
  20129. if (canvas.onpointermove) {
  20130. canvas.onpointermove = null;
  20131. canvas.releasePointerCapture(upEvent.pointerId);
  20132. }
  20133. if (!moved && upEvent.isPrimary) {
  20134. _this.click(upEvent);
  20135. }
  20136. };
  20137. // Gesture events are for iOS and easier to implement than pinch-zoom with multiple pointers for all browsers
  20138. // @ts-ignore
  20139. canvas.ongesturestart = function (event) {
  20140. gestureScale = 1;
  20141. event.preventDefault();
  20142. };
  20143. // @ts-ignore
  20144. canvas.ongestureend = function (event) {
  20145. gestureScale = 1;
  20146. };
  20147. // @ts-ignore
  20148. canvas.ongesturechange = function (event) {
  20149. var chart = _this.chart;
  20150. var chartArea = chart.chartArea;
  20151. var pos = Chart.helpers.getRelativePosition(event, chart);
  20152. // zoom when scrolling over chart elements
  20153. if (pos.x > chartArea.left) {
  20154. var scale = _this.chartScales[X_AXIS_SECONDS];
  20155. var amount = event.scale - gestureScale;
  20156. _this.zoom(scale, pos, amount);
  20157. gestureScale = event.scale;
  20158. }
  20159. };
  20160. }
  20161. var _proto = TimelineChart.prototype;
  20162. _proto.click = function click(event) {
  20163. // Log object on click and seek to position
  20164. var chart = this.chart;
  20165. var element = chart.getElementAtEvent(event);
  20166. if (element.length && chart.data.datasets) {
  20167. var _self$hls;
  20168. var dataset = chart.data.datasets[element[0]._datasetIndex];
  20169. var obj = dataset.data[element[0]._index];
  20170. // eslint-disable-next-line no-console
  20171. console.log(obj);
  20172. if ((_self$hls = self.hls) != null && _self$hls.media) {
  20173. var scale = this.chartScales[X_AXIS_SECONDS];
  20174. var pos = Chart.helpers.getRelativePosition(event, chart);
  20175. self.hls.media.currentTime = scale.getValueForPixel(pos.x);
  20176. }
  20177. }
  20178. };
  20179. _proto.pan = function pan(scale, amount, min, max) {
  20180. if (amount === 0) {
  20181. return;
  20182. }
  20183. var pan = amount;
  20184. if (amount > 0) {
  20185. pan = Math.min(this.zoom100 + 10 - max, amount);
  20186. } else {
  20187. pan = Math.max(-10 - min, amount);
  20188. }
  20189. scale.options.ticks.min = min + pan;
  20190. scale.options.ticks.max = max + pan;
  20191. this.updateOnRepaint();
  20192. };
  20193. _proto.zoom = function zoom(scale, pos, amount) {
  20194. var range = scale.max - scale.min;
  20195. var diff = range * amount;
  20196. var minPercent = (scale.getValueForPixel(pos.x) - scale.min) / range;
  20197. var maxPercent = 1 - minPercent;
  20198. var minDelta = diff * minPercent;
  20199. var maxDelta = diff * maxPercent;
  20200. scale.options.ticks.min = Math.max(-10, scale.min + minDelta);
  20201. scale.options.ticks.max = Math.min(this.zoom100 + 10, scale.max - maxDelta);
  20202. this.updateOnRepaint();
  20203. };
  20204. _proto.reset = function reset() {
  20205. var scale = this.chartScales[X_AXIS_SECONDS];
  20206. scale.options.ticks.min = 0;
  20207. scale.options.ticks.max = 60;
  20208. var _this$chart$data = this.chart.data,
  20209. labels = _this$chart$data.labels,
  20210. datasets = _this$chart$data.datasets;
  20211. if (labels && datasets) {
  20212. labels.length = 0;
  20213. datasets.length = 0;
  20214. this.resize(datasets);
  20215. }
  20216. };
  20217. _proto.update = function update() {
  20218. var _this$chart$ctx;
  20219. if (this.hidden || !((_this$chart$ctx = this.chart.ctx) != null && _this$chart$ctx.canvas.width)) {
  20220. return;
  20221. }
  20222. self.cancelAnimationFrame(this.rafDebounceRequestId);
  20223. this.chart.update({
  20224. duration: 0,
  20225. lazy: true
  20226. });
  20227. };
  20228. _proto.updateOnRepaint = function updateOnRepaint() {
  20229. var _this2 = this;
  20230. if (this.hidden) {
  20231. return;
  20232. }
  20233. self.cancelAnimationFrame(this.rafDebounceRequestId);
  20234. this.rafDebounceRequestId = self.requestAnimationFrame(function () {
  20235. return _this2.update();
  20236. });
  20237. };
  20238. _proto.resize = function resize(datasets) {
  20239. var _this3 = this;
  20240. if (this.hidden) {
  20241. return;
  20242. }
  20243. if (datasets != null && datasets.length) {
  20244. var _this$chart$canvas;
  20245. var scale = this.chartScales[X_AXIS_SECONDS];
  20246. var top = this.chart.chartArea.top;
  20247. var height = top + datasets.reduce(function (val, dataset) {
  20248. return val + dataset.barThickness;
  20249. }, 0) + scale.height + 5;
  20250. var container = (_this$chart$canvas = this.chart.canvas) == null ? void 0 : _this$chart$canvas.parentElement;
  20251. if (container) {
  20252. container.style.height = height + "px";
  20253. }
  20254. }
  20255. self.cancelAnimationFrame(this.rafDebounceRequestId);
  20256. this.rafDebounceRequestId = self.requestAnimationFrame(function () {
  20257. _this3.chart.resize();
  20258. });
  20259. };
  20260. _proto.show = function show() {
  20261. this.hidden = false;
  20262. };
  20263. _proto.hide = function hide() {
  20264. this.hidden = true;
  20265. };
  20266. _proto.updateLevels = function updateLevels(levels, levelSwitched) {
  20267. var _this4 = this;
  20268. var _this$chart$data2 = this.chart.data,
  20269. labels = _this$chart$data2.labels,
  20270. datasets = _this$chart$data2.datasets;
  20271. if (!labels || !datasets) {
  20272. return;
  20273. }
  20274. var _self$hls2 = self.hls,
  20275. loadLevel = _self$hls2.loadLevel,
  20276. nextLoadLevel = _self$hls2.nextLoadLevel,
  20277. nextAutoLevel = _self$hls2.nextAutoLevel;
  20278. // eslint-disable-next-line no-undefined
  20279. var currentLevel = levelSwitched !== undefined ? levelSwitched : self.hls.currentLevel;
  20280. levels.forEach(function (level, i) {
  20281. var index = level.id || i;
  20282. labels.push(getLevelName(level, index));
  20283. var borderColor = null;
  20284. if (currentLevel === i) {
  20285. borderColor = 'rgba(32, 32, 240, 1.0)';
  20286. } else if (loadLevel === i) {
  20287. borderColor = 'rgba(255, 128, 0, 1.0)';
  20288. } else if (nextLoadLevel === i) {
  20289. borderColor = 'rgba(200, 200, 64, 1.0)';
  20290. } else if (nextAutoLevel === i) {
  20291. borderColor = 'rgba(160, 0, 160, 1.0)';
  20292. }
  20293. datasets.push(datasetWithDefaults({
  20294. url: Array.isArray(level.url) ? level.url[level.urlId || 0] : level.url,
  20295. trackType: 'level',
  20296. borderColor: borderColor,
  20297. level: index
  20298. }));
  20299. if (level.details) {
  20300. _this4.updateLevelOrTrack(level.details);
  20301. }
  20302. });
  20303. this.resize(datasets);
  20304. };
  20305. _proto.updateAudioTracks = function updateAudioTracks(audioTracks) {
  20306. var _this5 = this;
  20307. var _this$chart$data3 = this.chart.data,
  20308. labels = _this$chart$data3.labels,
  20309. datasets = _this$chart$data3.datasets;
  20310. if (!labels || !datasets) {
  20311. return;
  20312. }
  20313. var audioTrack = self.hls.audioTrack;
  20314. audioTracks.forEach(function (track, i) {
  20315. labels.push(getAudioTrackName(track, i));
  20316. datasets.push(datasetWithDefaults({
  20317. url: track.url,
  20318. trackType: 'audioTrack',
  20319. borderColor: audioTrack === i ? 'rgba(32, 32, 240, 1.0)' : null,
  20320. audioTrack: i
  20321. }));
  20322. if (track.details) {
  20323. _this5.updateLevelOrTrack(track.details);
  20324. }
  20325. });
  20326. this.resize(datasets);
  20327. };
  20328. _proto.updateSubtitleTracks = function updateSubtitleTracks(subtitles) {
  20329. var _this6 = this;
  20330. var _this$chart$data4 = this.chart.data,
  20331. labels = _this$chart$data4.labels,
  20332. datasets = _this$chart$data4.datasets;
  20333. if (!labels || !datasets) {
  20334. return;
  20335. }
  20336. var subtitleTrack = self.hls.subtitleTrack;
  20337. subtitles.forEach(function (track, i) {
  20338. labels.push(getSubtitlesName(track, i));
  20339. datasets.push(datasetWithDefaults({
  20340. url: track.url,
  20341. trackType: 'subtitleTrack',
  20342. borderColor: subtitleTrack === i ? 'rgba(32, 32, 240, 1.0)' : null,
  20343. subtitleTrack: i
  20344. }));
  20345. if (track.details) {
  20346. _this6.updateLevelOrTrack(track.details);
  20347. }
  20348. });
  20349. this.resize(datasets);
  20350. };
  20351. _proto.removeType = function removeType(trackType) {
  20352. var _this$chart$data5 = this.chart.data,
  20353. labels = _this$chart$data5.labels,
  20354. datasets = _this$chart$data5.datasets;
  20355. if (!labels || !datasets) {
  20356. return;
  20357. }
  20358. var i = datasets.length;
  20359. while (i--) {
  20360. if (datasets[i].trackType === trackType) {
  20361. datasets.splice(i, 1);
  20362. labels.splice(i, 1);
  20363. }
  20364. }
  20365. };
  20366. _proto.updateLevelOrTrack = function updateLevelOrTrack(details) {
  20367. var targetduration = details.targetduration,
  20368. totalduration = details.totalduration,
  20369. url = details.url;
  20370. var datasets = this.chart.data.datasets;
  20371. var levelDataSet = arrayFind(datasets, function (dataset) {
  20372. return stripDeliveryDirectives(url) === stripDeliveryDirectives(dataset.url || '');
  20373. });
  20374. if (!levelDataSet) {
  20375. levelDataSet = arrayFind(datasets, function (dataset) {
  20376. var _details$fragments$;
  20377. return ((_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.level) === dataset.level;
  20378. });
  20379. }
  20380. if (!levelDataSet) {
  20381. return;
  20382. }
  20383. var data = levelDataSet.data;
  20384. data.length = 0;
  20385. if (details.fragments) {
  20386. details.fragments.forEach(function (fragment) {
  20387. // TODO: keep track of initial playlist start and duration so that we can show drift and pts offset
  20388. // (Make that a feature of hls.js v1.0.0 fragments)
  20389. var chartFragment = _extends({
  20390. dataType: 'fragment'
  20391. }, fragment,
  20392. // Remove loader references for GC
  20393. {
  20394. loader: null
  20395. });
  20396. data.push(chartFragment);
  20397. });
  20398. }
  20399. if (details.partList) {
  20400. details.partList.forEach(function (part) {
  20401. var chartPart = _extends({
  20402. dataType: 'part',
  20403. start: part.fragment.start + part.fragOffset
  20404. }, part, {
  20405. fragment: _extends({}, part.fragment, {
  20406. loader: null
  20407. })
  20408. });
  20409. data.push(chartPart);
  20410. });
  20411. if (details.fragmentHint) {
  20412. var chartFragment = _extends({
  20413. dataType: 'fragmentHint'
  20414. }, details.fragmentHint,
  20415. // Remove loader references for GC
  20416. {
  20417. loader: null
  20418. });
  20419. data.push(chartFragment);
  20420. }
  20421. }
  20422. var start = getPlaylistStart(details);
  20423. this.maxZoom = this.zoom100 = Math.max(start + totalduration + targetduration * 3, this.zoom100);
  20424. this.updateOnRepaint();
  20425. }
  20426. // @ts-ignore
  20427. ;
  20428. _proto.updateFragment = function updateFragment(data) {
  20429. var datasets = this.chart.data.datasets;
  20430. var frag = data.frag;
  20431. var levelDataSet = arrayFind(datasets, function (dataset) {
  20432. return frag.baseurl === dataset.url;
  20433. });
  20434. if (!levelDataSet) {
  20435. levelDataSet = arrayFind(datasets, function (dataset) {
  20436. return frag.level === dataset.level;
  20437. });
  20438. }
  20439. if (!levelDataSet) {
  20440. return;
  20441. }
  20442. // eslint-disable-next-line no-restricted-properties
  20443. var fragData = arrayFind(levelDataSet.data, function (fragData) {
  20444. return fragData.relurl === frag.relurl && fragData.sn === frag.sn;
  20445. });
  20446. if (fragData && fragData !== frag) {
  20447. _extends(fragData, frag);
  20448. }
  20449. this.updateOnRepaint();
  20450. };
  20451. _proto.updateSourceBuffers = function updateSourceBuffers(tracks, media) {
  20452. var _this7 = this;
  20453. var _this$chart$data6 = this.chart.data,
  20454. labels = _this$chart$data6.labels,
  20455. datasets = _this$chart$data6.datasets;
  20456. if (!labels || !datasets) {
  20457. return;
  20458. }
  20459. var trackTypes = Object.keys(tracks).sort(function (type) {
  20460. return type === 'video' ? 1 : -1;
  20461. });
  20462. var mediaBufferData = [];
  20463. this.removeSourceBuffers();
  20464. this.media = media;
  20465. trackTypes.forEach(function (type) {
  20466. var track = tracks[type];
  20467. var data = [];
  20468. var sourceBuffer = track.buffer;
  20469. var backgroundColor = {
  20470. video: 'rgba(0, 0, 255, 0.2)',
  20471. audio: 'rgba(128, 128, 0, 0.2)',
  20472. audiovideo: 'rgba(128, 128, 255, 0.2)'
  20473. }[type];
  20474. labels.unshift(type + " buffer (" + track.id + ")");
  20475. datasets.unshift(datasetWithDefaults({
  20476. data: data,
  20477. categoryPercentage: 0.5,
  20478. backgroundColor: backgroundColor,
  20479. sourceBuffer: sourceBuffer
  20480. }));
  20481. sourceBuffer.addEventListener('update', function () {
  20482. try {
  20483. replaceTimeRangeTuples(sourceBuffer.buffered, data);
  20484. } catch (error) {
  20485. // eslint-disable-next-line no-console
  20486. console.warn(error);
  20487. return;
  20488. }
  20489. replaceTimeRangeTuples(media.buffered, mediaBufferData);
  20490. _this7.update();
  20491. });
  20492. });
  20493. if (trackTypes.length === 0) {
  20494. media.onprogress = function () {
  20495. replaceTimeRangeTuples(media.buffered, mediaBufferData);
  20496. _this7.update();
  20497. };
  20498. }
  20499. labels.unshift('media buffer');
  20500. datasets.unshift(datasetWithDefaults({
  20501. data: mediaBufferData,
  20502. categoryPercentage: 0.5,
  20503. backgroundColor: 'rgba(0, 255, 0, 0.2)',
  20504. media: media
  20505. }));
  20506. media.ontimeupdate = function () {
  20507. return _this7.drawCurrentTime();
  20508. };
  20509. // TextTrackList
  20510. var textTracks = media.textTracks;
  20511. this.tracksChangeHandler = this.tracksChangeHandler || function (e) {
  20512. return _this7.setTextTracks(e.currentTarget);
  20513. };
  20514. textTracks.removeEventListener('addtrack', this.tracksChangeHandler);
  20515. textTracks.removeEventListener('removetrack', this.tracksChangeHandler);
  20516. textTracks.removeEventListener('change', this.tracksChangeHandler);
  20517. textTracks.addEventListener('addtrack', this.tracksChangeHandler);
  20518. textTracks.addEventListener('removetrack', this.tracksChangeHandler);
  20519. textTracks.addEventListener('change', this.tracksChangeHandler);
  20520. this.setTextTracks(textTracks);
  20521. this.resize(datasets);
  20522. };
  20523. _proto.removeSourceBuffers = function removeSourceBuffers() {
  20524. var _this$chart$data7 = this.chart.data,
  20525. labels = _this$chart$data7.labels,
  20526. datasets = _this$chart$data7.datasets;
  20527. if (!labels || !datasets) {
  20528. return;
  20529. }
  20530. var i = datasets.length;
  20531. while (i--) {
  20532. if ((labels[0] || '').toString().indexOf('buffer') > -1) {
  20533. datasets.splice(i, 1);
  20534. labels.splice(i, 1);
  20535. }
  20536. }
  20537. };
  20538. _proto.setTextTracks = function setTextTracks(textTracks) {
  20539. var _this8 = this;
  20540. var _this$chart$data8 = this.chart.data,
  20541. labels = _this$chart$data8.labels,
  20542. datasets = _this$chart$data8.datasets;
  20543. if (!labels || !datasets) {
  20544. return;
  20545. }
  20546. this.removeType('textTrack');
  20547. [].forEach.call(textTracks, function (textTrack, i) {
  20548. // Uncomment to disable rending of subtitle/caption cues in the timeline
  20549. // if (textTrack.kind === 'subtitles' || textTrack.kind === 'captions') {
  20550. // return;
  20551. // }
  20552. var data = [];
  20553. labels.push((textTrack.name || textTrack.label) + " " + textTrack.kind + " (" + textTrack.mode + ")");
  20554. datasets.push(datasetWithDefaults({
  20555. data: data,
  20556. categoryPercentage: 0.5,
  20557. url: '',
  20558. trackType: 'textTrack',
  20559. borderColor: textTrack.mode !== 'hidden' === i ? 'rgba(32, 32, 240, 1.0)' : null,
  20560. textTrack: i
  20561. }));
  20562. _this8.cuesChangeHandler = _this8.cuesChangeHandler || function (e) {
  20563. return _this8.updateTextTrackCues(e.currentTarget);
  20564. };
  20565. textTrack._data = data;
  20566. textTrack.removeEventListener('cuechange', _this8.cuesChangeHandler);
  20567. textTrack.addEventListener('cuechange', _this8.cuesChangeHandler);
  20568. _this8.updateTextTrackCues(textTrack);
  20569. });
  20570. this.resize(datasets);
  20571. };
  20572. _proto.updateTextTrackCues = function updateTextTrackCues(textTrack) {
  20573. var data = textTrack._data;
  20574. if (!data) {
  20575. return;
  20576. }
  20577. var activeCues = textTrack.activeCues,
  20578. cues = textTrack.cues;
  20579. data.length = 0;
  20580. if (!cues) {
  20581. return;
  20582. }
  20583. var length = cues.length;
  20584. var activeLength = 0;
  20585. var activeMin = Infinity;
  20586. var activeMax = 0;
  20587. if (activeCues) {
  20588. activeLength = activeCues.length;
  20589. for (var i = 0; i < activeLength; i++) {
  20590. var cue = activeCues[i];
  20591. if (!cue && activeCues.item) {
  20592. cue = activeCues.item(i);
  20593. }
  20594. if (cue) {
  20595. activeMin = Math.min(activeMin, cue.startTime);
  20596. activeMax = cue.endTime ? Math.max(activeMax, cue.endTime) : activeMax;
  20597. } else {
  20598. activeLength--;
  20599. }
  20600. }
  20601. }
  20602. var _loop = function _loop() {
  20603. var cue = cues[_i];
  20604. if (!cue && cues.item) {
  20605. cue = cues.item(_i);
  20606. }
  20607. if (!cue) {
  20608. return 1; // continue
  20609. }
  20610. var start = cue.startTime;
  20611. var end = cue.endTime;
  20612. var content = getCueLabel(cue);
  20613. var active = false;
  20614. if (activeLength && end >= activeMin && start <= activeMax) {
  20615. active = [].some.call(activeCues, function (activeCue) {
  20616. return cuesMatch(activeCue, cue);
  20617. });
  20618. }
  20619. data.push({
  20620. start: start,
  20621. end: end,
  20622. content: content,
  20623. active: active,
  20624. dataType: 'cue'
  20625. });
  20626. };
  20627. for (var _i = 0; _i < length; _i++) {
  20628. if (_loop()) continue;
  20629. }
  20630. this.updateOnRepaint();
  20631. };
  20632. _proto.drawCurrentTime = function drawCurrentTime() {
  20633. var _self$hls3;
  20634. var chart = this.chart;
  20635. if ((_self$hls3 = self.hls) != null && _self$hls3.media && chart.data.datasets.length) {
  20636. var currentTime = self.hls.media.currentTime;
  20637. var scale = this.chartScales[X_AXIS_SECONDS];
  20638. var ctx = chart.ctx;
  20639. if (this.hidden || !ctx || !ctx.canvas.width) {
  20640. return;
  20641. }
  20642. var chartArea = chart.chartArea;
  20643. var x = scale.getPixelForValue(currentTime);
  20644. ctx.restore();
  20645. ctx.save();
  20646. this.drawLineX(ctx, x, chartArea);
  20647. if (x > chartArea.left && x < chartArea.right) {
  20648. ctx.fillStyle = this.getCurrentTimeColor(self.hls.media);
  20649. var y = chartArea.top + chart.data.datasets[0].barThickness + 1;
  20650. ctx.fillText(hhmmss(currentTime, 5), x + 2, y, 100);
  20651. }
  20652. ctx.restore();
  20653. }
  20654. };
  20655. _proto.getCurrentTimeColor = function getCurrentTimeColor(video) {
  20656. if (!video.readyState || video.ended) {
  20657. return 'rgba(0, 0, 0, 0.9)';
  20658. }
  20659. if (video.seeking || video.readyState < 3) {
  20660. return 'rgba(255, 128, 0, 0.9)';
  20661. }
  20662. if (video.paused) {
  20663. return 'rgba(128, 0, 255, 0.9)';
  20664. }
  20665. return 'rgba(0, 0, 255, 0.9)';
  20666. };
  20667. _proto.drawLineX = function drawLineX(ctx, x, chartArea) {
  20668. if (!this.imageDataBuffer) {
  20669. var devicePixelRatio = self.devicePixelRatio || 1;
  20670. this.imageDataBuffer = ctx.getImageData(0, 0, chartArea.right * devicePixelRatio, chartArea.bottom * devicePixelRatio);
  20671. } else {
  20672. ctx.fillStyle = '#ffffff';
  20673. ctx.fillRect(0, 0, chartArea.right, chartArea.bottom);
  20674. ctx.putImageData(this.imageDataBuffer, 0, 0);
  20675. }
  20676. if (x > chartArea.left && x < chartArea.right) {
  20677. ctx.lineWidth = 1;
  20678. ctx.strokeStyle = this.getCurrentTimeColor(self.hls.media); // alpha '0.5'
  20679. ctx.beginPath();
  20680. ctx.moveTo(x, chartArea.top);
  20681. ctx.lineTo(x, chartArea.bottom);
  20682. ctx.stroke();
  20683. }
  20684. };
  20685. return _createClass(TimelineChart, [{
  20686. key: "chartScales",
  20687. get: function get() {
  20688. return this.chart.scales;
  20689. }
  20690. }, {
  20691. key: "minZoom",
  20692. get: function get() {
  20693. var scale = this.chartScales[X_AXIS_SECONDS];
  20694. if (scale) {
  20695. return scale.options.ticks.min;
  20696. }
  20697. return 1;
  20698. }
  20699. // @ts-ignore
  20700. }, {
  20701. key: "maxZoom",
  20702. get: function get() {
  20703. var scale = this.chartScales[X_AXIS_SECONDS];
  20704. if (scale) {
  20705. return scale.options.ticks.max;
  20706. }
  20707. return this.zoom100;
  20708. }
  20709. // @ts-ignore
  20710. ,
  20711. set: function set(x) {
  20712. var currentZoom = this.maxZoom;
  20713. var newZoom = Math.max(x, currentZoom);
  20714. if (currentZoom === 60 && newZoom !== currentZoom) {
  20715. var scale = this.chartScales[X_AXIS_SECONDS];
  20716. scale.options.ticks.max = newZoom;
  20717. }
  20718. }
  20719. }]);
  20720. }();
  20721. function stripDeliveryDirectives(url) {
  20722. if (url === '') {
  20723. return url;
  20724. }
  20725. try {
  20726. var webUrl = new self.URL(url);
  20727. webUrl.searchParams.delete('_HLS_msn');
  20728. webUrl.searchParams.delete('_HLS_part');
  20729. webUrl.searchParams.delete('_HLS_skip');
  20730. webUrl.searchParams.sort();
  20731. return webUrl.href;
  20732. } catch (e) {
  20733. return url.replace(/[?&]_HLS_(?:msn|part|skip)=[^?&]+/g, '');
  20734. }
  20735. }
  20736. function datasetWithDefaults(options) {
  20737. return _extends({
  20738. data: [],
  20739. xAxisID: X_AXIS_SECONDS,
  20740. barThickness: 35,
  20741. categoryPercentage: 1
  20742. }, options);
  20743. }
  20744. function getPlaylistStart(details) {
  20745. var _details$fragments;
  20746. return (_details$fragments = details.fragments) != null && _details$fragments.length ? details.fragments[0].start : 0;
  20747. }
  20748. function getLevelName(level, index) {
  20749. var _level$attrs;
  20750. var label = '(main playlist)';
  20751. if ((_level$attrs = level.attrs) != null && _level$attrs.BANDWIDTH) {
  20752. label = getMainLevelAttribute(level) + "@" + level.attrs.BANDWIDTH;
  20753. if (level.name) {
  20754. label = label + " (" + level.name + ")";
  20755. }
  20756. } else if (level.name) {
  20757. label = level.name;
  20758. }
  20759. return label + " L-" + index;
  20760. }
  20761. function getMainLevelAttribute(level) {
  20762. return level.attrs.RESOLUTION || level.attrs.CODECS || level.attrs.AUDIO;
  20763. }
  20764. function getAudioTrackName(track, index) {
  20765. var label = track.lang ? track.name + "/" + track.lang : track.name;
  20766. return label + " (" + (track.groupId || track.attrs['GROUP-ID']) + ") A-" + index;
  20767. }
  20768. function getSubtitlesName(track, index) {
  20769. var label = track.lang ? track.name + "/" + track.lang : track.name;
  20770. return label + " (" + (track.groupId || track.attrs['GROUP-ID']) + ") S-" + index;
  20771. }
  20772. function replaceTimeRangeTuples(timeRanges, data) {
  20773. data.length = 0;
  20774. var length = timeRanges.length;
  20775. for (var i = 0; i < length; i++) {
  20776. data.push([timeRanges.start(i), timeRanges.end(i)]);
  20777. }
  20778. }
  20779. function cuesMatch(cue1, cue2) {
  20780. 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);
  20781. }
  20782. function getCueLabel(cue) {
  20783. if (cue.text) {
  20784. return cue.text;
  20785. }
  20786. var result = parseDataCue(cue);
  20787. return JSON.stringify(result);
  20788. }
  20789. function parseDataCue(cue) {
  20790. var data = {};
  20791. var value = cue.value;
  20792. if (value) {
  20793. if (value.info) {
  20794. var collection = data[value.key];
  20795. if (collection !== Object(collection)) {
  20796. collection = {};
  20797. data[value.key] = collection;
  20798. }
  20799. collection[value.info] = value.data;
  20800. } else {
  20801. data[value.key] = value.data;
  20802. }
  20803. }
  20804. return data;
  20805. }
  20806. function getChartOptions() {
  20807. return {
  20808. animation: {
  20809. duration: 0
  20810. },
  20811. elements: {
  20812. rectangle: {
  20813. borderWidth: 1,
  20814. borderColor: 'rgba(20, 20, 20, 1)'
  20815. }
  20816. },
  20817. events: ['click', 'touchstart'],
  20818. hover: {
  20819. mode: null,
  20820. animationDuration: 0
  20821. },
  20822. legend: {
  20823. display: false
  20824. },
  20825. maintainAspectRatio: false,
  20826. responsiveAnimationDuration: 0,
  20827. scales: {
  20828. // TODO: additional xAxes for PTS and PDT
  20829. xAxes: [{
  20830. id: X_AXIS_SECONDS,
  20831. ticks: {
  20832. beginAtZero: true,
  20833. sampleSize: 0,
  20834. maxRotation: 0,
  20835. callback: function callback(tickValue, i, ticks) {
  20836. if (i === 0 || i === ticks.length - 1) {
  20837. return tickValue ? '' : '0';
  20838. } else {
  20839. return hhmmss(tickValue, 2);
  20840. }
  20841. }
  20842. }
  20843. }],
  20844. yAxes: [{
  20845. gridLines: {
  20846. display: false
  20847. }
  20848. }]
  20849. },
  20850. tooltips: {
  20851. enabled: false
  20852. }
  20853. };
  20854. }
  20855. function arrayFind(array, predicate) {
  20856. var len = array.length >>> 0;
  20857. if (typeof predicate !== 'function') {
  20858. throw TypeError('predicate must be a function');
  20859. }
  20860. var thisArg = arguments[2];
  20861. var k = 0;
  20862. while (k < len) {
  20863. var kValue = array[k];
  20864. if (predicate.call(thisArg, kValue, k, array)) {
  20865. return kValue;
  20866. }
  20867. k++;
  20868. }
  20869. // eslint-disable-next-line no-undefined
  20870. return undefined;
  20871. }
  20872. /* global $, Hls, null */
  20873. var STORAGE_KEYS = {
  20874. Editor_Persistence: 'hlsjs:config-editor-persist',
  20875. Hls_Config: 'hlsjs:config',
  20876. volume: 'hlsjs:volume',
  20877. demo_tabs: 'hlsjs:demo-tabs'
  20878. };
  20879. var testStreams = requireTestStreams();
  20880. var defaultTestStreamUrl = testStreams[Object.keys(testStreams)[0]].url;
  20881. var sourceURL = decodeURIComponent(getURLParam('src', defaultTestStreamUrl));
  20882. var demoConfig = getURLParam('demoConfig', null);
  20883. if (demoConfig) {
  20884. demoConfig = JSON.parse(atob(demoConfig));
  20885. } else {
  20886. demoConfig = {};
  20887. }
  20888. var hlsjsDefaults = {
  20889. debug: true,
  20890. enableWorker: true,
  20891. lowLatencyMode: true,
  20892. backBufferLength: 60 * 1.5
  20893. };
  20894. var enableStreaming = getDemoConfigPropOrDefault('enableStreaming', true);
  20895. var autoRecoverError = getDemoConfigPropOrDefault('autoRecoverError', true);
  20896. var levelCapping = getDemoConfigPropOrDefault('levelCapping', -1);
  20897. var limitMetrics = getDemoConfigPropOrDefault('limitMetrics', -1);
  20898. var dumpfMP4 = getDemoConfigPropOrDefault('dumpfMP4', false);
  20899. var stopOnStall = getDemoConfigPropOrDefault('stopOnStall', false);
  20900. var bufferingIdx = -1;
  20901. var selectedTestStream = null;
  20902. var video = document.querySelector('#video');
  20903. var startTime = Date.now();
  20904. var lastSeekingIdx;
  20905. var lastStartPosition;
  20906. var lastDuration;
  20907. var lastAudioTrackSwitchingIdx;
  20908. var hls;
  20909. var url;
  20910. var events;
  20911. var stats;
  20912. var tracks;
  20913. var fmp4Data;
  20914. var configPersistenceEnabled = false;
  20915. var configEditor = null;
  20916. var chart;
  20917. var resizeAsyncCallbackId = -1;
  20918. var requestAnimationFrame = self.requestAnimationFrame || self.setTimeout;
  20919. var cancelAnimationFrame = self.cancelAnimationFrame || self.clearTimeout;
  20920. var resizeHandlers = [];
  20921. var resize = function resize() {
  20922. cancelAnimationFrame(resizeAsyncCallbackId);
  20923. resizeAsyncCallbackId = requestAnimationFrame(function () {
  20924. resizeHandlers.forEach(function (handler) {
  20925. handler();
  20926. });
  20927. });
  20928. };
  20929. self.onresize = resize;
  20930. if (self.screen && self.screen.orientation) {
  20931. self.screen.orientation.onchange = resize;
  20932. }
  20933. var playerResize = function playerResize() {
  20934. var bounds = video.getBoundingClientRect();
  20935. $('#currentSize').html(Math.round(bounds.width * 10) / 10 + " x " + Math.round(bounds.height * 10) / 10);
  20936. if (video.videoWidth && video.videoHeight) {
  20937. $('#currentResolution').html(video.videoWidth + " x " + video.videoHeight);
  20938. }
  20939. };
  20940. resizeHandlers.push(playerResize);
  20941. $(document).ready(function () {
  20942. setupConfigEditor();
  20943. chart = setupTimelineChart();
  20944. Object.keys(testStreams).forEach(function (key, index) {
  20945. var stream = testStreams[key];
  20946. var option = new Option(stream.description, key);
  20947. $('#streamSelect').append(option);
  20948. if (stream.url === sourceURL) {
  20949. document.querySelector('#streamSelect').selectedIndex = index + 1;
  20950. }
  20951. });
  20952. var videoWidth = video.style.width;
  20953. if (videoWidth) {
  20954. $('#videoSize option').each(function (i, option) {
  20955. if (option.value === videoWidth) {
  20956. document.querySelector('#videoSize').selectedIndex = i;
  20957. $('#bufferedCanvas').width(videoWidth);
  20958. resize();
  20959. return false;
  20960. }
  20961. });
  20962. }
  20963. $('#streamSelect').change(function () {
  20964. var key = $('#streamSelect').val() || Object.keys(testStreams)[0];
  20965. selectedTestStream = testStreams[key];
  20966. var streamUrl = selectedTestStream.url;
  20967. $('#streamURL').val(streamUrl);
  20968. loadSelectedStream();
  20969. });
  20970. $('#streamURL').change(function () {
  20971. selectedTestStream = null;
  20972. loadSelectedStream();
  20973. });
  20974. $('#videoSize').change(function () {
  20975. $('#video').width($('#videoSize').val());
  20976. $('#bufferedCanvas').width($('#videoSize').val());
  20977. checkBuffer();
  20978. resize();
  20979. });
  20980. $('#enableStreaming').click(function () {
  20981. enableStreaming = this.checked;
  20982. loadSelectedStream();
  20983. });
  20984. $('#autoRecoverError').click(function () {
  20985. autoRecoverError = this.checked;
  20986. onDemoConfigChanged();
  20987. });
  20988. $('#stopOnStall').click(function () {
  20989. stopOnStall = this.checked;
  20990. onDemoConfigChanged();
  20991. });
  20992. $('#dumpfMP4').click(function () {
  20993. dumpfMP4 = this.checked;
  20994. $('.btn-dump').toggle(dumpfMP4);
  20995. onDemoConfigChanged();
  20996. });
  20997. $('#limitMetrics').change(function () {
  20998. limitMetrics = this.value;
  20999. onDemoConfigChanged();
  21000. });
  21001. $('#levelCapping').change(function () {
  21002. levelCapping = this.value;
  21003. onDemoConfigChanged();
  21004. });
  21005. $('#limitMetrics').val(limitMetrics);
  21006. $('#enableStreaming').prop('checked', enableStreaming);
  21007. $('#autoRecoverError').prop('checked', autoRecoverError);
  21008. $('#stopOnStall').prop('checked', stopOnStall);
  21009. $('#dumpfMP4').prop('checked', dumpfMP4);
  21010. $('#levelCapping').val(levelCapping);
  21011. // If cloudflare pages build link to branch
  21012. // If not a stable tag link to npm
  21013. // otherwise link to github tag
  21014. function getVersionLink(version) {
  21015. var noneStable = version.includes('-');
  21016. if (noneStable) {
  21017. return "https://www.npmjs.com/package/hls.js/v/" + encodeURIComponent(version);
  21018. } else {
  21019. return "https://github.com/video-dev/hls.js/releases/tag/v" + encodeURIComponent(version);
  21020. }
  21021. }
  21022. var version = Hls.version;
  21023. if (version) {
  21024. var $a = $('<a />').attr('target', '_blank').attr('rel', 'noopener noreferrer').attr('href', getVersionLink(version)).text('v' + version);
  21025. $('.title').append(' ').append($a);
  21026. }
  21027. $('#streamURL').val(sourceURL);
  21028. var volumeSettings = JSON.parse(localStorage.getItem(STORAGE_KEYS.volume)) || {
  21029. volume: 0.05,
  21030. muted: false
  21031. };
  21032. video.volume = volumeSettings.volume;
  21033. video.muted = volumeSettings.muted;
  21034. $('.btn-dump').toggle(dumpfMP4);
  21035. $('#toggleButtons').show();
  21036. $('#metricsButtonWindow').toggle(self.windowSliding);
  21037. $('#metricsButtonFixed').toggle(!self.windowSliding);
  21038. loadSelectedStream();
  21039. var tabIndexesCSV = localStorage.getItem(STORAGE_KEYS.demo_tabs);
  21040. if (tabIndexesCSV === null) {
  21041. tabIndexesCSV = '0,1,2';
  21042. }
  21043. if (tabIndexesCSV) {
  21044. tabIndexesCSV.split(',').forEach(function (indexString) {
  21045. toggleTab($('.demo-tab-btn')[parseInt(indexString) || 0], true);
  21046. });
  21047. }
  21048. $(self).on('popstate', function () {
  21049. self.location.reload();
  21050. });
  21051. });
  21052. function setupGlobals() {
  21053. self.events = events = {
  21054. url: url,
  21055. t0: self.performance.now(),
  21056. load: [],
  21057. buffer: [],
  21058. video: [],
  21059. level: [],
  21060. bitrate: []
  21061. };
  21062. lastAudioTrackSwitchingIdx = undefined;
  21063. lastSeekingIdx = undefined;
  21064. bufferingIdx = -1;
  21065. // actual values, only on window
  21066. self.recoverDecodingErrorDate = null;
  21067. self.recoverSwapAudioCodecDate = null;
  21068. self.fmp4Data = fmp4Data = {
  21069. audio: [],
  21070. video: []
  21071. };
  21072. self.onClickBufferedRange = onClickBufferedRange;
  21073. self.updateLevelInfo = updateLevelInfo;
  21074. self.onDemoConfigChanged = onDemoConfigChanged;
  21075. self.createfMP4 = createfMP4;
  21076. self.goToMetricsPermaLink = goToMetricsPermaLink;
  21077. self.toggleTab = toggleTab;
  21078. self.toggleTabClick = toggleTabClick;
  21079. self.applyConfigEditorValue = applyConfigEditorValue;
  21080. }
  21081. function trimArray(target, limit) {
  21082. if (limit < 0) {
  21083. return;
  21084. }
  21085. while (target.length > limit) {
  21086. target.shift();
  21087. }
  21088. }
  21089. function trimEventHistory() {
  21090. var x = limitMetrics;
  21091. if (x < 0) {
  21092. return;
  21093. }
  21094. trimArray(events.load, x);
  21095. trimArray(events.buffer, x);
  21096. trimArray(events.video, x);
  21097. trimArray(events.level, x);
  21098. trimArray(events.bitrate, x);
  21099. }
  21100. function loadSelectedStream() {
  21101. $('#statusOut,#errorOut').empty();
  21102. if (!Hls.isSupported()) {
  21103. handleUnsupported();
  21104. return;
  21105. }
  21106. url = $('#streamURL').val();
  21107. // Check if the URL is valid to avoid XSS issue.
  21108. if (url) {
  21109. try {
  21110. new URL(url);
  21111. } catch (error) {
  21112. $('#streamURL').val('');
  21113. alert('Invalid URL');
  21114. return false;
  21115. }
  21116. }
  21117. setupGlobals();
  21118. hideCanvas();
  21119. if (hls) {
  21120. hls.destroy();
  21121. clearInterval(hls.bufferTimer);
  21122. hls = null;
  21123. }
  21124. if (!enableStreaming) {
  21125. logStatus('Streaming disabled');
  21126. return;
  21127. }
  21128. logStatus('Loading ' + url);
  21129. // Extending both a demo-specific config and the user config which can override all
  21130. var hlsConfig = $.extend({}, hlsjsDefaults, getEditorValue({
  21131. parse: true
  21132. }));
  21133. if (selectedTestStream && selectedTestStream.config) {
  21134. console.info('[loadSelectedStream] extending hls config with stream-specific config: ', selectedTestStream.config);
  21135. $.extend(hlsConfig, selectedTestStream.config);
  21136. updateConfigEditorValue(hlsConfig);
  21137. }
  21138. onDemoConfigChanged(true);
  21139. console.log('Using Hls.js config:', hlsConfig);
  21140. self.hls = hls = new Hls(hlsConfig);
  21141. logStatus('Loading manifest and attaching video element...');
  21142. var expiredTracks = [].filter.call(video.textTracks, function (track) {
  21143. return track.kind !== 'metadata';
  21144. });
  21145. if (expiredTracks.length) {
  21146. var kinds = expiredTracks.map(function (track) {
  21147. return track.kind;
  21148. }).filter(function (kind, index, self) {
  21149. return self.indexOf(kind) === index;
  21150. });
  21151. logStatus("Replacing video element to remove " + kinds.join(' and ') + " text tracks");
  21152. var videoWithExpiredTextTracks = video;
  21153. video = videoWithExpiredTextTracks.cloneNode(false);
  21154. video.removeAttribute('src');
  21155. video.volume = videoWithExpiredTextTracks.volume;
  21156. video.muted = videoWithExpiredTextTracks.muted;
  21157. videoWithExpiredTextTracks.parentNode.insertBefore(video, videoWithExpiredTextTracks);
  21158. videoWithExpiredTextTracks.parentNode.removeChild(videoWithExpiredTextTracks);
  21159. }
  21160. addChartEventListeners(hls);
  21161. addVideoEventListeners(video);
  21162. hls.loadSource(url);
  21163. hls.autoLevelCapping = levelCapping;
  21164. hls.attachMedia(video);
  21165. hls.on(Hls.Events.MEDIA_ATTACHED, function () {
  21166. logStatus('Media element attached');
  21167. bufferingIdx = -1;
  21168. events.video.push({
  21169. time: self.performance.now() - events.t0,
  21170. type: 'Media attached'
  21171. });
  21172. trimEventHistory();
  21173. });
  21174. hls.on(Hls.Events.MEDIA_DETACHED, function () {
  21175. logStatus('Media element detached');
  21176. clearInterval(hls.bufferTimer);
  21177. bufferingIdx = -1;
  21178. tracks = [];
  21179. events.video.push({
  21180. time: self.performance.now() - events.t0,
  21181. type: 'Media detached'
  21182. });
  21183. trimEventHistory();
  21184. });
  21185. hls.on(Hls.Events.DESTROYING, function () {
  21186. clearInterval(hls.bufferTimer);
  21187. });
  21188. hls.on(Hls.Events.BUFFER_RESET, function () {
  21189. clearInterval(hls.bufferTimer);
  21190. });
  21191. hls.on(Hls.Events.FRAG_PARSING_INIT_SEGMENT, function (eventName, data) {
  21192. showCanvas();
  21193. events.video.push({
  21194. time: self.performance.now() - events.t0,
  21195. type: data.id + ' init segment'
  21196. });
  21197. trimEventHistory();
  21198. });
  21199. hls.on(Hls.Events.FRAG_PARSING_METADATA, function (eventName, data) {
  21200. // console.log("Id3 samples ", data.samples);
  21201. });
  21202. hls.on(Hls.Events.LEVEL_SWITCHING, function (eventName, data) {
  21203. events.level.push({
  21204. time: self.performance.now() - events.t0,
  21205. id: data.level,
  21206. bitrate: Math.round(hls.levels[data.level].bitrate / 1000)
  21207. });
  21208. trimEventHistory();
  21209. updateLevelInfo();
  21210. });
  21211. hls.on(Hls.Events.MANIFEST_PARSED, function (eventName, data) {
  21212. events.load.push({
  21213. type: 'manifest',
  21214. name: '',
  21215. start: 0,
  21216. end: data.levels.length,
  21217. time: data.stats.loading.start - events.t0,
  21218. latency: data.stats.loading.first - data.stats.loading.start,
  21219. load: data.stats.loading.end - data.stats.loading.first,
  21220. duration: data.stats.loading.end - data.stats.loading.first
  21221. });
  21222. trimEventHistory();
  21223. self.refreshCanvas();
  21224. });
  21225. hls.on(Hls.Events.MANIFEST_PARSED, function (eventName, data) {
  21226. logStatus(hls.levels.length + " quality levels found");
  21227. logStatus('Manifest successfully loaded');
  21228. stats = {
  21229. levelNb: data.levels.length,
  21230. levelParsed: 0
  21231. };
  21232. trimEventHistory();
  21233. updateLevelInfo();
  21234. });
  21235. hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, function (eventName, data) {
  21236. logStatus('No of audio tracks found: ' + data.audioTracks.length);
  21237. updateAudioTrackInfo();
  21238. });
  21239. hls.on(Hls.Events.AUDIO_TRACK_SWITCHING, function (eventName, data) {
  21240. logStatus('Audio track switching...');
  21241. updateAudioTrackInfo();
  21242. events.video.push({
  21243. time: self.performance.now() - events.t0,
  21244. type: 'audio switching',
  21245. name: '@' + data.id
  21246. });
  21247. trimEventHistory();
  21248. lastAudioTrackSwitchingIdx = events.video.length - 1;
  21249. });
  21250. hls.on(Hls.Events.AUDIO_TRACK_SWITCHED, function (eventName, data) {
  21251. logStatus('Audio track switched');
  21252. updateAudioTrackInfo();
  21253. var event = {
  21254. time: self.performance.now() - events.t0,
  21255. type: 'audio switched',
  21256. name: '@' + data.id
  21257. };
  21258. if (lastAudioTrackSwitchingIdx !== undefined) {
  21259. events.video[lastAudioTrackSwitchingIdx].duration = event.time - events.video[lastAudioTrackSwitchingIdx].time;
  21260. lastAudioTrackSwitchingIdx = undefined;
  21261. }
  21262. events.video.push(event);
  21263. trimEventHistory();
  21264. });
  21265. hls.on(Hls.Events.LEVEL_LOADED, function (eventName, data) {
  21266. events.isLive = data.details.live;
  21267. var event = {
  21268. type: 'level',
  21269. id: data.level,
  21270. start: data.details.startSN,
  21271. end: data.details.endSN,
  21272. time: data.stats.loading.start - events.t0,
  21273. latency: data.stats.loading.first - data.stats.loading.start,
  21274. load: data.stats.loading.end - data.stats.loading.first,
  21275. parsing: data.stats.parsing.end - data.stats.loading.end,
  21276. duration: data.stats.loading.end - data.stats.loading.first
  21277. };
  21278. var parsingDuration = data.stats.parsing.end - data.stats.loading.end;
  21279. if (stats.levelParsed) {
  21280. this.sumLevelParsingMs += parsingDuration;
  21281. } else {
  21282. this.sumLevelParsingMs = parsingDuration;
  21283. }
  21284. stats.levelParsed++;
  21285. stats.levelParsingUs = Math.round(1000 * this.sumLevelParsingMs / stats.levelParsed);
  21286. // console.log('parsing level duration :' + stats.levelParsingUs + 'us,count:' + stats.levelParsed);
  21287. events.load.push(event);
  21288. trimEventHistory();
  21289. self.refreshCanvas();
  21290. });
  21291. hls.on(Hls.Events.AUDIO_TRACK_LOADED, function (eventName, data) {
  21292. events.isLive = data.details.live;
  21293. var event = {
  21294. type: 'audio track',
  21295. id: data.id,
  21296. start: data.details.startSN,
  21297. end: data.details.endSN,
  21298. time: data.stats.loading.start - events.t0,
  21299. latency: data.stats.loading.first - data.stats.loading.start,
  21300. load: data.stats.loading.end - data.stats.loading.first,
  21301. parsing: data.stats.parsing.end - data.stats.loading.end,
  21302. duration: data.stats.loading.end - data.stats.loading.first
  21303. };
  21304. events.load.push(event);
  21305. trimEventHistory();
  21306. self.refreshCanvas();
  21307. });
  21308. hls.on(Hls.Events.FRAG_BUFFERED, function (eventName, data) {
  21309. var stats = data.part && data.part.stats && data.part.stats.loaded ? data.part.stats : data.frag.stats;
  21310. if (data.stats.aborted) {
  21311. console.assert('Aborted request being buffered.', data);
  21312. return;
  21313. }
  21314. var event = {
  21315. type: data.frag.type + (data.part ? ' part' : ' fragment'),
  21316. id: data.frag.level,
  21317. id2: data.frag.sn,
  21318. id3: data.part ? data.part.index : undefined,
  21319. time: data.stats.loading.start - events.t0,
  21320. latency: data.stats.loading.first - data.stats.loading.start,
  21321. load: data.stats.loading.end - data.stats.loading.first,
  21322. parsing: data.stats.parsing.end - data.stats.loading.end,
  21323. buffer: data.stats.buffering.end - data.stats.parsing.end,
  21324. duration: data.stats.buffering.end - data.stats.loading.first,
  21325. bw: Math.round(8 * data.stats.total / (data.stats.buffering.end - data.stats.loading.start)),
  21326. // bandwidth of this fragment
  21327. ewma: Math.round(hls.bandwidthEstimate / 1000),
  21328. // estimated bandwidth
  21329. size: data.stats.total
  21330. };
  21331. events.load.push(event);
  21332. events.bitrate.push({
  21333. time: self.performance.now() - events.t0,
  21334. bitrate: event.bw,
  21335. ewma: event.ewma,
  21336. duration: data.frag.duration,
  21337. level: event.id
  21338. });
  21339. if (events.buffer.length === 0) {
  21340. events.buffer.push({
  21341. time: 0,
  21342. buffer: 0,
  21343. pos: 0
  21344. });
  21345. }
  21346. clearInterval(hls.bufferTimer);
  21347. hls.bufferTimer = self.setInterval(checkBuffer, 100);
  21348. trimEventHistory();
  21349. self.refreshCanvas();
  21350. updateLevelInfo();
  21351. var latency = data.stats.loading.first - data.stats.loading.start;
  21352. var parsing = data.stats.parsing.end - data.stats.loading.end;
  21353. var process = data.stats.buffering.end - data.stats.loading.start;
  21354. var bitrate = Math.round(8 * data.stats.total / (data.stats.buffering.end - data.stats.loading.first));
  21355. if (stats.fragBuffered) {
  21356. stats.fragMinLatency = Math.min(stats.fragMinLatency, latency);
  21357. stats.fragMaxLatency = Math.max(stats.fragMaxLatency, latency);
  21358. stats.fragMinProcess = Math.min(stats.fragMinProcess, process);
  21359. stats.fragMaxProcess = Math.max(stats.fragMaxProcess, process);
  21360. stats.fragMinKbps = Math.min(stats.fragMinKbps, bitrate);
  21361. stats.fragMaxKbps = Math.max(stats.fragMaxKbps, bitrate);
  21362. stats.autoLevelCappingMin = Math.min(stats.autoLevelCappingMin, hls.autoLevelCapping);
  21363. stats.autoLevelCappingMax = Math.max(stats.autoLevelCappingMax, hls.autoLevelCapping);
  21364. stats.fragBuffered++;
  21365. } else {
  21366. stats.fragMinLatency = stats.fragMaxLatency = latency;
  21367. stats.fragMinProcess = stats.fragMaxProcess = process;
  21368. stats.fragMinKbps = stats.fragMaxKbps = bitrate;
  21369. stats.fragBuffered = 1;
  21370. stats.fragBufferedBytes = 0;
  21371. stats.autoLevelCappingMin = stats.autoLevelCappingMax = hls.autoLevelCapping;
  21372. this.sumLatency = 0;
  21373. this.sumKbps = 0;
  21374. this.sumProcess = 0;
  21375. this.sumParsing = 0;
  21376. }
  21377. stats.fraglastLatency = latency;
  21378. this.sumLatency += latency;
  21379. stats.fragAvgLatency = Math.round(this.sumLatency / stats.fragBuffered);
  21380. stats.fragLastProcess = process;
  21381. this.sumProcess += process;
  21382. this.sumParsing += parsing;
  21383. stats.fragAvgProcess = Math.round(this.sumProcess / stats.fragBuffered);
  21384. stats.fragLastKbps = bitrate;
  21385. this.sumKbps += bitrate;
  21386. stats.fragAvgKbps = Math.round(this.sumKbps / stats.fragBuffered);
  21387. stats.fragBufferedBytes += data.stats.total;
  21388. stats.fragparsingKbps = Math.round(8 * stats.fragBufferedBytes / this.sumParsing);
  21389. stats.fragparsingMs = Math.round(this.sumParsing);
  21390. stats.autoLevelCappingLast = hls.autoLevelCapping;
  21391. });
  21392. hls.on(Hls.Events.LEVEL_SWITCHED, function (eventName, data) {
  21393. var event = {
  21394. time: self.performance.now() - events.t0,
  21395. type: 'level switched',
  21396. name: data.level
  21397. };
  21398. events.video.push(event);
  21399. trimEventHistory();
  21400. self.refreshCanvas();
  21401. updateLevelInfo();
  21402. });
  21403. hls.on(Hls.Events.FRAG_CHANGED, function (eventName, data) {
  21404. var event = {
  21405. time: self.performance.now() - events.t0,
  21406. type: 'frag changed',
  21407. name: data.frag.sn + ' @ ' + data.frag.level
  21408. };
  21409. events.video.push(event);
  21410. trimEventHistory();
  21411. self.refreshCanvas();
  21412. updateLevelInfo();
  21413. stats.tagList = data.frag.tagList;
  21414. var level = data.frag.level;
  21415. var autoLevel = hls.autoLevelEnabled;
  21416. if (stats.levelStart === undefined) {
  21417. stats.levelStart = level;
  21418. }
  21419. stats.fragProgramDateTime = data.frag.programDateTime;
  21420. stats.fragStart = data.frag.start;
  21421. if (autoLevel) {
  21422. if (stats.fragChangedAuto) {
  21423. stats.autoLevelMin = Math.min(stats.autoLevelMin, level);
  21424. stats.autoLevelMax = Math.max(stats.autoLevelMax, level);
  21425. stats.fragChangedAuto++;
  21426. if (this.levelLastAuto && level !== stats.autoLevelLast) {
  21427. stats.autoLevelSwitch++;
  21428. }
  21429. } else {
  21430. stats.autoLevelMin = stats.autoLevelMax = level;
  21431. stats.autoLevelSwitch = 0;
  21432. stats.fragChangedAuto = 1;
  21433. this.sumAutoLevel = 0;
  21434. }
  21435. this.sumAutoLevel += level;
  21436. stats.autoLevelAvg = Math.round(1000 * this.sumAutoLevel / stats.fragChangedAuto) / 1000;
  21437. stats.autoLevelLast = level;
  21438. } else {
  21439. if (stats.fragChangedManual) {
  21440. stats.manualLevelMin = Math.min(stats.manualLevelMin, level);
  21441. stats.manualLevelMax = Math.max(stats.manualLevelMax, level);
  21442. stats.fragChangedManual++;
  21443. if (!this.levelLastAuto && level !== stats.manualLevelLast) {
  21444. stats.manualLevelSwitch++;
  21445. }
  21446. } else {
  21447. stats.manualLevelMin = stats.manualLevelMax = level;
  21448. stats.manualLevelSwitch = 0;
  21449. stats.fragChangedManual = 1;
  21450. }
  21451. stats.manualLevelLast = level;
  21452. }
  21453. this.levelLastAuto = autoLevel;
  21454. });
  21455. hls.on(Hls.Events.FRAG_LOAD_EMERGENCY_ABORTED, function (eventName, data) {
  21456. if (stats) {
  21457. if (stats.fragLoadEmergencyAborted === undefined) {
  21458. stats.fragLoadEmergencyAborted = 1;
  21459. } else {
  21460. stats.fragLoadEmergencyAborted++;
  21461. }
  21462. }
  21463. });
  21464. hls.on(Hls.Events.FRAG_DECRYPTED, function (eventName, data) {
  21465. if (!stats.fragDecrypted) {
  21466. stats.fragDecrypted = 0;
  21467. this.totalDecryptTime = 0;
  21468. stats.fragAvgDecryptTime = 0;
  21469. }
  21470. stats.fragDecrypted++;
  21471. this.totalDecryptTime += data.stats.tdecrypt - data.stats.tstart;
  21472. stats.fragAvgDecryptTime = this.totalDecryptTime / stats.fragDecrypted;
  21473. });
  21474. hls.on(Hls.Events.ERROR, function (eventName, data) {
  21475. console.warn('Error event:', data);
  21476. switch (data.details) {
  21477. case Hls.ErrorDetails.MANIFEST_LOAD_ERROR:
  21478. try {
  21479. $('#errorOut').html('Cannot load <a href="' + data.context.url + '">' + url + '</a><br>HTTP response code:' + data.response.code + ' <br>' + data.response.text);
  21480. if (data.response.code === 0) {
  21481. $('#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');
  21482. }
  21483. } catch (err) {
  21484. $('#errorOut').html('Cannot load <a href="' + data.context.url + '">' + url + '</a><br>Response body: ' + data.response.text);
  21485. }
  21486. break;
  21487. case Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  21488. logError('Timeout while loading manifest');
  21489. break;
  21490. case Hls.ErrorDetails.MANIFEST_PARSING_ERROR:
  21491. logError('Error while parsing manifest:' + data.reason);
  21492. break;
  21493. case Hls.ErrorDetails.LEVEL_EMPTY_ERROR:
  21494. logError('Loaded level contains no fragments ' + data.level + ' ' + data.url);
  21495. // handleLevelError demonstrates how to remove a level that errors followed by a downswitch
  21496. // handleLevelError(data);
  21497. break;
  21498. case Hls.ErrorDetails.LEVEL_LOAD_ERROR:
  21499. logError('Error while loading level playlist ' + data.context.level + ' ' + data.url);
  21500. // handleLevelError demonstrates how to remove a level that errors followed by a downswitch
  21501. // handleLevelError(data);
  21502. break;
  21503. case Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  21504. logError('Timeout while loading level playlist ' + data.context.level + ' ' + data.url);
  21505. // handleLevelError demonstrates how to remove a level that errors followed by a downswitch
  21506. // handleLevelError(data);
  21507. break;
  21508. case Hls.ErrorDetails.LEVEL_SWITCH_ERROR:
  21509. logError('Error while trying to switch to level ' + data.level);
  21510. break;
  21511. case Hls.ErrorDetails.FRAG_LOAD_ERROR:
  21512. logError('Error while loading fragment ' + data.frag.url);
  21513. break;
  21514. case Hls.ErrorDetails.FRAG_LOAD_TIMEOUT:
  21515. logError('Timeout while loading fragment ' + data.frag.url);
  21516. break;
  21517. case Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
  21518. logError('Fragment-loop loading error');
  21519. break;
  21520. case Hls.ErrorDetails.FRAG_DECRYPT_ERROR:
  21521. logError('Decrypting error:' + data.reason);
  21522. break;
  21523. case Hls.ErrorDetails.FRAG_PARSING_ERROR:
  21524. logError('Parsing error:' + data.reason);
  21525. break;
  21526. case Hls.ErrorDetails.KEY_LOAD_ERROR:
  21527. logError('Error while loading key ' + data.frag.decryptdata.uri);
  21528. break;
  21529. case Hls.ErrorDetails.KEY_LOAD_TIMEOUT:
  21530. logError('Timeout while loading key ' + data.frag.decryptdata.uri);
  21531. break;
  21532. case Hls.ErrorDetails.BUFFER_APPEND_ERROR:
  21533. logError('Buffer append error');
  21534. break;
  21535. case Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  21536. logError('Buffer add codec error for ' + data.mimeType + ':' + data.error.message);
  21537. break;
  21538. case Hls.ErrorDetails.BUFFER_APPENDING_ERROR:
  21539. logError('Buffer appending error');
  21540. break;
  21541. case Hls.ErrorDetails.BUFFER_STALLED_ERROR:
  21542. logError('Buffer stalled error');
  21543. if (stopOnStall) {
  21544. hls.stopLoad();
  21545. video.pause();
  21546. }
  21547. break;
  21548. }
  21549. if (data.fatal) {
  21550. console.error("Fatal error : " + data.details);
  21551. switch (data.type) {
  21552. case Hls.ErrorTypes.MEDIA_ERROR:
  21553. logError("A media error occurred: " + data.details);
  21554. handleMediaError();
  21555. break;
  21556. case Hls.ErrorTypes.NETWORK_ERROR:
  21557. logError("A network error occurred: " + data.details);
  21558. break;
  21559. default:
  21560. logError("An unrecoverable error occurred: " + data.details);
  21561. hls.destroy();
  21562. break;
  21563. }
  21564. }
  21565. if (!stats) {
  21566. stats = {};
  21567. }
  21568. // track all errors independently
  21569. if (stats[data.details] === undefined) {
  21570. stats[data.details] = 1;
  21571. } else {
  21572. stats[data.details] += 1;
  21573. }
  21574. // track fatal error
  21575. if (data.fatal) {
  21576. if (stats.fatalError === undefined) {
  21577. stats.fatalError = 1;
  21578. } else {
  21579. stats.fatalError += 1;
  21580. }
  21581. }
  21582. $('#statisticsOut').text(JSON.stringify(sortObject(stats), null, '\t'));
  21583. });
  21584. hls.on(Hls.Events.BUFFER_CREATED, function (eventName, data) {
  21585. tracks = data.tracks;
  21586. });
  21587. hls.on(Hls.Events.BUFFER_APPENDING, function (eventName, data) {
  21588. if (dumpfMP4) {
  21589. fmp4Data[data.type].push(data.data);
  21590. }
  21591. });
  21592. hls.on(Hls.Events.FPS_DROP, function (eventName, data) {
  21593. var event = {
  21594. time: self.performance.now() - events.t0,
  21595. type: 'frame drop',
  21596. name: data.currentDropped + '/' + data.currentDecoded
  21597. };
  21598. events.video.push(event);
  21599. trimEventHistory();
  21600. if (stats) {
  21601. if (stats.fpsDropEvent === undefined) {
  21602. stats.fpsDropEvent = 1;
  21603. } else {
  21604. stats.fpsDropEvent++;
  21605. }
  21606. stats.fpsTotalDroppedFrames = data.totalDroppedFrames;
  21607. }
  21608. });
  21609. }
  21610. function addVideoEventListeners(video) {
  21611. video.removeEventListener('resize', handleVideoEvent);
  21612. video.removeEventListener('seeking', handleVideoEvent);
  21613. video.removeEventListener('seeked', handleVideoEvent);
  21614. video.removeEventListener('pause', handleVideoEvent);
  21615. video.removeEventListener('play', handleVideoEvent);
  21616. video.removeEventListener('canplay', handleVideoEvent);
  21617. video.removeEventListener('canplaythrough', handleVideoEvent);
  21618. video.removeEventListener('ended', handleVideoEvent);
  21619. video.removeEventListener('playing', handleVideoEvent);
  21620. video.removeEventListener('error', handleVideoEvent);
  21621. video.removeEventListener('loadedmetadata', handleVideoEvent);
  21622. video.removeEventListener('loadeddata', handleVideoEvent);
  21623. video.removeEventListener('durationchange', handleVideoEvent);
  21624. video.removeEventListener('volumechange', handleVolumeEvent);
  21625. video.addEventListener('resize', handleVideoEvent);
  21626. video.addEventListener('seeking', handleVideoEvent);
  21627. video.addEventListener('seeked', handleVideoEvent);
  21628. video.addEventListener('pause', handleVideoEvent);
  21629. video.addEventListener('play', handleVideoEvent);
  21630. video.addEventListener('canplay', handleVideoEvent);
  21631. video.addEventListener('canplaythrough', handleVideoEvent);
  21632. video.addEventListener('ended', handleVideoEvent);
  21633. video.addEventListener('playing', handleVideoEvent);
  21634. video.addEventListener('error', handleVideoEvent);
  21635. video.addEventListener('loadedmetadata', handleVideoEvent);
  21636. video.addEventListener('loadeddata', handleVideoEvent);
  21637. video.addEventListener('durationchange', handleVideoEvent);
  21638. video.addEventListener('volumechange', handleVolumeEvent);
  21639. }
  21640. function handleUnsupported() {
  21641. if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1) {
  21642. 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>');
  21643. } else {
  21644. logStatus('Your Browser does not support MediaSourceExtension / MP4 mediasource');
  21645. }
  21646. }
  21647. function handleVideoEvent(evt) {
  21648. var data = '';
  21649. switch (evt.type) {
  21650. case 'durationchange':
  21651. if (evt.target.duration - lastDuration <= 0.5) {
  21652. // some browsers report several duration change events with almost the same value ... avoid spamming video events
  21653. return;
  21654. }
  21655. lastDuration = evt.target.duration;
  21656. data = Math.round(evt.target.duration * 1000);
  21657. break;
  21658. case 'resize':
  21659. data = evt.target.videoWidth + '/' + evt.target.videoHeight;
  21660. playerResize();
  21661. break;
  21662. case 'loadedmetadata':
  21663. case 'loadeddata':
  21664. case 'canplay':
  21665. case 'canplaythrough':
  21666. case 'ended':
  21667. case 'seeking':
  21668. case 'seeked':
  21669. case 'play':
  21670. case 'playing':
  21671. lastStartPosition = evt.target.currentTime;
  21672. case 'pause':
  21673. case 'waiting':
  21674. case 'stalled':
  21675. case 'error':
  21676. data = Math.round(evt.target.currentTime * 1000);
  21677. if (evt.type === 'error') {
  21678. var errorTxt;
  21679. var mediaError = evt.currentTarget.error;
  21680. switch (mediaError.code) {
  21681. case mediaError.MEDIA_ERR_ABORTED:
  21682. errorTxt = 'You aborted the video playback';
  21683. break;
  21684. case mediaError.MEDIA_ERR_DECODE:
  21685. errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support';
  21686. handleMediaError();
  21687. break;
  21688. case mediaError.MEDIA_ERR_NETWORK:
  21689. errorTxt = 'A network error caused the video download to fail part-way';
  21690. break;
  21691. case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
  21692. errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported';
  21693. break;
  21694. }
  21695. if (mediaError.message) {
  21696. errorTxt += ' - ' + mediaError.message;
  21697. }
  21698. logStatus(errorTxt);
  21699. console.error(errorTxt);
  21700. }
  21701. break;
  21702. }
  21703. var event = {
  21704. time: self.performance.now() - events.t0,
  21705. type: evt.type,
  21706. name: data
  21707. };
  21708. events.video.push(event);
  21709. if (evt.type === 'seeking') {
  21710. lastSeekingIdx = events.video.length - 1;
  21711. }
  21712. if (evt.type === 'seeked') {
  21713. events.video[lastSeekingIdx].duration = event.time - events.video[lastSeekingIdx].time;
  21714. }
  21715. trimEventHistory();
  21716. }
  21717. function handleVolumeEvent() {
  21718. localStorage.setItem(STORAGE_KEYS.volume, JSON.stringify({
  21719. muted: video.muted,
  21720. volume: video.volume
  21721. }));
  21722. }
  21723. function handleMediaError() {
  21724. if (autoRecoverError) {
  21725. var now = self.performance.now();
  21726. if (!self.recoverDecodingErrorDate || now - self.recoverDecodingErrorDate > 3000) {
  21727. self.recoverDecodingErrorDate = self.performance.now();
  21728. $('#statusOut').append(', trying to recover media error.');
  21729. hls.recoverMediaError();
  21730. } else {
  21731. if (!self.recoverSwapAudioCodecDate || now - self.recoverSwapAudioCodecDate > 3000) {
  21732. self.recoverSwapAudioCodecDate = self.performance.now();
  21733. $('#statusOut').append(', trying to swap audio codec and recover media error.');
  21734. hls.swapAudioCodec();
  21735. hls.recoverMediaError();
  21736. } else {
  21737. $('#statusOut').append(', cannot recover. Last media error recovery failed.');
  21738. }
  21739. }
  21740. }
  21741. }
  21742. function timeRangesToString(r) {
  21743. var log = '';
  21744. for (var i = 0; i < r.length; i++) {
  21745. log += '[' + r.start(i) + ', ' + r.end(i) + ']';
  21746. log += ' ';
  21747. }
  21748. return log;
  21749. }
  21750. function checkBuffer() {
  21751. var canvas = document.querySelector('#bufferedCanvas');
  21752. var ctx = canvas.getContext('2d');
  21753. var r = video.buffered;
  21754. var seekableEnd = getSeekableEnd();
  21755. var bufferingDuration;
  21756. if (r) {
  21757. ctx.fillStyle = 'black';
  21758. if (!canvas.width || canvas.width !== video.clientWidth) {
  21759. canvas.width = video.clientWidth;
  21760. }
  21761. ctx.fillRect(0, 0, canvas.width, canvas.height);
  21762. var pos = video.currentTime;
  21763. var bufferLen = 0;
  21764. ctx.fillStyle = 'gray';
  21765. for (var i = 0; i < r.length; i++) {
  21766. var start = r.start(i) / seekableEnd * canvas.width;
  21767. var end = r.end(i) / seekableEnd * canvas.width;
  21768. ctx.fillRect(start, 2, Math.max(2, end - start), 11);
  21769. if (pos >= r.start(i) && pos < r.end(i)) {
  21770. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  21771. bufferLen = r.end(i) - pos;
  21772. }
  21773. }
  21774. // check if we are in buffering / or playback ended state
  21775. if (bufferLen <= 0.1 && video.paused === false && pos - lastStartPosition > 0.5) {
  21776. if (lastDuration - pos <= 0.5 && events.isLive === false) ; else {
  21777. // we are not at the end of the playlist ... real buffering
  21778. if (bufferingIdx !== -1) {
  21779. bufferingDuration = self.performance.now() - events.t0 - events.video[bufferingIdx].time;
  21780. events.video[bufferingIdx].duration = bufferingDuration;
  21781. events.video[bufferingIdx].name = bufferingDuration;
  21782. } else {
  21783. events.video.push({
  21784. type: 'buffering',
  21785. time: self.performance.now() - events.t0
  21786. });
  21787. trimEventHistory();
  21788. // we are in buffering state
  21789. bufferingIdx = events.video.length - 1;
  21790. }
  21791. }
  21792. }
  21793. if (bufferLen > 0.1 && bufferingIdx !== -1) {
  21794. bufferingDuration = self.performance.now() - events.t0 - events.video[bufferingIdx].time;
  21795. events.video[bufferingIdx].duration = bufferingDuration;
  21796. events.video[bufferingIdx].name = bufferingDuration;
  21797. // we are out of buffering state
  21798. bufferingIdx = -1;
  21799. }
  21800. // update buffer/position for current Time
  21801. var event = {
  21802. time: self.performance.now() - events.t0,
  21803. buffer: Math.round(bufferLen * 1000),
  21804. pos: Math.round(pos * 1000)
  21805. };
  21806. var bufEvents = events.buffer;
  21807. var bufEventLen = bufEvents.length;
  21808. if (bufEventLen > 1) {
  21809. var event0 = bufEvents[bufEventLen - 2];
  21810. var event1 = bufEvents[bufEventLen - 1];
  21811. var slopeBuf0 = (event0.buffer - event1.buffer) / (event0.time - event1.time);
  21812. var slopeBuf1 = (event1.buffer - event.buffer) / (event1.time - event.time);
  21813. var slopePos0 = (event0.pos - event1.pos) / (event0.time - event1.time);
  21814. var slopePos1 = (event1.pos - event.pos) / (event1.time - event.time);
  21815. // compute slopes. if less than 30% difference, remove event1
  21816. if ((slopeBuf0 === slopeBuf1 || Math.abs(slopeBuf0 / slopeBuf1 - 1) <= 0.3) && (slopePos0 === slopePos1 || Math.abs(slopePos0 / slopePos1 - 1) <= 0.3)) {
  21817. bufEvents.pop();
  21818. }
  21819. }
  21820. events.buffer.push(event);
  21821. trimEventHistory();
  21822. self.refreshCanvas();
  21823. if ($('#statsDisplayTab').is(':visible')) {
  21824. var log = "Duration: " + video.duration + "\nBuffered: " + timeRangesToString(video.buffered) + "\nSeekable: " + timeRangesToString(video.seekable) + "\nPlayed: " + timeRangesToString(video.played) + "\n";
  21825. if (hls.media) {
  21826. for (var type in tracks) {
  21827. log += "Buffer for " + type + " contains:" + timeRangesToString(tracks[type].buffer.buffered) + "\n";
  21828. }
  21829. var videoPlaybackQuality = video.getVideoPlaybackQuality;
  21830. if (videoPlaybackQuality && typeof videoPlaybackQuality === typeof Function) {
  21831. log += "Dropped frames: " + video.getVideoPlaybackQuality().droppedVideoFrames + "\n";
  21832. log += "Corrupted frames: " + video.getVideoPlaybackQuality().corruptedVideoFrames + "\n";
  21833. } else if (video.webkitDroppedFrameCount) {
  21834. log += "Dropped frames: " + video.webkitDroppedFrameCount + "\n";
  21835. }
  21836. }
  21837. log += "TTFB Estimate: " + hls.ttfbEstimate.toFixed(3) + "\n";
  21838. log += "Bandwidth Estimate: " + hls.bandwidthEstimate.toFixed(3) + "\n";
  21839. if (events.isLive) {
  21840. 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");
  21841. if (stats.fragProgramDateTime) {
  21842. var currentPDT = stats.fragProgramDateTime + (video.currentTime - stats.fragStart) * 1000;
  21843. log += " Program Date Time: " + new Date(currentPDT).toISOString();
  21844. var pdtLatency = (Date.now() - currentPDT) / 1000;
  21845. if (pdtLatency > 0) {
  21846. log += " (" + pdtLatency.toFixed(3) + " seconds ago)";
  21847. }
  21848. }
  21849. }
  21850. $('#bufferedOut').text(log);
  21851. $('#statisticsOut').text(JSON.stringify(sortObject(stats), null, '\t'));
  21852. }
  21853. ctx.fillStyle = 'blue';
  21854. var x = video.currentTime / seekableEnd * canvas.width;
  21855. ctx.fillRect(x, 0, 2, 15);
  21856. } else if (ctx.fillStyle !== 'black') {
  21857. ctx.fillStyle = 'black';
  21858. ctx.fillRect(0, 0, canvas.width, canvas.height);
  21859. }
  21860. }
  21861. function showCanvas() {
  21862. self.showMetrics();
  21863. $('#bufferedOut').show();
  21864. $('#bufferedCanvas').show();
  21865. }
  21866. function hideCanvas() {
  21867. self.hideMetrics();
  21868. $('#bufferedOut').hide();
  21869. $('#bufferedCanvas').hide();
  21870. }
  21871. function getMetrics() {
  21872. var json = JSON.stringify(events);
  21873. var jsonpacked = mainExports.pack(json);
  21874. // console.log('packing JSON from ' + json.length + ' to ' + jsonpacked.length + ' bytes');
  21875. return btoa(jsonpacked);
  21876. }
  21877. self.copyMetricsToClipBoard = function () {
  21878. copyTextToClipboard(getMetrics());
  21879. };
  21880. self.goToMetrics = function () {
  21881. var url = document.URL;
  21882. url = url.slice(0, url.lastIndexOf('/') + 1) + 'metrics.html';
  21883. self.open(url, '_blank');
  21884. };
  21885. function goToMetricsPermaLink() {
  21886. var url = document.URL;
  21887. var b64 = getMetrics();
  21888. url = url.slice(0, url.lastIndexOf('/') + 1) + 'metrics.html#data=' + b64;
  21889. self.open(url, '_blank');
  21890. }
  21891. function onClickBufferedRange(event) {
  21892. var canvas = document.querySelector('#bufferedCanvas');
  21893. var target = (event.clientX - canvas.offsetLeft) / canvas.width * getSeekableEnd();
  21894. video.currentTime = target;
  21895. }
  21896. function getSeekableEnd() {
  21897. if (isFinite(video.duration)) {
  21898. return video.duration;
  21899. }
  21900. if (video.seekable.length) {
  21901. return video.seekable.end(video.seekable.length - 1);
  21902. }
  21903. return 0;
  21904. }
  21905. function getLevelButtonHtml(key, levels, onclickReplace, autoEnabled) {
  21906. var onclickAuto = (key + "=-1").replace(/^(\w+)=([^=]+)$/, onclickReplace);
  21907. var codecs = levels.reduce(function (uniqueCodecs, level) {
  21908. var levelCodecs = codecs2label(level.attrs.CODECS);
  21909. if (levelCodecs && uniqueCodecs.indexOf(levelCodecs) === -1) {
  21910. uniqueCodecs.push(levelCodecs);
  21911. }
  21912. return uniqueCodecs;
  21913. }, []);
  21914. return "<button type=\"button\" class=\"btn btn-sm " + (autoEnabled ? 'btn-primary' : 'btn-success') + "\" onclick=\"" + onclickAuto + "\">auto</button>" + levels.map(function (level, i) {
  21915. var enabled = hls[key] === i;
  21916. var onclick = (key + "=" + i).replace(/^(\w+)=(\w+)$/, onclickReplace);
  21917. var label = level2label(levels[i], i, codecs);
  21918. return "<button type=\"button\" class=\"btn btn-sm " + (enabled ? 'btn-primary' : 'btn-success') + "\" onclick=\"" + onclick + "\">" + label + "</button>";
  21919. }).join('');
  21920. }
  21921. function updateLevelInfo() {
  21922. var levels = hls.levels;
  21923. if (!levels) {
  21924. return;
  21925. }
  21926. var htmlCurrentLevel = getLevelButtonHtml('currentLevel', levels, 'hls.$1=$2', hls.autoLevelEnabled);
  21927. var htmlNextLevel = getLevelButtonHtml('nextLevel', levels, 'hls.$1=$2', hls.autoLevelEnabled);
  21928. var htmlLoadLevel = getLevelButtonHtml('loadLevel', levels, 'hls.$1=$2', hls.autoLevelEnabled);
  21929. var htmlCapLevel = getLevelButtonHtml('autoLevelCapping', levels, 'levelCapping=hls.$1=$2;updateLevelInfo();onDemoConfigChanged();', hls.autoLevelCapping === -1);
  21930. if ($('#currentLevelControl').html() !== htmlCurrentLevel) {
  21931. $('#currentLevelControl').html(htmlCurrentLevel);
  21932. }
  21933. if ($('#nextLevelControl').html() !== htmlNextLevel) {
  21934. $('#nextLevelControl').html(htmlNextLevel);
  21935. }
  21936. if ($('#loadLevelControl').html() !== htmlLoadLevel) {
  21937. $('#loadLevelControl').html(htmlLoadLevel);
  21938. }
  21939. if ($('#levelCappingControl').html() !== htmlCapLevel) {
  21940. $('#levelCappingControl').html(htmlCapLevel);
  21941. }
  21942. }
  21943. function updateAudioTrackInfo() {
  21944. var buttonTemplate = '<button type="button" class="btn btn-sm ';
  21945. var buttonEnabled = 'btn-primary" ';
  21946. var buttonDisabled = 'btn-success" ';
  21947. var html1 = '';
  21948. var audioTrackId = hls.audioTrack;
  21949. var len = hls.audioTracks.length;
  21950. var track = hls.audioTracks[audioTrackId];
  21951. for (var i = 0; i < len; i++) {
  21952. html1 += buttonTemplate;
  21953. if (audioTrackId === i) {
  21954. html1 += buttonEnabled;
  21955. } else {
  21956. html1 += buttonDisabled;
  21957. }
  21958. html1 += 'onclick="hls.audioTrack=' + i + '">' + hls.audioTracks[i].name + '</button>';
  21959. }
  21960. $('#audioTrackLabel').text(track ? track.lang || track.name : 'None selected');
  21961. $('#audioTrackControl').html(html1);
  21962. }
  21963. function codecs2label(levelCodecs) {
  21964. if (levelCodecs) {
  21965. return levelCodecs.replace(/([ah]vc.)[^,;]+/, '$1').replace('mp4a.40.2', 'mp4a');
  21966. }
  21967. return '';
  21968. }
  21969. function level2label(level, i, manifestCodecs) {
  21970. var levelCodecs = codecs2label(level.attrs.CODECS);
  21971. var levelNameInfo = level.name ? "\"" + level.name + "\": " : '';
  21972. var codecInfo = levelCodecs && manifestCodecs.length > 1 ? " / " + levelCodecs : '';
  21973. if (level.height) {
  21974. return i + " (" + levelNameInfo + level.height + "p / " + Math.round(level.bitrate / 1024) + "kb" + codecInfo + ")";
  21975. }
  21976. if (level.bitrate) {
  21977. return i + " (" + levelNameInfo + Math.round(level.bitrate / 1024) + "kb" + codecInfo + ")";
  21978. }
  21979. if (codecInfo) {
  21980. return i + " (" + levelNameInfo + levelCodecs + ")";
  21981. }
  21982. if (level.name) {
  21983. return i + " (" + level.name + ")";
  21984. }
  21985. return "" + i;
  21986. }
  21987. function getDemoConfigPropOrDefault(propName, defaultVal) {
  21988. return typeof demoConfig[propName] !== 'undefined' ? demoConfig[propName] : defaultVal;
  21989. }
  21990. function getURLParam(sParam, defaultValue) {
  21991. var sPageURL = self.location.search.substring(1);
  21992. var sURLVariables = sPageURL.split('&');
  21993. for (var i = 0; i < sURLVariables.length; i++) {
  21994. var sParameterName = sURLVariables[i].split('=');
  21995. if (sParameterName[0] === sParam) {
  21996. return sParameterName[1] === 'undefined' ? undefined : sParameterName[1] === 'false' ? false : sParameterName[1];
  21997. }
  21998. }
  21999. return defaultValue;
  22000. }
  22001. function onDemoConfigChanged(firstLoad) {
  22002. demoConfig = {
  22003. enableStreaming: enableStreaming,
  22004. autoRecoverError: autoRecoverError,
  22005. stopOnStall: stopOnStall,
  22006. dumpfMP4: dumpfMP4,
  22007. levelCapping: levelCapping,
  22008. limitMetrics: limitMetrics
  22009. };
  22010. if (configPersistenceEnabled) {
  22011. persistEditorValue();
  22012. }
  22013. var serializedDemoConfig = btoa(JSON.stringify(demoConfig));
  22014. var baseURL = document.URL.split('?')[0];
  22015. var streamURL = $('#streamURL').val();
  22016. var permalinkURL = baseURL + "?src=" + encodeURIComponent(streamURL) + "&demoConfig=" + serializedDemoConfig;
  22017. $('#StreamPermalink').html("<a href=\"" + permalinkURL + "\">" + permalinkURL + "</a>");
  22018. if (!firstLoad && self.location.href !== permalinkURL) {
  22019. self.history.pushState(null, null, permalinkURL);
  22020. }
  22021. }
  22022. function onConfigPersistenceChanged(event) {
  22023. configPersistenceEnabled = event.target.checked;
  22024. localStorage.setItem(STORAGE_KEYS.Editor_Persistence, JSON.stringify(configPersistenceEnabled));
  22025. if (configPersistenceEnabled) {
  22026. persistEditorValue();
  22027. } else {
  22028. localStorage.removeItem(STORAGE_KEYS.Hls_Config);
  22029. }
  22030. }
  22031. function getEditorValue(options) {
  22032. options = $.extend({
  22033. parse: false
  22034. }, options || {});
  22035. var value = configEditor.session.getValue();
  22036. if (options.parse) {
  22037. try {
  22038. value = JSON.parse(value);
  22039. } catch (e) {
  22040. console.warn('[getEditorValue] could not parse editor value', e);
  22041. value = {};
  22042. }
  22043. }
  22044. return value;
  22045. }
  22046. function getPersistedHlsConfig() {
  22047. var value = localStorage.getItem(STORAGE_KEYS.Hls_Config);
  22048. if (value === null) {
  22049. return value;
  22050. }
  22051. try {
  22052. value = JSON.parse(value);
  22053. } catch (e) {
  22054. console.warn('[getPersistedHlsConfig] could not hls config json', e);
  22055. value = {};
  22056. }
  22057. return value;
  22058. }
  22059. function persistEditorValue() {
  22060. localStorage.setItem(STORAGE_KEYS.Hls_Config, getEditorValue());
  22061. }
  22062. function setupConfigEditor() {
  22063. configEditor = self.ace.edit('config-editor');
  22064. configEditor.setTheme('ace/theme/github');
  22065. configEditor.session.setMode('ace/mode/json');
  22066. var contents = hlsjsDefaults;
  22067. var shouldRestorePersisted = JSON.parse(localStorage.getItem(STORAGE_KEYS.Editor_Persistence)) === true;
  22068. if (shouldRestorePersisted) {
  22069. $.extend(contents, getPersistedHlsConfig());
  22070. }
  22071. var elPersistence = document.querySelector('#config-persistence');
  22072. elPersistence.addEventListener('change', onConfigPersistenceChanged);
  22073. elPersistence.checked = shouldRestorePersisted;
  22074. configPersistenceEnabled = shouldRestorePersisted;
  22075. updateConfigEditorValue(contents);
  22076. }
  22077. function setupTimelineChart() {
  22078. var canvas = document.querySelector('#timeline-chart');
  22079. var chart = new TimelineChart(canvas, {
  22080. responsive: false
  22081. });
  22082. resizeHandlers.push(function () {
  22083. chart.resize();
  22084. });
  22085. chart.resize();
  22086. return chart;
  22087. }
  22088. function addChartEventListeners(hls) {
  22089. var updateLevelOrTrack = function updateLevelOrTrack(eventName, data) {
  22090. chart.updateLevelOrTrack(data.details);
  22091. };
  22092. var updateFragment = function updateFragment(eventName, data) {
  22093. if (data.stats) {
  22094. // Convert 0.x stats to partial v1 stats
  22095. var _data$stats = data.stats,
  22096. retry = _data$stats.retry,
  22097. loaded = _data$stats.loaded,
  22098. total = _data$stats.total,
  22099. trequest = _data$stats.trequest,
  22100. tfirst = _data$stats.tfirst,
  22101. tload = _data$stats.tload;
  22102. if (trequest && tload) {
  22103. data.frag.stats = {
  22104. loaded: loaded,
  22105. retry: retry,
  22106. total: total,
  22107. loading: {
  22108. start: trequest,
  22109. first: tfirst,
  22110. end: tload
  22111. }
  22112. };
  22113. }
  22114. }
  22115. chart.updateFragment(data);
  22116. };
  22117. var updateChart = function updateChart() {
  22118. chart.update();
  22119. };
  22120. hls.on(Hls.Events.MANIFEST_LOADING, function () {
  22121. chart.reset();
  22122. }, chart);
  22123. hls.on(Hls.Events.MANIFEST_PARSED, function (eventName, data) {
  22124. var levels = data.levels;
  22125. chart.removeType('level');
  22126. chart.removeType('audioTrack');
  22127. chart.removeType('subtitleTrack');
  22128. chart.updateLevels(levels);
  22129. }, chart);
  22130. hls.on(Hls.Events.BUFFER_CREATED, function (eventName, _ref) {
  22131. var tracks = _ref.tracks;
  22132. chart.updateSourceBuffers(tracks, hls.media);
  22133. }, chart);
  22134. hls.on(Hls.Events.BUFFER_RESET, function () {
  22135. chart.removeSourceBuffers();
  22136. }, chart);
  22137. hls.on(Hls.Events.LEVELS_UPDATED, function (eventName, _ref2) {
  22138. var levels = _ref2.levels;
  22139. chart.removeType('level');
  22140. chart.updateLevels(levels);
  22141. });
  22142. hls.on(Hls.Events.LEVEL_SWITCHED, function (eventName, _ref3) {
  22143. var level = _ref3.level;
  22144. chart.removeType('level');
  22145. chart.updateLevels(hls.levels, level);
  22146. }, chart);
  22147. hls.on(Hls.Events.LEVEL_LOADING, function () {
  22148. // TODO: mutate level datasets
  22149. // Update loadLevel
  22150. chart.removeType('level');
  22151. chart.updateLevels(hls.levels);
  22152. }, chart);
  22153. hls.on(Hls.Events.LEVEL_UPDATED, function (eventName, _ref4) {
  22154. var details = _ref4.details;
  22155. chart.updateLevelOrTrack(details);
  22156. }, chart);
  22157. hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, function (eventName, _ref5) {
  22158. var audioTracks = _ref5.audioTracks;
  22159. chart.removeType('audioTrack');
  22160. chart.updateAudioTracks(audioTracks);
  22161. }, chart);
  22162. hls.on(Hls.Events.SUBTITLE_TRACKS_UPDATED, function (eventName, _ref6) {
  22163. var subtitleTracks = _ref6.subtitleTracks;
  22164. chart.removeType('subtitleTrack');
  22165. chart.updateSubtitleTracks(subtitleTracks);
  22166. }, chart);
  22167. hls.on(Hls.Events.AUDIO_TRACK_SWITCHED, function (eventName) {
  22168. // TODO: mutate level datasets
  22169. chart.removeType('audioTrack');
  22170. chart.updateAudioTracks(hls.audioTracks);
  22171. }, chart);
  22172. hls.on(Hls.Events.SUBTITLE_TRACK_SWITCH, function (eventName) {
  22173. // TODO: mutate level datasets
  22174. chart.removeType('subtitleTrack');
  22175. chart.updateSubtitleTracks(hls.subtitleTracks);
  22176. }, chart);
  22177. hls.on(Hls.Events.AUDIO_TRACK_LOADED, updateLevelOrTrack, chart);
  22178. hls.on(Hls.Events.SUBTITLE_TRACK_LOADED, updateLevelOrTrack, chart);
  22179. hls.on(Hls.Events.LEVEL_PTS_UPDATED, updateLevelOrTrack, chart);
  22180. hls.on(Hls.Events.FRAG_LOADED, updateFragment, chart);
  22181. hls.on(Hls.Events.FRAG_PARSED, updateFragment, chart);
  22182. hls.on(Hls.Events.FRAG_CHANGED, updateFragment, chart);
  22183. hls.on(Hls.Events.BUFFER_APPENDING, updateChart, chart);
  22184. hls.on(Hls.Events.BUFFER_APPENDED, updateChart, chart);
  22185. hls.on(Hls.Events.BUFFER_FLUSHED, updateChart, chart);
  22186. }
  22187. function updateConfigEditorValue(obj) {
  22188. var json = JSON.stringify(obj, null, 2);
  22189. configEditor.session.setValue(json);
  22190. }
  22191. function applyConfigEditorValue() {
  22192. onDemoConfigChanged();
  22193. loadSelectedStream();
  22194. }
  22195. function createfMP4(type) {
  22196. if (fmp4Data[type].length) {
  22197. var blob = new Blob([arrayConcat(fmp4Data[type])], {
  22198. type: 'application/octet-stream'
  22199. });
  22200. var filename = type + '-' + new Date().toISOString() + '.mp4';
  22201. self.saveAs(blob, filename);
  22202. // $('body').append('<a download="hlsjs-' + filename + '" href="' + self.URL.createObjectURL(blob) + '">Download ' + filename + ' track</a><br>');
  22203. } else if (!dumpfMP4) {
  22204. console.error('Check "Dump transmuxed fMP4 data" first to make appended media available for saving.');
  22205. }
  22206. }
  22207. function arrayConcat(inputArray) {
  22208. var totalLength = inputArray.reduce(function (prev, cur) {
  22209. return prev + cur.length;
  22210. }, 0);
  22211. var result = new Uint8Array(totalLength);
  22212. var offset = 0;
  22213. inputArray.forEach(function (element) {
  22214. result.set(element, offset);
  22215. offset += element.length;
  22216. });
  22217. return result;
  22218. }
  22219. function hideAllTabs() {
  22220. $('.demo-tab-btn').css('background-color', '');
  22221. $('.demo-tab').hide();
  22222. }
  22223. function toggleTabClick(btn) {
  22224. toggleTab(btn);
  22225. var tabIndexes = $('.demo-tab-btn').toArray().map(function (el, i) {
  22226. return $('#' + $(el).data('tab')).is(':visible') ? i : null;
  22227. }).filter(function (i) {
  22228. return i !== null;
  22229. });
  22230. localStorage.setItem(STORAGE_KEYS.demo_tabs, tabIndexes.join(','));
  22231. }
  22232. function toggleTab(btn, dontHideOpenTabs) {
  22233. var tabElId = $(btn).data('tab');
  22234. // eslint-disable-next-line no-restricted-globals
  22235. var modifierPressed = dontHideOpenTabs || self.event && (self.event.metaKey || self.event.shiftKey);
  22236. if (!modifierPressed) {
  22237. hideAllTabs();
  22238. }
  22239. if (modifierPressed) {
  22240. $("#" + tabElId).toggle();
  22241. } else {
  22242. $("#" + tabElId).show();
  22243. }
  22244. $(btn).css('background-color', $("#" + tabElId).is(':visible') ? 'orange' : '');
  22245. if (!$('#statsDisplayTab').is(':visible')) {
  22246. self.hideMetrics();
  22247. }
  22248. if (hls) {
  22249. if ($('#timelineTab').is(':visible')) {
  22250. chart.show();
  22251. chart.resize(chart.chart.data ? chart.chart.data.datasets : null);
  22252. } else {
  22253. chart.hide();
  22254. }
  22255. }
  22256. }
  22257. function appendLog(textElId, message) {
  22258. var el = $('#' + textElId);
  22259. var logText = el.text();
  22260. if (logText.length) {
  22261. logText += '\n';
  22262. }
  22263. var timestamp = (Date.now() - startTime) / 1000;
  22264. var newMessage = timestamp + ' | ' + message;
  22265. logText += newMessage;
  22266. // update
  22267. el.text(logText);
  22268. var element = el[0];
  22269. element.scrollTop = element.scrollHeight - element.clientHeight;
  22270. }
  22271. function logStatus(message) {
  22272. appendLog('statusOut', message);
  22273. }
  22274. function logError(message) {
  22275. appendLog('errorOut', message);
  22276. }
  22277. }));
  22278. //# sourceMappingURL=hls-demo.js.map