Chart.bundle.js 534 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288
  1. /*!
  2. * Chart.js v2.8.0
  3. * https://www.chartjs.org
  4. * (c) 2019 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  9. typeof define === 'function' && define.amd ? define(factory) :
  10. (global.Chart = factory());
  11. }(this, (function () { 'use strict';
  12. /* MIT license */
  13. var conversions = {
  14. rgb2hsl: rgb2hsl,
  15. rgb2hsv: rgb2hsv,
  16. rgb2hwb: rgb2hwb,
  17. rgb2cmyk: rgb2cmyk,
  18. rgb2keyword: rgb2keyword,
  19. rgb2xyz: rgb2xyz,
  20. rgb2lab: rgb2lab,
  21. rgb2lch: rgb2lch,
  22. hsl2rgb: hsl2rgb,
  23. hsl2hsv: hsl2hsv,
  24. hsl2hwb: hsl2hwb,
  25. hsl2cmyk: hsl2cmyk,
  26. hsl2keyword: hsl2keyword,
  27. hsv2rgb: hsv2rgb,
  28. hsv2hsl: hsv2hsl,
  29. hsv2hwb: hsv2hwb,
  30. hsv2cmyk: hsv2cmyk,
  31. hsv2keyword: hsv2keyword,
  32. hwb2rgb: hwb2rgb,
  33. hwb2hsl: hwb2hsl,
  34. hwb2hsv: hwb2hsv,
  35. hwb2cmyk: hwb2cmyk,
  36. hwb2keyword: hwb2keyword,
  37. cmyk2rgb: cmyk2rgb,
  38. cmyk2hsl: cmyk2hsl,
  39. cmyk2hsv: cmyk2hsv,
  40. cmyk2hwb: cmyk2hwb,
  41. cmyk2keyword: cmyk2keyword,
  42. keyword2rgb: keyword2rgb,
  43. keyword2hsl: keyword2hsl,
  44. keyword2hsv: keyword2hsv,
  45. keyword2hwb: keyword2hwb,
  46. keyword2cmyk: keyword2cmyk,
  47. keyword2lab: keyword2lab,
  48. keyword2xyz: keyword2xyz,
  49. xyz2rgb: xyz2rgb,
  50. xyz2lab: xyz2lab,
  51. xyz2lch: xyz2lch,
  52. lab2xyz: lab2xyz,
  53. lab2rgb: lab2rgb,
  54. lab2lch: lab2lch,
  55. lch2lab: lch2lab,
  56. lch2xyz: lch2xyz,
  57. lch2rgb: lch2rgb
  58. };
  59. function rgb2hsl(rgb) {
  60. var r = rgb[0]/255,
  61. g = rgb[1]/255,
  62. b = rgb[2]/255,
  63. min = Math.min(r, g, b),
  64. max = Math.max(r, g, b),
  65. delta = max - min,
  66. h, s, l;
  67. if (max == min)
  68. h = 0;
  69. else if (r == max)
  70. h = (g - b) / delta;
  71. else if (g == max)
  72. h = 2 + (b - r) / delta;
  73. else if (b == max)
  74. h = 4 + (r - g)/ delta;
  75. h = Math.min(h * 60, 360);
  76. if (h < 0)
  77. h += 360;
  78. l = (min + max) / 2;
  79. if (max == min)
  80. s = 0;
  81. else if (l <= 0.5)
  82. s = delta / (max + min);
  83. else
  84. s = delta / (2 - max - min);
  85. return [h, s * 100, l * 100];
  86. }
  87. function rgb2hsv(rgb) {
  88. var r = rgb[0],
  89. g = rgb[1],
  90. b = rgb[2],
  91. min = Math.min(r, g, b),
  92. max = Math.max(r, g, b),
  93. delta = max - min,
  94. h, s, v;
  95. if (max == 0)
  96. s = 0;
  97. else
  98. s = (delta/max * 1000)/10;
  99. if (max == min)
  100. h = 0;
  101. else if (r == max)
  102. h = (g - b) / delta;
  103. else if (g == max)
  104. h = 2 + (b - r) / delta;
  105. else if (b == max)
  106. h = 4 + (r - g) / delta;
  107. h = Math.min(h * 60, 360);
  108. if (h < 0)
  109. h += 360;
  110. v = ((max / 255) * 1000) / 10;
  111. return [h, s, v];
  112. }
  113. function rgb2hwb(rgb) {
  114. var r = rgb[0],
  115. g = rgb[1],
  116. b = rgb[2],
  117. h = rgb2hsl(rgb)[0],
  118. w = 1/255 * Math.min(r, Math.min(g, b)),
  119. b = 1 - 1/255 * Math.max(r, Math.max(g, b));
  120. return [h, w * 100, b * 100];
  121. }
  122. function rgb2cmyk(rgb) {
  123. var r = rgb[0] / 255,
  124. g = rgb[1] / 255,
  125. b = rgb[2] / 255,
  126. c, m, y, k;
  127. k = Math.min(1 - r, 1 - g, 1 - b);
  128. c = (1 - r - k) / (1 - k) || 0;
  129. m = (1 - g - k) / (1 - k) || 0;
  130. y = (1 - b - k) / (1 - k) || 0;
  131. return [c * 100, m * 100, y * 100, k * 100];
  132. }
  133. function rgb2keyword(rgb) {
  134. return reverseKeywords[JSON.stringify(rgb)];
  135. }
  136. function rgb2xyz(rgb) {
  137. var r = rgb[0] / 255,
  138. g = rgb[1] / 255,
  139. b = rgb[2] / 255;
  140. // assume sRGB
  141. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  142. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  143. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  144. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  145. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  146. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  147. return [x * 100, y *100, z * 100];
  148. }
  149. function rgb2lab(rgb) {
  150. var xyz = rgb2xyz(rgb),
  151. x = xyz[0],
  152. y = xyz[1],
  153. z = xyz[2],
  154. l, a, b;
  155. x /= 95.047;
  156. y /= 100;
  157. z /= 108.883;
  158. x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
  159. y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
  160. z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
  161. l = (116 * y) - 16;
  162. a = 500 * (x - y);
  163. b = 200 * (y - z);
  164. return [l, a, b];
  165. }
  166. function rgb2lch(args) {
  167. return lab2lch(rgb2lab(args));
  168. }
  169. function hsl2rgb(hsl) {
  170. var h = hsl[0] / 360,
  171. s = hsl[1] / 100,
  172. l = hsl[2] / 100,
  173. t1, t2, t3, rgb, val;
  174. if (s == 0) {
  175. val = l * 255;
  176. return [val, val, val];
  177. }
  178. if (l < 0.5)
  179. t2 = l * (1 + s);
  180. else
  181. t2 = l + s - l * s;
  182. t1 = 2 * l - t2;
  183. rgb = [0, 0, 0];
  184. for (var i = 0; i < 3; i++) {
  185. t3 = h + 1 / 3 * - (i - 1);
  186. t3 < 0 && t3++;
  187. t3 > 1 && t3--;
  188. if (6 * t3 < 1)
  189. val = t1 + (t2 - t1) * 6 * t3;
  190. else if (2 * t3 < 1)
  191. val = t2;
  192. else if (3 * t3 < 2)
  193. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  194. else
  195. val = t1;
  196. rgb[i] = val * 255;
  197. }
  198. return rgb;
  199. }
  200. function hsl2hsv(hsl) {
  201. var h = hsl[0],
  202. s = hsl[1] / 100,
  203. l = hsl[2] / 100,
  204. sv, v;
  205. if(l === 0) {
  206. // no need to do calc on black
  207. // also avoids divide by 0 error
  208. return [0, 0, 0];
  209. }
  210. l *= 2;
  211. s *= (l <= 1) ? l : 2 - l;
  212. v = (l + s) / 2;
  213. sv = (2 * s) / (l + s);
  214. return [h, sv * 100, v * 100];
  215. }
  216. function hsl2hwb(args) {
  217. return rgb2hwb(hsl2rgb(args));
  218. }
  219. function hsl2cmyk(args) {
  220. return rgb2cmyk(hsl2rgb(args));
  221. }
  222. function hsl2keyword(args) {
  223. return rgb2keyword(hsl2rgb(args));
  224. }
  225. function hsv2rgb(hsv) {
  226. var h = hsv[0] / 60,
  227. s = hsv[1] / 100,
  228. v = hsv[2] / 100,
  229. hi = Math.floor(h) % 6;
  230. var f = h - Math.floor(h),
  231. p = 255 * v * (1 - s),
  232. q = 255 * v * (1 - (s * f)),
  233. t = 255 * v * (1 - (s * (1 - f))),
  234. v = 255 * v;
  235. switch(hi) {
  236. case 0:
  237. return [v, t, p];
  238. case 1:
  239. return [q, v, p];
  240. case 2:
  241. return [p, v, t];
  242. case 3:
  243. return [p, q, v];
  244. case 4:
  245. return [t, p, v];
  246. case 5:
  247. return [v, p, q];
  248. }
  249. }
  250. function hsv2hsl(hsv) {
  251. var h = hsv[0],
  252. s = hsv[1] / 100,
  253. v = hsv[2] / 100,
  254. sl, l;
  255. l = (2 - s) * v;
  256. sl = s * v;
  257. sl /= (l <= 1) ? l : 2 - l;
  258. sl = sl || 0;
  259. l /= 2;
  260. return [h, sl * 100, l * 100];
  261. }
  262. function hsv2hwb(args) {
  263. return rgb2hwb(hsv2rgb(args))
  264. }
  265. function hsv2cmyk(args) {
  266. return rgb2cmyk(hsv2rgb(args));
  267. }
  268. function hsv2keyword(args) {
  269. return rgb2keyword(hsv2rgb(args));
  270. }
  271. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  272. function hwb2rgb(hwb) {
  273. var h = hwb[0] / 360,
  274. wh = hwb[1] / 100,
  275. bl = hwb[2] / 100,
  276. ratio = wh + bl,
  277. i, v, f, n;
  278. // wh + bl cant be > 1
  279. if (ratio > 1) {
  280. wh /= ratio;
  281. bl /= ratio;
  282. }
  283. i = Math.floor(6 * h);
  284. v = 1 - bl;
  285. f = 6 * h - i;
  286. if ((i & 0x01) != 0) {
  287. f = 1 - f;
  288. }
  289. n = wh + f * (v - wh); // linear interpolation
  290. switch (i) {
  291. default:
  292. case 6:
  293. case 0: r = v; g = n; b = wh; break;
  294. case 1: r = n; g = v; b = wh; break;
  295. case 2: r = wh; g = v; b = n; break;
  296. case 3: r = wh; g = n; b = v; break;
  297. case 4: r = n; g = wh; b = v; break;
  298. case 5: r = v; g = wh; b = n; break;
  299. }
  300. return [r * 255, g * 255, b * 255];
  301. }
  302. function hwb2hsl(args) {
  303. return rgb2hsl(hwb2rgb(args));
  304. }
  305. function hwb2hsv(args) {
  306. return rgb2hsv(hwb2rgb(args));
  307. }
  308. function hwb2cmyk(args) {
  309. return rgb2cmyk(hwb2rgb(args));
  310. }
  311. function hwb2keyword(args) {
  312. return rgb2keyword(hwb2rgb(args));
  313. }
  314. function cmyk2rgb(cmyk) {
  315. var c = cmyk[0] / 100,
  316. m = cmyk[1] / 100,
  317. y = cmyk[2] / 100,
  318. k = cmyk[3] / 100,
  319. r, g, b;
  320. r = 1 - Math.min(1, c * (1 - k) + k);
  321. g = 1 - Math.min(1, m * (1 - k) + k);
  322. b = 1 - Math.min(1, y * (1 - k) + k);
  323. return [r * 255, g * 255, b * 255];
  324. }
  325. function cmyk2hsl(args) {
  326. return rgb2hsl(cmyk2rgb(args));
  327. }
  328. function cmyk2hsv(args) {
  329. return rgb2hsv(cmyk2rgb(args));
  330. }
  331. function cmyk2hwb(args) {
  332. return rgb2hwb(cmyk2rgb(args));
  333. }
  334. function cmyk2keyword(args) {
  335. return rgb2keyword(cmyk2rgb(args));
  336. }
  337. function xyz2rgb(xyz) {
  338. var x = xyz[0] / 100,
  339. y = xyz[1] / 100,
  340. z = xyz[2] / 100,
  341. r, g, b;
  342. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  343. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  344. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  345. // assume sRGB
  346. r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  347. : r = (r * 12.92);
  348. g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  349. : g = (g * 12.92);
  350. b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  351. : b = (b * 12.92);
  352. r = Math.min(Math.max(0, r), 1);
  353. g = Math.min(Math.max(0, g), 1);
  354. b = Math.min(Math.max(0, b), 1);
  355. return [r * 255, g * 255, b * 255];
  356. }
  357. function xyz2lab(xyz) {
  358. var x = xyz[0],
  359. y = xyz[1],
  360. z = xyz[2],
  361. l, a, b;
  362. x /= 95.047;
  363. y /= 100;
  364. z /= 108.883;
  365. x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
  366. y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
  367. z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
  368. l = (116 * y) - 16;
  369. a = 500 * (x - y);
  370. b = 200 * (y - z);
  371. return [l, a, b];
  372. }
  373. function xyz2lch(args) {
  374. return lab2lch(xyz2lab(args));
  375. }
  376. function lab2xyz(lab) {
  377. var l = lab[0],
  378. a = lab[1],
  379. b = lab[2],
  380. x, y, z, y2;
  381. if (l <= 8) {
  382. y = (l * 100) / 903.3;
  383. y2 = (7.787 * (y / 100)) + (16 / 116);
  384. } else {
  385. y = 100 * Math.pow((l + 16) / 116, 3);
  386. y2 = Math.pow(y / 100, 1/3);
  387. }
  388. x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
  389. z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
  390. return [x, y, z];
  391. }
  392. function lab2lch(lab) {
  393. var l = lab[0],
  394. a = lab[1],
  395. b = lab[2],
  396. hr, h, c;
  397. hr = Math.atan2(b, a);
  398. h = hr * 360 / 2 / Math.PI;
  399. if (h < 0) {
  400. h += 360;
  401. }
  402. c = Math.sqrt(a * a + b * b);
  403. return [l, c, h];
  404. }
  405. function lab2rgb(args) {
  406. return xyz2rgb(lab2xyz(args));
  407. }
  408. function lch2lab(lch) {
  409. var l = lch[0],
  410. c = lch[1],
  411. h = lch[2],
  412. a, b, hr;
  413. hr = h / 360 * 2 * Math.PI;
  414. a = c * Math.cos(hr);
  415. b = c * Math.sin(hr);
  416. return [l, a, b];
  417. }
  418. function lch2xyz(args) {
  419. return lab2xyz(lch2lab(args));
  420. }
  421. function lch2rgb(args) {
  422. return lab2rgb(lch2lab(args));
  423. }
  424. function keyword2rgb(keyword) {
  425. return cssKeywords[keyword];
  426. }
  427. function keyword2hsl(args) {
  428. return rgb2hsl(keyword2rgb(args));
  429. }
  430. function keyword2hsv(args) {
  431. return rgb2hsv(keyword2rgb(args));
  432. }
  433. function keyword2hwb(args) {
  434. return rgb2hwb(keyword2rgb(args));
  435. }
  436. function keyword2cmyk(args) {
  437. return rgb2cmyk(keyword2rgb(args));
  438. }
  439. function keyword2lab(args) {
  440. return rgb2lab(keyword2rgb(args));
  441. }
  442. function keyword2xyz(args) {
  443. return rgb2xyz(keyword2rgb(args));
  444. }
  445. var cssKeywords = {
  446. aliceblue: [240,248,255],
  447. antiquewhite: [250,235,215],
  448. aqua: [0,255,255],
  449. aquamarine: [127,255,212],
  450. azure: [240,255,255],
  451. beige: [245,245,220],
  452. bisque: [255,228,196],
  453. black: [0,0,0],
  454. blanchedalmond: [255,235,205],
  455. blue: [0,0,255],
  456. blueviolet: [138,43,226],
  457. brown: [165,42,42],
  458. burlywood: [222,184,135],
  459. cadetblue: [95,158,160],
  460. chartreuse: [127,255,0],
  461. chocolate: [210,105,30],
  462. coral: [255,127,80],
  463. cornflowerblue: [100,149,237],
  464. cornsilk: [255,248,220],
  465. crimson: [220,20,60],
  466. cyan: [0,255,255],
  467. darkblue: [0,0,139],
  468. darkcyan: [0,139,139],
  469. darkgoldenrod: [184,134,11],
  470. darkgray: [169,169,169],
  471. darkgreen: [0,100,0],
  472. darkgrey: [169,169,169],
  473. darkkhaki: [189,183,107],
  474. darkmagenta: [139,0,139],
  475. darkolivegreen: [85,107,47],
  476. darkorange: [255,140,0],
  477. darkorchid: [153,50,204],
  478. darkred: [139,0,0],
  479. darksalmon: [233,150,122],
  480. darkseagreen: [143,188,143],
  481. darkslateblue: [72,61,139],
  482. darkslategray: [47,79,79],
  483. darkslategrey: [47,79,79],
  484. darkturquoise: [0,206,209],
  485. darkviolet: [148,0,211],
  486. deeppink: [255,20,147],
  487. deepskyblue: [0,191,255],
  488. dimgray: [105,105,105],
  489. dimgrey: [105,105,105],
  490. dodgerblue: [30,144,255],
  491. firebrick: [178,34,34],
  492. floralwhite: [255,250,240],
  493. forestgreen: [34,139,34],
  494. fuchsia: [255,0,255],
  495. gainsboro: [220,220,220],
  496. ghostwhite: [248,248,255],
  497. gold: [255,215,0],
  498. goldenrod: [218,165,32],
  499. gray: [128,128,128],
  500. green: [0,128,0],
  501. greenyellow: [173,255,47],
  502. grey: [128,128,128],
  503. honeydew: [240,255,240],
  504. hotpink: [255,105,180],
  505. indianred: [205,92,92],
  506. indigo: [75,0,130],
  507. ivory: [255,255,240],
  508. khaki: [240,230,140],
  509. lavender: [230,230,250],
  510. lavenderblush: [255,240,245],
  511. lawngreen: [124,252,0],
  512. lemonchiffon: [255,250,205],
  513. lightblue: [173,216,230],
  514. lightcoral: [240,128,128],
  515. lightcyan: [224,255,255],
  516. lightgoldenrodyellow: [250,250,210],
  517. lightgray: [211,211,211],
  518. lightgreen: [144,238,144],
  519. lightgrey: [211,211,211],
  520. lightpink: [255,182,193],
  521. lightsalmon: [255,160,122],
  522. lightseagreen: [32,178,170],
  523. lightskyblue: [135,206,250],
  524. lightslategray: [119,136,153],
  525. lightslategrey: [119,136,153],
  526. lightsteelblue: [176,196,222],
  527. lightyellow: [255,255,224],
  528. lime: [0,255,0],
  529. limegreen: [50,205,50],
  530. linen: [250,240,230],
  531. magenta: [255,0,255],
  532. maroon: [128,0,0],
  533. mediumaquamarine: [102,205,170],
  534. mediumblue: [0,0,205],
  535. mediumorchid: [186,85,211],
  536. mediumpurple: [147,112,219],
  537. mediumseagreen: [60,179,113],
  538. mediumslateblue: [123,104,238],
  539. mediumspringgreen: [0,250,154],
  540. mediumturquoise: [72,209,204],
  541. mediumvioletred: [199,21,133],
  542. midnightblue: [25,25,112],
  543. mintcream: [245,255,250],
  544. mistyrose: [255,228,225],
  545. moccasin: [255,228,181],
  546. navajowhite: [255,222,173],
  547. navy: [0,0,128],
  548. oldlace: [253,245,230],
  549. olive: [128,128,0],
  550. olivedrab: [107,142,35],
  551. orange: [255,165,0],
  552. orangered: [255,69,0],
  553. orchid: [218,112,214],
  554. palegoldenrod: [238,232,170],
  555. palegreen: [152,251,152],
  556. paleturquoise: [175,238,238],
  557. palevioletred: [219,112,147],
  558. papayawhip: [255,239,213],
  559. peachpuff: [255,218,185],
  560. peru: [205,133,63],
  561. pink: [255,192,203],
  562. plum: [221,160,221],
  563. powderblue: [176,224,230],
  564. purple: [128,0,128],
  565. rebeccapurple: [102, 51, 153],
  566. red: [255,0,0],
  567. rosybrown: [188,143,143],
  568. royalblue: [65,105,225],
  569. saddlebrown: [139,69,19],
  570. salmon: [250,128,114],
  571. sandybrown: [244,164,96],
  572. seagreen: [46,139,87],
  573. seashell: [255,245,238],
  574. sienna: [160,82,45],
  575. silver: [192,192,192],
  576. skyblue: [135,206,235],
  577. slateblue: [106,90,205],
  578. slategray: [112,128,144],
  579. slategrey: [112,128,144],
  580. snow: [255,250,250],
  581. springgreen: [0,255,127],
  582. steelblue: [70,130,180],
  583. tan: [210,180,140],
  584. teal: [0,128,128],
  585. thistle: [216,191,216],
  586. tomato: [255,99,71],
  587. turquoise: [64,224,208],
  588. violet: [238,130,238],
  589. wheat: [245,222,179],
  590. white: [255,255,255],
  591. whitesmoke: [245,245,245],
  592. yellow: [255,255,0],
  593. yellowgreen: [154,205,50]
  594. };
  595. var reverseKeywords = {};
  596. for (var key in cssKeywords) {
  597. reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
  598. }
  599. var convert = function() {
  600. return new Converter();
  601. };
  602. for (var func in conversions) {
  603. // export Raw versions
  604. convert[func + "Raw"] = (function(func) {
  605. // accept array or plain args
  606. return function(arg) {
  607. if (typeof arg == "number")
  608. arg = Array.prototype.slice.call(arguments);
  609. return conversions[func](arg);
  610. }
  611. })(func);
  612. var pair = /(\w+)2(\w+)/.exec(func),
  613. from = pair[1],
  614. to = pair[2];
  615. // export rgb2hsl and ["rgb"]["hsl"]
  616. convert[from] = convert[from] || {};
  617. convert[from][to] = convert[func] = (function(func) {
  618. return function(arg) {
  619. if (typeof arg == "number")
  620. arg = Array.prototype.slice.call(arguments);
  621. var val = conversions[func](arg);
  622. if (typeof val == "string" || val === undefined)
  623. return val; // keyword
  624. for (var i = 0; i < val.length; i++)
  625. val[i] = Math.round(val[i]);
  626. return val;
  627. }
  628. })(func);
  629. }
  630. /* Converter does lazy conversion and caching */
  631. var Converter = function() {
  632. this.convs = {};
  633. };
  634. /* Either get the values for a space or
  635. set the values for a space, depending on args */
  636. Converter.prototype.routeSpace = function(space, args) {
  637. var values = args[0];
  638. if (values === undefined) {
  639. // color.rgb()
  640. return this.getValues(space);
  641. }
  642. // color.rgb(10, 10, 10)
  643. if (typeof values == "number") {
  644. values = Array.prototype.slice.call(args);
  645. }
  646. return this.setValues(space, values);
  647. };
  648. /* Set the values for a space, invalidating cache */
  649. Converter.prototype.setValues = function(space, values) {
  650. this.space = space;
  651. this.convs = {};
  652. this.convs[space] = values;
  653. return this;
  654. };
  655. /* Get the values for a space. If there's already
  656. a conversion for the space, fetch it, otherwise
  657. compute it */
  658. Converter.prototype.getValues = function(space) {
  659. var vals = this.convs[space];
  660. if (!vals) {
  661. var fspace = this.space,
  662. from = this.convs[fspace];
  663. vals = convert[fspace][space](from);
  664. this.convs[space] = vals;
  665. }
  666. return vals;
  667. };
  668. ["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
  669. Converter.prototype[space] = function(vals) {
  670. return this.routeSpace(space, arguments);
  671. };
  672. });
  673. var colorConvert = convert;
  674. var colorName = {
  675. "aliceblue": [240, 248, 255],
  676. "antiquewhite": [250, 235, 215],
  677. "aqua": [0, 255, 255],
  678. "aquamarine": [127, 255, 212],
  679. "azure": [240, 255, 255],
  680. "beige": [245, 245, 220],
  681. "bisque": [255, 228, 196],
  682. "black": [0, 0, 0],
  683. "blanchedalmond": [255, 235, 205],
  684. "blue": [0, 0, 255],
  685. "blueviolet": [138, 43, 226],
  686. "brown": [165, 42, 42],
  687. "burlywood": [222, 184, 135],
  688. "cadetblue": [95, 158, 160],
  689. "chartreuse": [127, 255, 0],
  690. "chocolate": [210, 105, 30],
  691. "coral": [255, 127, 80],
  692. "cornflowerblue": [100, 149, 237],
  693. "cornsilk": [255, 248, 220],
  694. "crimson": [220, 20, 60],
  695. "cyan": [0, 255, 255],
  696. "darkblue": [0, 0, 139],
  697. "darkcyan": [0, 139, 139],
  698. "darkgoldenrod": [184, 134, 11],
  699. "darkgray": [169, 169, 169],
  700. "darkgreen": [0, 100, 0],
  701. "darkgrey": [169, 169, 169],
  702. "darkkhaki": [189, 183, 107],
  703. "darkmagenta": [139, 0, 139],
  704. "darkolivegreen": [85, 107, 47],
  705. "darkorange": [255, 140, 0],
  706. "darkorchid": [153, 50, 204],
  707. "darkred": [139, 0, 0],
  708. "darksalmon": [233, 150, 122],
  709. "darkseagreen": [143, 188, 143],
  710. "darkslateblue": [72, 61, 139],
  711. "darkslategray": [47, 79, 79],
  712. "darkslategrey": [47, 79, 79],
  713. "darkturquoise": [0, 206, 209],
  714. "darkviolet": [148, 0, 211],
  715. "deeppink": [255, 20, 147],
  716. "deepskyblue": [0, 191, 255],
  717. "dimgray": [105, 105, 105],
  718. "dimgrey": [105, 105, 105],
  719. "dodgerblue": [30, 144, 255],
  720. "firebrick": [178, 34, 34],
  721. "floralwhite": [255, 250, 240],
  722. "forestgreen": [34, 139, 34],
  723. "fuchsia": [255, 0, 255],
  724. "gainsboro": [220, 220, 220],
  725. "ghostwhite": [248, 248, 255],
  726. "gold": [255, 215, 0],
  727. "goldenrod": [218, 165, 32],
  728. "gray": [128, 128, 128],
  729. "green": [0, 128, 0],
  730. "greenyellow": [173, 255, 47],
  731. "grey": [128, 128, 128],
  732. "honeydew": [240, 255, 240],
  733. "hotpink": [255, 105, 180],
  734. "indianred": [205, 92, 92],
  735. "indigo": [75, 0, 130],
  736. "ivory": [255, 255, 240],
  737. "khaki": [240, 230, 140],
  738. "lavender": [230, 230, 250],
  739. "lavenderblush": [255, 240, 245],
  740. "lawngreen": [124, 252, 0],
  741. "lemonchiffon": [255, 250, 205],
  742. "lightblue": [173, 216, 230],
  743. "lightcoral": [240, 128, 128],
  744. "lightcyan": [224, 255, 255],
  745. "lightgoldenrodyellow": [250, 250, 210],
  746. "lightgray": [211, 211, 211],
  747. "lightgreen": [144, 238, 144],
  748. "lightgrey": [211, 211, 211],
  749. "lightpink": [255, 182, 193],
  750. "lightsalmon": [255, 160, 122],
  751. "lightseagreen": [32, 178, 170],
  752. "lightskyblue": [135, 206, 250],
  753. "lightslategray": [119, 136, 153],
  754. "lightslategrey": [119, 136, 153],
  755. "lightsteelblue": [176, 196, 222],
  756. "lightyellow": [255, 255, 224],
  757. "lime": [0, 255, 0],
  758. "limegreen": [50, 205, 50],
  759. "linen": [250, 240, 230],
  760. "magenta": [255, 0, 255],
  761. "maroon": [128, 0, 0],
  762. "mediumaquamarine": [102, 205, 170],
  763. "mediumblue": [0, 0, 205],
  764. "mediumorchid": [186, 85, 211],
  765. "mediumpurple": [147, 112, 219],
  766. "mediumseagreen": [60, 179, 113],
  767. "mediumslateblue": [123, 104, 238],
  768. "mediumspringgreen": [0, 250, 154],
  769. "mediumturquoise": [72, 209, 204],
  770. "mediumvioletred": [199, 21, 133],
  771. "midnightblue": [25, 25, 112],
  772. "mintcream": [245, 255, 250],
  773. "mistyrose": [255, 228, 225],
  774. "moccasin": [255, 228, 181],
  775. "navajowhite": [255, 222, 173],
  776. "navy": [0, 0, 128],
  777. "oldlace": [253, 245, 230],
  778. "olive": [128, 128, 0],
  779. "olivedrab": [107, 142, 35],
  780. "orange": [255, 165, 0],
  781. "orangered": [255, 69, 0],
  782. "orchid": [218, 112, 214],
  783. "palegoldenrod": [238, 232, 170],
  784. "palegreen": [152, 251, 152],
  785. "paleturquoise": [175, 238, 238],
  786. "palevioletred": [219, 112, 147],
  787. "papayawhip": [255, 239, 213],
  788. "peachpuff": [255, 218, 185],
  789. "peru": [205, 133, 63],
  790. "pink": [255, 192, 203],
  791. "plum": [221, 160, 221],
  792. "powderblue": [176, 224, 230],
  793. "purple": [128, 0, 128],
  794. "rebeccapurple": [102, 51, 153],
  795. "red": [255, 0, 0],
  796. "rosybrown": [188, 143, 143],
  797. "royalblue": [65, 105, 225],
  798. "saddlebrown": [139, 69, 19],
  799. "salmon": [250, 128, 114],
  800. "sandybrown": [244, 164, 96],
  801. "seagreen": [46, 139, 87],
  802. "seashell": [255, 245, 238],
  803. "sienna": [160, 82, 45],
  804. "silver": [192, 192, 192],
  805. "skyblue": [135, 206, 235],
  806. "slateblue": [106, 90, 205],
  807. "slategray": [112, 128, 144],
  808. "slategrey": [112, 128, 144],
  809. "snow": [255, 250, 250],
  810. "springgreen": [0, 255, 127],
  811. "steelblue": [70, 130, 180],
  812. "tan": [210, 180, 140],
  813. "teal": [0, 128, 128],
  814. "thistle": [216, 191, 216],
  815. "tomato": [255, 99, 71],
  816. "turquoise": [64, 224, 208],
  817. "violet": [238, 130, 238],
  818. "wheat": [245, 222, 179],
  819. "white": [255, 255, 255],
  820. "whitesmoke": [245, 245, 245],
  821. "yellow": [255, 255, 0],
  822. "yellowgreen": [154, 205, 50]
  823. };
  824. /* MIT license */
  825. var colorString = {
  826. getRgba: getRgba,
  827. getHsla: getHsla,
  828. getRgb: getRgb,
  829. getHsl: getHsl,
  830. getHwb: getHwb,
  831. getAlpha: getAlpha,
  832. hexString: hexString,
  833. rgbString: rgbString,
  834. rgbaString: rgbaString,
  835. percentString: percentString,
  836. percentaString: percentaString,
  837. hslString: hslString,
  838. hslaString: hslaString,
  839. hwbString: hwbString,
  840. keyword: keyword
  841. };
  842. function getRgba(string) {
  843. if (!string) {
  844. return;
  845. }
  846. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  847. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  848. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  849. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  850. keyword = /(\w+)/;
  851. var rgb = [0, 0, 0],
  852. a = 1,
  853. match = string.match(abbr),
  854. hexAlpha = "";
  855. if (match) {
  856. match = match[1];
  857. hexAlpha = match[3];
  858. for (var i = 0; i < rgb.length; i++) {
  859. rgb[i] = parseInt(match[i] + match[i], 16);
  860. }
  861. if (hexAlpha) {
  862. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  863. }
  864. }
  865. else if (match = string.match(hex)) {
  866. hexAlpha = match[2];
  867. match = match[1];
  868. for (var i = 0; i < rgb.length; i++) {
  869. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  870. }
  871. if (hexAlpha) {
  872. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  873. }
  874. }
  875. else if (match = string.match(rgba)) {
  876. for (var i = 0; i < rgb.length; i++) {
  877. rgb[i] = parseInt(match[i + 1]);
  878. }
  879. a = parseFloat(match[4]);
  880. }
  881. else if (match = string.match(per)) {
  882. for (var i = 0; i < rgb.length; i++) {
  883. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  884. }
  885. a = parseFloat(match[4]);
  886. }
  887. else if (match = string.match(keyword)) {
  888. if (match[1] == "transparent") {
  889. return [0, 0, 0, 0];
  890. }
  891. rgb = colorName[match[1]];
  892. if (!rgb) {
  893. return;
  894. }
  895. }
  896. for (var i = 0; i < rgb.length; i++) {
  897. rgb[i] = scale(rgb[i], 0, 255);
  898. }
  899. if (!a && a != 0) {
  900. a = 1;
  901. }
  902. else {
  903. a = scale(a, 0, 1);
  904. }
  905. rgb[3] = a;
  906. return rgb;
  907. }
  908. function getHsla(string) {
  909. if (!string) {
  910. return;
  911. }
  912. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  913. var match = string.match(hsl);
  914. if (match) {
  915. var alpha = parseFloat(match[4]);
  916. var h = scale(parseInt(match[1]), 0, 360),
  917. s = scale(parseFloat(match[2]), 0, 100),
  918. l = scale(parseFloat(match[3]), 0, 100),
  919. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  920. return [h, s, l, a];
  921. }
  922. }
  923. function getHwb(string) {
  924. if (!string) {
  925. return;
  926. }
  927. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  928. var match = string.match(hwb);
  929. if (match) {
  930. var alpha = parseFloat(match[4]);
  931. var h = scale(parseInt(match[1]), 0, 360),
  932. w = scale(parseFloat(match[2]), 0, 100),
  933. b = scale(parseFloat(match[3]), 0, 100),
  934. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  935. return [h, w, b, a];
  936. }
  937. }
  938. function getRgb(string) {
  939. var rgba = getRgba(string);
  940. return rgba && rgba.slice(0, 3);
  941. }
  942. function getHsl(string) {
  943. var hsla = getHsla(string);
  944. return hsla && hsla.slice(0, 3);
  945. }
  946. function getAlpha(string) {
  947. var vals = getRgba(string);
  948. if (vals) {
  949. return vals[3];
  950. }
  951. else if (vals = getHsla(string)) {
  952. return vals[3];
  953. }
  954. else if (vals = getHwb(string)) {
  955. return vals[3];
  956. }
  957. }
  958. // generators
  959. function hexString(rgba, a) {
  960. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  961. return "#" + hexDouble(rgba[0])
  962. + hexDouble(rgba[1])
  963. + hexDouble(rgba[2])
  964. + (
  965. (a >= 0 && a < 1)
  966. ? hexDouble(Math.round(a * 255))
  967. : ""
  968. );
  969. }
  970. function rgbString(rgba, alpha) {
  971. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  972. return rgbaString(rgba, alpha);
  973. }
  974. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  975. }
  976. function rgbaString(rgba, alpha) {
  977. if (alpha === undefined) {
  978. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  979. }
  980. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  981. + ", " + alpha + ")";
  982. }
  983. function percentString(rgba, alpha) {
  984. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  985. return percentaString(rgba, alpha);
  986. }
  987. var r = Math.round(rgba[0]/255 * 100),
  988. g = Math.round(rgba[1]/255 * 100),
  989. b = Math.round(rgba[2]/255 * 100);
  990. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  991. }
  992. function percentaString(rgba, alpha) {
  993. var r = Math.round(rgba[0]/255 * 100),
  994. g = Math.round(rgba[1]/255 * 100),
  995. b = Math.round(rgba[2]/255 * 100);
  996. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  997. }
  998. function hslString(hsla, alpha) {
  999. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1000. return hslaString(hsla, alpha);
  1001. }
  1002. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1003. }
  1004. function hslaString(hsla, alpha) {
  1005. if (alpha === undefined) {
  1006. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1007. }
  1008. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1009. + alpha + ")";
  1010. }
  1011. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1012. // (hwb have alpha optional & 1 is default value)
  1013. function hwbString(hwb, alpha) {
  1014. if (alpha === undefined) {
  1015. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1016. }
  1017. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1018. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1019. }
  1020. function keyword(rgb) {
  1021. return reverseNames[rgb.slice(0, 3)];
  1022. }
  1023. // helpers
  1024. function scale(num, min, max) {
  1025. return Math.min(Math.max(min, num), max);
  1026. }
  1027. function hexDouble(num) {
  1028. var str = num.toString(16).toUpperCase();
  1029. return (str.length < 2) ? "0" + str : str;
  1030. }
  1031. //create a list of reverse color names
  1032. var reverseNames = {};
  1033. for (var name in colorName) {
  1034. reverseNames[colorName[name]] = name;
  1035. }
  1036. /* MIT license */
  1037. var Color = function (obj) {
  1038. if (obj instanceof Color) {
  1039. return obj;
  1040. }
  1041. if (!(this instanceof Color)) {
  1042. return new Color(obj);
  1043. }
  1044. this.valid = false;
  1045. this.values = {
  1046. rgb: [0, 0, 0],
  1047. hsl: [0, 0, 0],
  1048. hsv: [0, 0, 0],
  1049. hwb: [0, 0, 0],
  1050. cmyk: [0, 0, 0, 0],
  1051. alpha: 1
  1052. };
  1053. // parse Color() argument
  1054. var vals;
  1055. if (typeof obj === 'string') {
  1056. vals = colorString.getRgba(obj);
  1057. if (vals) {
  1058. this.setValues('rgb', vals);
  1059. } else if (vals = colorString.getHsla(obj)) {
  1060. this.setValues('hsl', vals);
  1061. } else if (vals = colorString.getHwb(obj)) {
  1062. this.setValues('hwb', vals);
  1063. }
  1064. } else if (typeof obj === 'object') {
  1065. vals = obj;
  1066. if (vals.r !== undefined || vals.red !== undefined) {
  1067. this.setValues('rgb', vals);
  1068. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1069. this.setValues('hsl', vals);
  1070. } else if (vals.v !== undefined || vals.value !== undefined) {
  1071. this.setValues('hsv', vals);
  1072. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1073. this.setValues('hwb', vals);
  1074. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1075. this.setValues('cmyk', vals);
  1076. }
  1077. }
  1078. };
  1079. Color.prototype = {
  1080. isValid: function () {
  1081. return this.valid;
  1082. },
  1083. rgb: function () {
  1084. return this.setSpace('rgb', arguments);
  1085. },
  1086. hsl: function () {
  1087. return this.setSpace('hsl', arguments);
  1088. },
  1089. hsv: function () {
  1090. return this.setSpace('hsv', arguments);
  1091. },
  1092. hwb: function () {
  1093. return this.setSpace('hwb', arguments);
  1094. },
  1095. cmyk: function () {
  1096. return this.setSpace('cmyk', arguments);
  1097. },
  1098. rgbArray: function () {
  1099. return this.values.rgb;
  1100. },
  1101. hslArray: function () {
  1102. return this.values.hsl;
  1103. },
  1104. hsvArray: function () {
  1105. return this.values.hsv;
  1106. },
  1107. hwbArray: function () {
  1108. var values = this.values;
  1109. if (values.alpha !== 1) {
  1110. return values.hwb.concat([values.alpha]);
  1111. }
  1112. return values.hwb;
  1113. },
  1114. cmykArray: function () {
  1115. return this.values.cmyk;
  1116. },
  1117. rgbaArray: function () {
  1118. var values = this.values;
  1119. return values.rgb.concat([values.alpha]);
  1120. },
  1121. hslaArray: function () {
  1122. var values = this.values;
  1123. return values.hsl.concat([values.alpha]);
  1124. },
  1125. alpha: function (val) {
  1126. if (val === undefined) {
  1127. return this.values.alpha;
  1128. }
  1129. this.setValues('alpha', val);
  1130. return this;
  1131. },
  1132. red: function (val) {
  1133. return this.setChannel('rgb', 0, val);
  1134. },
  1135. green: function (val) {
  1136. return this.setChannel('rgb', 1, val);
  1137. },
  1138. blue: function (val) {
  1139. return this.setChannel('rgb', 2, val);
  1140. },
  1141. hue: function (val) {
  1142. if (val) {
  1143. val %= 360;
  1144. val = val < 0 ? 360 + val : val;
  1145. }
  1146. return this.setChannel('hsl', 0, val);
  1147. },
  1148. saturation: function (val) {
  1149. return this.setChannel('hsl', 1, val);
  1150. },
  1151. lightness: function (val) {
  1152. return this.setChannel('hsl', 2, val);
  1153. },
  1154. saturationv: function (val) {
  1155. return this.setChannel('hsv', 1, val);
  1156. },
  1157. whiteness: function (val) {
  1158. return this.setChannel('hwb', 1, val);
  1159. },
  1160. blackness: function (val) {
  1161. return this.setChannel('hwb', 2, val);
  1162. },
  1163. value: function (val) {
  1164. return this.setChannel('hsv', 2, val);
  1165. },
  1166. cyan: function (val) {
  1167. return this.setChannel('cmyk', 0, val);
  1168. },
  1169. magenta: function (val) {
  1170. return this.setChannel('cmyk', 1, val);
  1171. },
  1172. yellow: function (val) {
  1173. return this.setChannel('cmyk', 2, val);
  1174. },
  1175. black: function (val) {
  1176. return this.setChannel('cmyk', 3, val);
  1177. },
  1178. hexString: function () {
  1179. return colorString.hexString(this.values.rgb);
  1180. },
  1181. rgbString: function () {
  1182. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1183. },
  1184. rgbaString: function () {
  1185. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1186. },
  1187. percentString: function () {
  1188. return colorString.percentString(this.values.rgb, this.values.alpha);
  1189. },
  1190. hslString: function () {
  1191. return colorString.hslString(this.values.hsl, this.values.alpha);
  1192. },
  1193. hslaString: function () {
  1194. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1195. },
  1196. hwbString: function () {
  1197. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1198. },
  1199. keyword: function () {
  1200. return colorString.keyword(this.values.rgb, this.values.alpha);
  1201. },
  1202. rgbNumber: function () {
  1203. var rgb = this.values.rgb;
  1204. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1205. },
  1206. luminosity: function () {
  1207. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1208. var rgb = this.values.rgb;
  1209. var lum = [];
  1210. for (var i = 0; i < rgb.length; i++) {
  1211. var chan = rgb[i] / 255;
  1212. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1213. }
  1214. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1215. },
  1216. contrast: function (color2) {
  1217. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1218. var lum1 = this.luminosity();
  1219. var lum2 = color2.luminosity();
  1220. if (lum1 > lum2) {
  1221. return (lum1 + 0.05) / (lum2 + 0.05);
  1222. }
  1223. return (lum2 + 0.05) / (lum1 + 0.05);
  1224. },
  1225. level: function (color2) {
  1226. var contrastRatio = this.contrast(color2);
  1227. if (contrastRatio >= 7.1) {
  1228. return 'AAA';
  1229. }
  1230. return (contrastRatio >= 4.5) ? 'AA' : '';
  1231. },
  1232. dark: function () {
  1233. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1234. var rgb = this.values.rgb;
  1235. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1236. return yiq < 128;
  1237. },
  1238. light: function () {
  1239. return !this.dark();
  1240. },
  1241. negate: function () {
  1242. var rgb = [];
  1243. for (var i = 0; i < 3; i++) {
  1244. rgb[i] = 255 - this.values.rgb[i];
  1245. }
  1246. this.setValues('rgb', rgb);
  1247. return this;
  1248. },
  1249. lighten: function (ratio) {
  1250. var hsl = this.values.hsl;
  1251. hsl[2] += hsl[2] * ratio;
  1252. this.setValues('hsl', hsl);
  1253. return this;
  1254. },
  1255. darken: function (ratio) {
  1256. var hsl = this.values.hsl;
  1257. hsl[2] -= hsl[2] * ratio;
  1258. this.setValues('hsl', hsl);
  1259. return this;
  1260. },
  1261. saturate: function (ratio) {
  1262. var hsl = this.values.hsl;
  1263. hsl[1] += hsl[1] * ratio;
  1264. this.setValues('hsl', hsl);
  1265. return this;
  1266. },
  1267. desaturate: function (ratio) {
  1268. var hsl = this.values.hsl;
  1269. hsl[1] -= hsl[1] * ratio;
  1270. this.setValues('hsl', hsl);
  1271. return this;
  1272. },
  1273. whiten: function (ratio) {
  1274. var hwb = this.values.hwb;
  1275. hwb[1] += hwb[1] * ratio;
  1276. this.setValues('hwb', hwb);
  1277. return this;
  1278. },
  1279. blacken: function (ratio) {
  1280. var hwb = this.values.hwb;
  1281. hwb[2] += hwb[2] * ratio;
  1282. this.setValues('hwb', hwb);
  1283. return this;
  1284. },
  1285. greyscale: function () {
  1286. var rgb = this.values.rgb;
  1287. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1288. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1289. this.setValues('rgb', [val, val, val]);
  1290. return this;
  1291. },
  1292. clearer: function (ratio) {
  1293. var alpha = this.values.alpha;
  1294. this.setValues('alpha', alpha - (alpha * ratio));
  1295. return this;
  1296. },
  1297. opaquer: function (ratio) {
  1298. var alpha = this.values.alpha;
  1299. this.setValues('alpha', alpha + (alpha * ratio));
  1300. return this;
  1301. },
  1302. rotate: function (degrees) {
  1303. var hsl = this.values.hsl;
  1304. var hue = (hsl[0] + degrees) % 360;
  1305. hsl[0] = hue < 0 ? 360 + hue : hue;
  1306. this.setValues('hsl', hsl);
  1307. return this;
  1308. },
  1309. /**
  1310. * Ported from sass implementation in C
  1311. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1312. */
  1313. mix: function (mixinColor, weight) {
  1314. var color1 = this;
  1315. var color2 = mixinColor;
  1316. var p = weight === undefined ? 0.5 : weight;
  1317. var w = 2 * p - 1;
  1318. var a = color1.alpha() - color2.alpha();
  1319. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1320. var w2 = 1 - w1;
  1321. return this
  1322. .rgb(
  1323. w1 * color1.red() + w2 * color2.red(),
  1324. w1 * color1.green() + w2 * color2.green(),
  1325. w1 * color1.blue() + w2 * color2.blue()
  1326. )
  1327. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1328. },
  1329. toJSON: function () {
  1330. return this.rgb();
  1331. },
  1332. clone: function () {
  1333. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1334. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1335. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1336. // except 'alpha' which is a number.
  1337. var result = new Color();
  1338. var source = this.values;
  1339. var target = result.values;
  1340. var value, type;
  1341. for (var prop in source) {
  1342. if (source.hasOwnProperty(prop)) {
  1343. value = source[prop];
  1344. type = ({}).toString.call(value);
  1345. if (type === '[object Array]') {
  1346. target[prop] = value.slice(0);
  1347. } else if (type === '[object Number]') {
  1348. target[prop] = value;
  1349. } else {
  1350. console.error('unexpected color value:', value);
  1351. }
  1352. }
  1353. }
  1354. return result;
  1355. }
  1356. };
  1357. Color.prototype.spaces = {
  1358. rgb: ['red', 'green', 'blue'],
  1359. hsl: ['hue', 'saturation', 'lightness'],
  1360. hsv: ['hue', 'saturation', 'value'],
  1361. hwb: ['hue', 'whiteness', 'blackness'],
  1362. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1363. };
  1364. Color.prototype.maxes = {
  1365. rgb: [255, 255, 255],
  1366. hsl: [360, 100, 100],
  1367. hsv: [360, 100, 100],
  1368. hwb: [360, 100, 100],
  1369. cmyk: [100, 100, 100, 100]
  1370. };
  1371. Color.prototype.getValues = function (space) {
  1372. var values = this.values;
  1373. var vals = {};
  1374. for (var i = 0; i < space.length; i++) {
  1375. vals[space.charAt(i)] = values[space][i];
  1376. }
  1377. if (values.alpha !== 1) {
  1378. vals.a = values.alpha;
  1379. }
  1380. // {r: 255, g: 255, b: 255, a: 0.4}
  1381. return vals;
  1382. };
  1383. Color.prototype.setValues = function (space, vals) {
  1384. var values = this.values;
  1385. var spaces = this.spaces;
  1386. var maxes = this.maxes;
  1387. var alpha = 1;
  1388. var i;
  1389. this.valid = true;
  1390. if (space === 'alpha') {
  1391. alpha = vals;
  1392. } else if (vals.length) {
  1393. // [10, 10, 10]
  1394. values[space] = vals.slice(0, space.length);
  1395. alpha = vals[space.length];
  1396. } else if (vals[space.charAt(0)] !== undefined) {
  1397. // {r: 10, g: 10, b: 10}
  1398. for (i = 0; i < space.length; i++) {
  1399. values[space][i] = vals[space.charAt(i)];
  1400. }
  1401. alpha = vals.a;
  1402. } else if (vals[spaces[space][0]] !== undefined) {
  1403. // {red: 10, green: 10, blue: 10}
  1404. var chans = spaces[space];
  1405. for (i = 0; i < space.length; i++) {
  1406. values[space][i] = vals[chans[i]];
  1407. }
  1408. alpha = vals.alpha;
  1409. }
  1410. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1411. if (space === 'alpha') {
  1412. return false;
  1413. }
  1414. var capped;
  1415. // cap values of the space prior converting all values
  1416. for (i = 0; i < space.length; i++) {
  1417. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1418. values[space][i] = Math.round(capped);
  1419. }
  1420. // convert to all the other color spaces
  1421. for (var sname in spaces) {
  1422. if (sname !== space) {
  1423. values[sname] = colorConvert[space][sname](values[space]);
  1424. }
  1425. }
  1426. return true;
  1427. };
  1428. Color.prototype.setSpace = function (space, args) {
  1429. var vals = args[0];
  1430. if (vals === undefined) {
  1431. // color.rgb()
  1432. return this.getValues(space);
  1433. }
  1434. // color.rgb(10, 10, 10)
  1435. if (typeof vals === 'number') {
  1436. vals = Array.prototype.slice.call(args);
  1437. }
  1438. this.setValues(space, vals);
  1439. return this;
  1440. };
  1441. Color.prototype.setChannel = function (space, index, val) {
  1442. var svalues = this.values[space];
  1443. if (val === undefined) {
  1444. // color.red()
  1445. return svalues[index];
  1446. } else if (val === svalues[index]) {
  1447. // color.red(color.red())
  1448. return this;
  1449. }
  1450. // color.red(100)
  1451. svalues[index] = val;
  1452. this.setValues(space, svalues);
  1453. return this;
  1454. };
  1455. if (typeof window !== 'undefined') {
  1456. window.Color = Color;
  1457. }
  1458. var chartjsColor = Color;
  1459. /**
  1460. * @namespace Chart.helpers
  1461. */
  1462. var helpers = {
  1463. /**
  1464. * An empty function that can be used, for example, for optional callback.
  1465. */
  1466. noop: function() {},
  1467. /**
  1468. * Returns a unique id, sequentially generated from a global variable.
  1469. * @returns {number}
  1470. * @function
  1471. */
  1472. uid: (function() {
  1473. var id = 0;
  1474. return function() {
  1475. return id++;
  1476. };
  1477. }()),
  1478. /**
  1479. * Returns true if `value` is neither null nor undefined, else returns false.
  1480. * @param {*} value - The value to test.
  1481. * @returns {boolean}
  1482. * @since 2.7.0
  1483. */
  1484. isNullOrUndef: function(value) {
  1485. return value === null || typeof value === 'undefined';
  1486. },
  1487. /**
  1488. * Returns true if `value` is an array (including typed arrays), else returns false.
  1489. * @param {*} value - The value to test.
  1490. * @returns {boolean}
  1491. * @function
  1492. */
  1493. isArray: function(value) {
  1494. if (Array.isArray && Array.isArray(value)) {
  1495. return true;
  1496. }
  1497. var type = Object.prototype.toString.call(value);
  1498. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1499. return true;
  1500. }
  1501. return false;
  1502. },
  1503. /**
  1504. * Returns true if `value` is an object (excluding null), else returns false.
  1505. * @param {*} value - The value to test.
  1506. * @returns {boolean}
  1507. * @since 2.7.0
  1508. */
  1509. isObject: function(value) {
  1510. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1511. },
  1512. /**
  1513. * Returns true if `value` is a finite number, else returns false
  1514. * @param {*} value - The value to test.
  1515. * @returns {boolean}
  1516. */
  1517. isFinite: function(value) {
  1518. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1519. },
  1520. /**
  1521. * Returns `value` if defined, else returns `defaultValue`.
  1522. * @param {*} value - The value to return if defined.
  1523. * @param {*} defaultValue - The value to return if `value` is undefined.
  1524. * @returns {*}
  1525. */
  1526. valueOrDefault: function(value, defaultValue) {
  1527. return typeof value === 'undefined' ? defaultValue : value;
  1528. },
  1529. /**
  1530. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1531. * @param {Array} value - The array to lookup for value at `index`.
  1532. * @param {number} index - The index in `value` to lookup for value.
  1533. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1534. * @returns {*}
  1535. */
  1536. valueAtIndexOrDefault: function(value, index, defaultValue) {
  1537. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1538. },
  1539. /**
  1540. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1541. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1542. * @param {function} fn - The function to call.
  1543. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1544. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1545. * @returns {*}
  1546. */
  1547. callback: function(fn, args, thisArg) {
  1548. if (fn && typeof fn.call === 'function') {
  1549. return fn.apply(thisArg, args);
  1550. }
  1551. },
  1552. /**
  1553. * Note(SB) for performance sake, this method should only be used when loopable type
  1554. * is unknown or in none intensive code (not called often and small loopable). Else
  1555. * it's preferable to use a regular for() loop and save extra function calls.
  1556. * @param {object|Array} loopable - The object or array to be iterated.
  1557. * @param {function} fn - The function to call for each item.
  1558. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1559. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1560. */
  1561. each: function(loopable, fn, thisArg, reverse) {
  1562. var i, len, keys;
  1563. if (helpers.isArray(loopable)) {
  1564. len = loopable.length;
  1565. if (reverse) {
  1566. for (i = len - 1; i >= 0; i--) {
  1567. fn.call(thisArg, loopable[i], i);
  1568. }
  1569. } else {
  1570. for (i = 0; i < len; i++) {
  1571. fn.call(thisArg, loopable[i], i);
  1572. }
  1573. }
  1574. } else if (helpers.isObject(loopable)) {
  1575. keys = Object.keys(loopable);
  1576. len = keys.length;
  1577. for (i = 0; i < len; i++) {
  1578. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1579. }
  1580. }
  1581. },
  1582. /**
  1583. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1584. * @see https://stackoverflow.com/a/14853974
  1585. * @param {Array} a0 - The array to compare
  1586. * @param {Array} a1 - The array to compare
  1587. * @returns {boolean}
  1588. */
  1589. arrayEquals: function(a0, a1) {
  1590. var i, ilen, v0, v1;
  1591. if (!a0 || !a1 || a0.length !== a1.length) {
  1592. return false;
  1593. }
  1594. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1595. v0 = a0[i];
  1596. v1 = a1[i];
  1597. if (v0 instanceof Array && v1 instanceof Array) {
  1598. if (!helpers.arrayEquals(v0, v1)) {
  1599. return false;
  1600. }
  1601. } else if (v0 !== v1) {
  1602. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1603. return false;
  1604. }
  1605. }
  1606. return true;
  1607. },
  1608. /**
  1609. * Returns a deep copy of `source` without keeping references on objects and arrays.
  1610. * @param {*} source - The value to clone.
  1611. * @returns {*}
  1612. */
  1613. clone: function(source) {
  1614. if (helpers.isArray(source)) {
  1615. return source.map(helpers.clone);
  1616. }
  1617. if (helpers.isObject(source)) {
  1618. var target = {};
  1619. var keys = Object.keys(source);
  1620. var klen = keys.length;
  1621. var k = 0;
  1622. for (; k < klen; ++k) {
  1623. target[keys[k]] = helpers.clone(source[keys[k]]);
  1624. }
  1625. return target;
  1626. }
  1627. return source;
  1628. },
  1629. /**
  1630. * The default merger when Chart.helpers.merge is called without merger option.
  1631. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  1632. * @private
  1633. */
  1634. _merger: function(key, target, source, options) {
  1635. var tval = target[key];
  1636. var sval = source[key];
  1637. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1638. helpers.merge(tval, sval, options);
  1639. } else {
  1640. target[key] = helpers.clone(sval);
  1641. }
  1642. },
  1643. /**
  1644. * Merges source[key] in target[key] only if target[key] is undefined.
  1645. * @private
  1646. */
  1647. _mergerIf: function(key, target, source) {
  1648. var tval = target[key];
  1649. var sval = source[key];
  1650. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1651. helpers.mergeIf(tval, sval);
  1652. } else if (!target.hasOwnProperty(key)) {
  1653. target[key] = helpers.clone(sval);
  1654. }
  1655. },
  1656. /**
  1657. * Recursively deep copies `source` properties into `target` with the given `options`.
  1658. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  1659. * @param {object} target - The target object in which all sources are merged into.
  1660. * @param {object|object[]} source - Object(s) to merge into `target`.
  1661. * @param {object} [options] - Merging options:
  1662. * @param {function} [options.merger] - The merge method (key, target, source, options)
  1663. * @returns {object} The `target` object.
  1664. */
  1665. merge: function(target, source, options) {
  1666. var sources = helpers.isArray(source) ? source : [source];
  1667. var ilen = sources.length;
  1668. var merge, i, keys, klen, k;
  1669. if (!helpers.isObject(target)) {
  1670. return target;
  1671. }
  1672. options = options || {};
  1673. merge = options.merger || helpers._merger;
  1674. for (i = 0; i < ilen; ++i) {
  1675. source = sources[i];
  1676. if (!helpers.isObject(source)) {
  1677. continue;
  1678. }
  1679. keys = Object.keys(source);
  1680. for (k = 0, klen = keys.length; k < klen; ++k) {
  1681. merge(keys[k], target, source, options);
  1682. }
  1683. }
  1684. return target;
  1685. },
  1686. /**
  1687. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  1688. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  1689. * @param {object} target - The target object in which all sources are merged into.
  1690. * @param {object|object[]} source - Object(s) to merge into `target`.
  1691. * @returns {object} The `target` object.
  1692. */
  1693. mergeIf: function(target, source) {
  1694. return helpers.merge(target, source, {merger: helpers._mergerIf});
  1695. },
  1696. /**
  1697. * Applies the contents of two or more objects together into the first object.
  1698. * @param {object} target - The target object in which all objects are merged into.
  1699. * @param {object} arg1 - Object containing additional properties to merge in target.
  1700. * @param {object} argN - Additional objects containing properties to merge in target.
  1701. * @returns {object} The `target` object.
  1702. */
  1703. extend: function(target) {
  1704. var setFn = function(value, key) {
  1705. target[key] = value;
  1706. };
  1707. for (var i = 1, ilen = arguments.length; i < ilen; ++i) {
  1708. helpers.each(arguments[i], setFn);
  1709. }
  1710. return target;
  1711. },
  1712. /**
  1713. * Basic javascript inheritance based on the model created in Backbone.js
  1714. */
  1715. inherits: function(extensions) {
  1716. var me = this;
  1717. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  1718. return me.apply(this, arguments);
  1719. };
  1720. var Surrogate = function() {
  1721. this.constructor = ChartElement;
  1722. };
  1723. Surrogate.prototype = me.prototype;
  1724. ChartElement.prototype = new Surrogate();
  1725. ChartElement.extend = helpers.inherits;
  1726. if (extensions) {
  1727. helpers.extend(ChartElement.prototype, extensions);
  1728. }
  1729. ChartElement.__super__ = me.prototype;
  1730. return ChartElement;
  1731. }
  1732. };
  1733. var helpers_core = helpers;
  1734. // DEPRECATIONS
  1735. /**
  1736. * Provided for backward compatibility, use Chart.helpers.callback instead.
  1737. * @function Chart.helpers.callCallback
  1738. * @deprecated since version 2.6.0
  1739. * @todo remove at version 3
  1740. * @private
  1741. */
  1742. helpers.callCallback = helpers.callback;
  1743. /**
  1744. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  1745. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  1746. * @function Chart.helpers.indexOf
  1747. * @deprecated since version 2.7.0
  1748. * @todo remove at version 3
  1749. * @private
  1750. */
  1751. helpers.indexOf = function(array, item, fromIndex) {
  1752. return Array.prototype.indexOf.call(array, item, fromIndex);
  1753. };
  1754. /**
  1755. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  1756. * @function Chart.helpers.getValueOrDefault
  1757. * @deprecated since version 2.7.0
  1758. * @todo remove at version 3
  1759. * @private
  1760. */
  1761. helpers.getValueOrDefault = helpers.valueOrDefault;
  1762. /**
  1763. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  1764. * @function Chart.helpers.getValueAtIndexOrDefault
  1765. * @deprecated since version 2.7.0
  1766. * @todo remove at version 3
  1767. * @private
  1768. */
  1769. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  1770. /**
  1771. * Easing functions adapted from Robert Penner's easing equations.
  1772. * @namespace Chart.helpers.easingEffects
  1773. * @see http://www.robertpenner.com/easing/
  1774. */
  1775. var effects = {
  1776. linear: function(t) {
  1777. return t;
  1778. },
  1779. easeInQuad: function(t) {
  1780. return t * t;
  1781. },
  1782. easeOutQuad: function(t) {
  1783. return -t * (t - 2);
  1784. },
  1785. easeInOutQuad: function(t) {
  1786. if ((t /= 0.5) < 1) {
  1787. return 0.5 * t * t;
  1788. }
  1789. return -0.5 * ((--t) * (t - 2) - 1);
  1790. },
  1791. easeInCubic: function(t) {
  1792. return t * t * t;
  1793. },
  1794. easeOutCubic: function(t) {
  1795. return (t = t - 1) * t * t + 1;
  1796. },
  1797. easeInOutCubic: function(t) {
  1798. if ((t /= 0.5) < 1) {
  1799. return 0.5 * t * t * t;
  1800. }
  1801. return 0.5 * ((t -= 2) * t * t + 2);
  1802. },
  1803. easeInQuart: function(t) {
  1804. return t * t * t * t;
  1805. },
  1806. easeOutQuart: function(t) {
  1807. return -((t = t - 1) * t * t * t - 1);
  1808. },
  1809. easeInOutQuart: function(t) {
  1810. if ((t /= 0.5) < 1) {
  1811. return 0.5 * t * t * t * t;
  1812. }
  1813. return -0.5 * ((t -= 2) * t * t * t - 2);
  1814. },
  1815. easeInQuint: function(t) {
  1816. return t * t * t * t * t;
  1817. },
  1818. easeOutQuint: function(t) {
  1819. return (t = t - 1) * t * t * t * t + 1;
  1820. },
  1821. easeInOutQuint: function(t) {
  1822. if ((t /= 0.5) < 1) {
  1823. return 0.5 * t * t * t * t * t;
  1824. }
  1825. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  1826. },
  1827. easeInSine: function(t) {
  1828. return -Math.cos(t * (Math.PI / 2)) + 1;
  1829. },
  1830. easeOutSine: function(t) {
  1831. return Math.sin(t * (Math.PI / 2));
  1832. },
  1833. easeInOutSine: function(t) {
  1834. return -0.5 * (Math.cos(Math.PI * t) - 1);
  1835. },
  1836. easeInExpo: function(t) {
  1837. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  1838. },
  1839. easeOutExpo: function(t) {
  1840. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  1841. },
  1842. easeInOutExpo: function(t) {
  1843. if (t === 0) {
  1844. return 0;
  1845. }
  1846. if (t === 1) {
  1847. return 1;
  1848. }
  1849. if ((t /= 0.5) < 1) {
  1850. return 0.5 * Math.pow(2, 10 * (t - 1));
  1851. }
  1852. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  1853. },
  1854. easeInCirc: function(t) {
  1855. if (t >= 1) {
  1856. return t;
  1857. }
  1858. return -(Math.sqrt(1 - t * t) - 1);
  1859. },
  1860. easeOutCirc: function(t) {
  1861. return Math.sqrt(1 - (t = t - 1) * t);
  1862. },
  1863. easeInOutCirc: function(t) {
  1864. if ((t /= 0.5) < 1) {
  1865. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  1866. }
  1867. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  1868. },
  1869. easeInElastic: function(t) {
  1870. var s = 1.70158;
  1871. var p = 0;
  1872. var a = 1;
  1873. if (t === 0) {
  1874. return 0;
  1875. }
  1876. if (t === 1) {
  1877. return 1;
  1878. }
  1879. if (!p) {
  1880. p = 0.3;
  1881. }
  1882. if (a < 1) {
  1883. a = 1;
  1884. s = p / 4;
  1885. } else {
  1886. s = p / (2 * Math.PI) * Math.asin(1 / a);
  1887. }
  1888. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  1889. },
  1890. easeOutElastic: function(t) {
  1891. var s = 1.70158;
  1892. var p = 0;
  1893. var a = 1;
  1894. if (t === 0) {
  1895. return 0;
  1896. }
  1897. if (t === 1) {
  1898. return 1;
  1899. }
  1900. if (!p) {
  1901. p = 0.3;
  1902. }
  1903. if (a < 1) {
  1904. a = 1;
  1905. s = p / 4;
  1906. } else {
  1907. s = p / (2 * Math.PI) * Math.asin(1 / a);
  1908. }
  1909. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  1910. },
  1911. easeInOutElastic: function(t) {
  1912. var s = 1.70158;
  1913. var p = 0;
  1914. var a = 1;
  1915. if (t === 0) {
  1916. return 0;
  1917. }
  1918. if ((t /= 0.5) === 2) {
  1919. return 1;
  1920. }
  1921. if (!p) {
  1922. p = 0.45;
  1923. }
  1924. if (a < 1) {
  1925. a = 1;
  1926. s = p / 4;
  1927. } else {
  1928. s = p / (2 * Math.PI) * Math.asin(1 / a);
  1929. }
  1930. if (t < 1) {
  1931. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  1932. }
  1933. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  1934. },
  1935. easeInBack: function(t) {
  1936. var s = 1.70158;
  1937. return t * t * ((s + 1) * t - s);
  1938. },
  1939. easeOutBack: function(t) {
  1940. var s = 1.70158;
  1941. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  1942. },
  1943. easeInOutBack: function(t) {
  1944. var s = 1.70158;
  1945. if ((t /= 0.5) < 1) {
  1946. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  1947. }
  1948. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  1949. },
  1950. easeInBounce: function(t) {
  1951. return 1 - effects.easeOutBounce(1 - t);
  1952. },
  1953. easeOutBounce: function(t) {
  1954. if (t < (1 / 2.75)) {
  1955. return 7.5625 * t * t;
  1956. }
  1957. if (t < (2 / 2.75)) {
  1958. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  1959. }
  1960. if (t < (2.5 / 2.75)) {
  1961. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  1962. }
  1963. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  1964. },
  1965. easeInOutBounce: function(t) {
  1966. if (t < 0.5) {
  1967. return effects.easeInBounce(t * 2) * 0.5;
  1968. }
  1969. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  1970. }
  1971. };
  1972. var helpers_easing = {
  1973. effects: effects
  1974. };
  1975. // DEPRECATIONS
  1976. /**
  1977. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  1978. * @function Chart.helpers.easingEffects
  1979. * @deprecated since version 2.7.0
  1980. * @todo remove at version 3
  1981. * @private
  1982. */
  1983. helpers_core.easingEffects = effects;
  1984. var PI = Math.PI;
  1985. var RAD_PER_DEG = PI / 180;
  1986. var DOUBLE_PI = PI * 2;
  1987. var HALF_PI = PI / 2;
  1988. var QUARTER_PI = PI / 4;
  1989. var TWO_THIRDS_PI = PI * 2 / 3;
  1990. /**
  1991. * @namespace Chart.helpers.canvas
  1992. */
  1993. var exports$1 = {
  1994. /**
  1995. * Clears the entire canvas associated to the given `chart`.
  1996. * @param {Chart} chart - The chart for which to clear the canvas.
  1997. */
  1998. clear: function(chart) {
  1999. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2000. },
  2001. /**
  2002. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2003. * given size (width, height) and the same `radius` for all corners.
  2004. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2005. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2006. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2007. * @param {number} width - The rectangle's width.
  2008. * @param {number} height - The rectangle's height.
  2009. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2010. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2011. */
  2012. roundedRect: function(ctx, x, y, width, height, radius) {
  2013. if (radius) {
  2014. var r = Math.min(radius, height / 2, width / 2);
  2015. var left = x + r;
  2016. var top = y + r;
  2017. var right = x + width - r;
  2018. var bottom = y + height - r;
  2019. ctx.moveTo(x, top);
  2020. if (left < right && top < bottom) {
  2021. ctx.arc(left, top, r, -PI, -HALF_PI);
  2022. ctx.arc(right, top, r, -HALF_PI, 0);
  2023. ctx.arc(right, bottom, r, 0, HALF_PI);
  2024. ctx.arc(left, bottom, r, HALF_PI, PI);
  2025. } else if (left < right) {
  2026. ctx.moveTo(left, y);
  2027. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2028. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2029. } else if (top < bottom) {
  2030. ctx.arc(left, top, r, -PI, 0);
  2031. ctx.arc(left, bottom, r, 0, PI);
  2032. } else {
  2033. ctx.arc(left, top, r, -PI, PI);
  2034. }
  2035. ctx.closePath();
  2036. ctx.moveTo(x, y);
  2037. } else {
  2038. ctx.rect(x, y, width, height);
  2039. }
  2040. },
  2041. drawPoint: function(ctx, style, radius, x, y, rotation) {
  2042. var type, xOffset, yOffset, size, cornerRadius;
  2043. var rad = (rotation || 0) * RAD_PER_DEG;
  2044. if (style && typeof style === 'object') {
  2045. type = style.toString();
  2046. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2047. ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height);
  2048. return;
  2049. }
  2050. }
  2051. if (isNaN(radius) || radius <= 0) {
  2052. return;
  2053. }
  2054. ctx.beginPath();
  2055. switch (style) {
  2056. // Default includes circle
  2057. default:
  2058. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2059. ctx.closePath();
  2060. break;
  2061. case 'triangle':
  2062. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2063. rad += TWO_THIRDS_PI;
  2064. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2065. rad += TWO_THIRDS_PI;
  2066. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2067. ctx.closePath();
  2068. break;
  2069. case 'rectRounded':
  2070. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2071. // `quadraticCurveTo` since it generates better results when rect is
  2072. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2073. // closer proportion to the previous impl and it is inscribed in the
  2074. // circle with `radius`. For more details, see the following PRs:
  2075. // https://github.com/chartjs/Chart.js/issues/5597
  2076. // https://github.com/chartjs/Chart.js/issues/5858
  2077. cornerRadius = radius * 0.516;
  2078. size = radius - cornerRadius;
  2079. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2080. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2081. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2082. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2083. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2084. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2085. ctx.closePath();
  2086. break;
  2087. case 'rect':
  2088. if (!rotation) {
  2089. size = Math.SQRT1_2 * radius;
  2090. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2091. break;
  2092. }
  2093. rad += QUARTER_PI;
  2094. /* falls through */
  2095. case 'rectRot':
  2096. xOffset = Math.cos(rad) * radius;
  2097. yOffset = Math.sin(rad) * radius;
  2098. ctx.moveTo(x - xOffset, y - yOffset);
  2099. ctx.lineTo(x + yOffset, y - xOffset);
  2100. ctx.lineTo(x + xOffset, y + yOffset);
  2101. ctx.lineTo(x - yOffset, y + xOffset);
  2102. ctx.closePath();
  2103. break;
  2104. case 'crossRot':
  2105. rad += QUARTER_PI;
  2106. /* falls through */
  2107. case 'cross':
  2108. xOffset = Math.cos(rad) * radius;
  2109. yOffset = Math.sin(rad) * radius;
  2110. ctx.moveTo(x - xOffset, y - yOffset);
  2111. ctx.lineTo(x + xOffset, y + yOffset);
  2112. ctx.moveTo(x + yOffset, y - xOffset);
  2113. ctx.lineTo(x - yOffset, y + xOffset);
  2114. break;
  2115. case 'star':
  2116. xOffset = Math.cos(rad) * radius;
  2117. yOffset = Math.sin(rad) * radius;
  2118. ctx.moveTo(x - xOffset, y - yOffset);
  2119. ctx.lineTo(x + xOffset, y + yOffset);
  2120. ctx.moveTo(x + yOffset, y - xOffset);
  2121. ctx.lineTo(x - yOffset, y + xOffset);
  2122. rad += QUARTER_PI;
  2123. xOffset = Math.cos(rad) * radius;
  2124. yOffset = Math.sin(rad) * radius;
  2125. ctx.moveTo(x - xOffset, y - yOffset);
  2126. ctx.lineTo(x + xOffset, y + yOffset);
  2127. ctx.moveTo(x + yOffset, y - xOffset);
  2128. ctx.lineTo(x - yOffset, y + xOffset);
  2129. break;
  2130. case 'line':
  2131. xOffset = Math.cos(rad) * radius;
  2132. yOffset = Math.sin(rad) * radius;
  2133. ctx.moveTo(x - xOffset, y - yOffset);
  2134. ctx.lineTo(x + xOffset, y + yOffset);
  2135. break;
  2136. case 'dash':
  2137. ctx.moveTo(x, y);
  2138. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2139. break;
  2140. }
  2141. ctx.fill();
  2142. ctx.stroke();
  2143. },
  2144. /**
  2145. * Returns true if the point is inside the rectangle
  2146. * @param {object} point - The point to test
  2147. * @param {object} area - The rectangle
  2148. * @returns {boolean}
  2149. * @private
  2150. */
  2151. _isPointInArea: function(point, area) {
  2152. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2153. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2154. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2155. },
  2156. clipArea: function(ctx, area) {
  2157. ctx.save();
  2158. ctx.beginPath();
  2159. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2160. ctx.clip();
  2161. },
  2162. unclipArea: function(ctx) {
  2163. ctx.restore();
  2164. },
  2165. lineTo: function(ctx, previous, target, flip) {
  2166. var stepped = target.steppedLine;
  2167. if (stepped) {
  2168. if (stepped === 'middle') {
  2169. var midpoint = (previous.x + target.x) / 2.0;
  2170. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2171. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2172. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2173. ctx.lineTo(previous.x, target.y);
  2174. } else {
  2175. ctx.lineTo(target.x, previous.y);
  2176. }
  2177. ctx.lineTo(target.x, target.y);
  2178. return;
  2179. }
  2180. if (!target.tension) {
  2181. ctx.lineTo(target.x, target.y);
  2182. return;
  2183. }
  2184. ctx.bezierCurveTo(
  2185. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2186. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2187. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2188. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2189. target.x,
  2190. target.y);
  2191. }
  2192. };
  2193. var helpers_canvas = exports$1;
  2194. // DEPRECATIONS
  2195. /**
  2196. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2197. * @namespace Chart.helpers.clear
  2198. * @deprecated since version 2.7.0
  2199. * @todo remove at version 3
  2200. * @private
  2201. */
  2202. helpers_core.clear = exports$1.clear;
  2203. /**
  2204. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2205. * @namespace Chart.helpers.drawRoundedRectangle
  2206. * @deprecated since version 2.7.0
  2207. * @todo remove at version 3
  2208. * @private
  2209. */
  2210. helpers_core.drawRoundedRectangle = function(ctx) {
  2211. ctx.beginPath();
  2212. exports$1.roundedRect.apply(exports$1, arguments);
  2213. };
  2214. var defaults = {
  2215. /**
  2216. * @private
  2217. */
  2218. _set: function(scope, values) {
  2219. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2220. }
  2221. };
  2222. defaults._set('global', {
  2223. defaultColor: 'rgba(0,0,0,0.1)',
  2224. defaultFontColor: '#666',
  2225. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2226. defaultFontSize: 12,
  2227. defaultFontStyle: 'normal',
  2228. defaultLineHeight: 1.2,
  2229. showLines: true
  2230. });
  2231. var core_defaults = defaults;
  2232. var valueOrDefault = helpers_core.valueOrDefault;
  2233. /**
  2234. * Converts the given font object into a CSS font string.
  2235. * @param {object} font - A font object.
  2236. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2237. * @private
  2238. */
  2239. function toFontString(font) {
  2240. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2241. return null;
  2242. }
  2243. return (font.style ? font.style + ' ' : '')
  2244. + (font.weight ? font.weight + ' ' : '')
  2245. + font.size + 'px '
  2246. + font.family;
  2247. }
  2248. /**
  2249. * @alias Chart.helpers.options
  2250. * @namespace
  2251. */
  2252. var helpers_options = {
  2253. /**
  2254. * Converts the given line height `value` in pixels for a specific font `size`.
  2255. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2256. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2257. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2258. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2259. * @since 2.7.0
  2260. */
  2261. toLineHeight: function(value, size) {
  2262. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2263. if (!matches || matches[1] === 'normal') {
  2264. return size * 1.2;
  2265. }
  2266. value = +matches[2];
  2267. switch (matches[3]) {
  2268. case 'px':
  2269. return value;
  2270. case '%':
  2271. value /= 100;
  2272. break;
  2273. default:
  2274. break;
  2275. }
  2276. return size * value;
  2277. },
  2278. /**
  2279. * Converts the given value into a padding object with pre-computed width/height.
  2280. * @param {number|object} value - If a number, set the value to all TRBL component,
  2281. * else, if and object, use defined properties and sets undefined ones to 0.
  2282. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2283. * @since 2.7.0
  2284. */
  2285. toPadding: function(value) {
  2286. var t, r, b, l;
  2287. if (helpers_core.isObject(value)) {
  2288. t = +value.top || 0;
  2289. r = +value.right || 0;
  2290. b = +value.bottom || 0;
  2291. l = +value.left || 0;
  2292. } else {
  2293. t = r = b = l = +value || 0;
  2294. }
  2295. return {
  2296. top: t,
  2297. right: r,
  2298. bottom: b,
  2299. left: l,
  2300. height: t + b,
  2301. width: l + r
  2302. };
  2303. },
  2304. /**
  2305. * Parses font options and returns the font object.
  2306. * @param {object} options - A object that contains font options to be parsed.
  2307. * @return {object} The font object.
  2308. * @todo Support font.* options and renamed to toFont().
  2309. * @private
  2310. */
  2311. _parseFont: function(options) {
  2312. var globalDefaults = core_defaults.global;
  2313. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2314. var font = {
  2315. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2316. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2317. size: size,
  2318. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2319. weight: null,
  2320. string: ''
  2321. };
  2322. font.string = toFontString(font);
  2323. return font;
  2324. },
  2325. /**
  2326. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2327. * @param {Array} inputs - An array of values, falling back to the last value.
  2328. * @param {object} [context] - If defined and the current value is a function, the value
  2329. * is called with `context` as first argument and the result becomes the new input.
  2330. * @param {number} [index] - If defined and the current value is an array, the value
  2331. * at `index` become the new input.
  2332. * @since 2.7.0
  2333. */
  2334. resolve: function(inputs, context, index) {
  2335. var i, ilen, value;
  2336. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2337. value = inputs[i];
  2338. if (value === undefined) {
  2339. continue;
  2340. }
  2341. if (context !== undefined && typeof value === 'function') {
  2342. value = value(context);
  2343. }
  2344. if (index !== undefined && helpers_core.isArray(value)) {
  2345. value = value[index];
  2346. }
  2347. if (value !== undefined) {
  2348. return value;
  2349. }
  2350. }
  2351. }
  2352. };
  2353. var helpers$1 = helpers_core;
  2354. var easing = helpers_easing;
  2355. var canvas = helpers_canvas;
  2356. var options = helpers_options;
  2357. helpers$1.easing = easing;
  2358. helpers$1.canvas = canvas;
  2359. helpers$1.options = options;
  2360. function interpolate(start, view, model, ease) {
  2361. var keys = Object.keys(model);
  2362. var i, ilen, key, actual, origin, target, type, c0, c1;
  2363. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2364. key = keys[i];
  2365. target = model[key];
  2366. // if a value is added to the model after pivot() has been called, the view
  2367. // doesn't contain it, so let's initialize the view to the target value.
  2368. if (!view.hasOwnProperty(key)) {
  2369. view[key] = target;
  2370. }
  2371. actual = view[key];
  2372. if (actual === target || key[0] === '_') {
  2373. continue;
  2374. }
  2375. if (!start.hasOwnProperty(key)) {
  2376. start[key] = actual;
  2377. }
  2378. origin = start[key];
  2379. type = typeof target;
  2380. if (type === typeof origin) {
  2381. if (type === 'string') {
  2382. c0 = chartjsColor(origin);
  2383. if (c0.valid) {
  2384. c1 = chartjsColor(target);
  2385. if (c1.valid) {
  2386. view[key] = c1.mix(c0, ease).rgbString();
  2387. continue;
  2388. }
  2389. }
  2390. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2391. view[key] = origin + (target - origin) * ease;
  2392. continue;
  2393. }
  2394. }
  2395. view[key] = target;
  2396. }
  2397. }
  2398. var Element = function(configuration) {
  2399. helpers$1.extend(this, configuration);
  2400. this.initialize.apply(this, arguments);
  2401. };
  2402. helpers$1.extend(Element.prototype, {
  2403. initialize: function() {
  2404. this.hidden = false;
  2405. },
  2406. pivot: function() {
  2407. var me = this;
  2408. if (!me._view) {
  2409. me._view = helpers$1.clone(me._model);
  2410. }
  2411. me._start = {};
  2412. return me;
  2413. },
  2414. transition: function(ease) {
  2415. var me = this;
  2416. var model = me._model;
  2417. var start = me._start;
  2418. var view = me._view;
  2419. // No animation -> No Transition
  2420. if (!model || ease === 1) {
  2421. me._view = model;
  2422. me._start = null;
  2423. return me;
  2424. }
  2425. if (!view) {
  2426. view = me._view = {};
  2427. }
  2428. if (!start) {
  2429. start = me._start = {};
  2430. }
  2431. interpolate(start, view, model, ease);
  2432. return me;
  2433. },
  2434. tooltipPosition: function() {
  2435. return {
  2436. x: this._model.x,
  2437. y: this._model.y
  2438. };
  2439. },
  2440. hasValue: function() {
  2441. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2442. }
  2443. });
  2444. Element.extend = helpers$1.inherits;
  2445. var core_element = Element;
  2446. var exports$2 = core_element.extend({
  2447. chart: null, // the animation associated chart instance
  2448. currentStep: 0, // the current animation step
  2449. numSteps: 60, // default number of steps
  2450. easing: '', // the easing to use for this animation
  2451. render: null, // render function used by the animation service
  2452. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2453. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2454. });
  2455. var core_animation = exports$2;
  2456. // DEPRECATIONS
  2457. /**
  2458. * Provided for backward compatibility, use Chart.Animation instead
  2459. * @prop Chart.Animation#animationObject
  2460. * @deprecated since version 2.6.0
  2461. * @todo remove at version 3
  2462. */
  2463. Object.defineProperty(exports$2.prototype, 'animationObject', {
  2464. get: function() {
  2465. return this;
  2466. }
  2467. });
  2468. /**
  2469. * Provided for backward compatibility, use Chart.Animation#chart instead
  2470. * @prop Chart.Animation#chartInstance
  2471. * @deprecated since version 2.6.0
  2472. * @todo remove at version 3
  2473. */
  2474. Object.defineProperty(exports$2.prototype, 'chartInstance', {
  2475. get: function() {
  2476. return this.chart;
  2477. },
  2478. set: function(value) {
  2479. this.chart = value;
  2480. }
  2481. });
  2482. core_defaults._set('global', {
  2483. animation: {
  2484. duration: 1000,
  2485. easing: 'easeOutQuart',
  2486. onProgress: helpers$1.noop,
  2487. onComplete: helpers$1.noop
  2488. }
  2489. });
  2490. var core_animations = {
  2491. animations: [],
  2492. request: null,
  2493. /**
  2494. * @param {Chart} chart - The chart to animate.
  2495. * @param {Chart.Animation} animation - The animation that we will animate.
  2496. * @param {number} duration - The animation duration in ms.
  2497. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  2498. */
  2499. addAnimation: function(chart, animation, duration, lazy) {
  2500. var animations = this.animations;
  2501. var i, ilen;
  2502. animation.chart = chart;
  2503. animation.startTime = Date.now();
  2504. animation.duration = duration;
  2505. if (!lazy) {
  2506. chart.animating = true;
  2507. }
  2508. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  2509. if (animations[i].chart === chart) {
  2510. animations[i] = animation;
  2511. return;
  2512. }
  2513. }
  2514. animations.push(animation);
  2515. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  2516. if (animations.length === 1) {
  2517. this.requestAnimationFrame();
  2518. }
  2519. },
  2520. cancelAnimation: function(chart) {
  2521. var index = helpers$1.findIndex(this.animations, function(animation) {
  2522. return animation.chart === chart;
  2523. });
  2524. if (index !== -1) {
  2525. this.animations.splice(index, 1);
  2526. chart.animating = false;
  2527. }
  2528. },
  2529. requestAnimationFrame: function() {
  2530. var me = this;
  2531. if (me.request === null) {
  2532. // Skip animation frame requests until the active one is executed.
  2533. // This can happen when processing mouse events, e.g. 'mousemove'
  2534. // and 'mouseout' events will trigger multiple renders.
  2535. me.request = helpers$1.requestAnimFrame.call(window, function() {
  2536. me.request = null;
  2537. me.startDigest();
  2538. });
  2539. }
  2540. },
  2541. /**
  2542. * @private
  2543. */
  2544. startDigest: function() {
  2545. var me = this;
  2546. me.advance();
  2547. // Do we have more stuff to animate?
  2548. if (me.animations.length > 0) {
  2549. me.requestAnimationFrame();
  2550. }
  2551. },
  2552. /**
  2553. * @private
  2554. */
  2555. advance: function() {
  2556. var animations = this.animations;
  2557. var animation, chart, numSteps, nextStep;
  2558. var i = 0;
  2559. // 1 animation per chart, so we are looping charts here
  2560. while (i < animations.length) {
  2561. animation = animations[i];
  2562. chart = animation.chart;
  2563. numSteps = animation.numSteps;
  2564. // Make sure that currentStep starts at 1
  2565. // https://github.com/chartjs/Chart.js/issues/6104
  2566. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  2567. animation.currentStep = Math.min(nextStep, numSteps);
  2568. helpers$1.callback(animation.render, [chart, animation], chart);
  2569. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  2570. if (animation.currentStep >= numSteps) {
  2571. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  2572. chart.animating = false;
  2573. animations.splice(i, 1);
  2574. } else {
  2575. ++i;
  2576. }
  2577. }
  2578. }
  2579. };
  2580. var resolve = helpers$1.options.resolve;
  2581. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  2582. /**
  2583. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  2584. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  2585. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  2586. */
  2587. function listenArrayEvents(array, listener) {
  2588. if (array._chartjs) {
  2589. array._chartjs.listeners.push(listener);
  2590. return;
  2591. }
  2592. Object.defineProperty(array, '_chartjs', {
  2593. configurable: true,
  2594. enumerable: false,
  2595. value: {
  2596. listeners: [listener]
  2597. }
  2598. });
  2599. arrayEvents.forEach(function(key) {
  2600. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  2601. var base = array[key];
  2602. Object.defineProperty(array, key, {
  2603. configurable: true,
  2604. enumerable: false,
  2605. value: function() {
  2606. var args = Array.prototype.slice.call(arguments);
  2607. var res = base.apply(this, args);
  2608. helpers$1.each(array._chartjs.listeners, function(object) {
  2609. if (typeof object[method] === 'function') {
  2610. object[method].apply(object, args);
  2611. }
  2612. });
  2613. return res;
  2614. }
  2615. });
  2616. });
  2617. }
  2618. /**
  2619. * Removes the given array event listener and cleanup extra attached properties (such as
  2620. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  2621. */
  2622. function unlistenArrayEvents(array, listener) {
  2623. var stub = array._chartjs;
  2624. if (!stub) {
  2625. return;
  2626. }
  2627. var listeners = stub.listeners;
  2628. var index = listeners.indexOf(listener);
  2629. if (index !== -1) {
  2630. listeners.splice(index, 1);
  2631. }
  2632. if (listeners.length > 0) {
  2633. return;
  2634. }
  2635. arrayEvents.forEach(function(key) {
  2636. delete array[key];
  2637. });
  2638. delete array._chartjs;
  2639. }
  2640. // Base class for all dataset controllers (line, bar, etc)
  2641. var DatasetController = function(chart, datasetIndex) {
  2642. this.initialize(chart, datasetIndex);
  2643. };
  2644. helpers$1.extend(DatasetController.prototype, {
  2645. /**
  2646. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  2647. * @type {Chart.core.element}
  2648. */
  2649. datasetElementType: null,
  2650. /**
  2651. * Element type used to generate a meta data (e.g. Chart.element.Point).
  2652. * @type {Chart.core.element}
  2653. */
  2654. dataElementType: null,
  2655. initialize: function(chart, datasetIndex) {
  2656. var me = this;
  2657. me.chart = chart;
  2658. me.index = datasetIndex;
  2659. me.linkScales();
  2660. me.addElements();
  2661. },
  2662. updateIndex: function(datasetIndex) {
  2663. this.index = datasetIndex;
  2664. },
  2665. linkScales: function() {
  2666. var me = this;
  2667. var meta = me.getMeta();
  2668. var dataset = me.getDataset();
  2669. if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) {
  2670. meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
  2671. }
  2672. if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) {
  2673. meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
  2674. }
  2675. },
  2676. getDataset: function() {
  2677. return this.chart.data.datasets[this.index];
  2678. },
  2679. getMeta: function() {
  2680. return this.chart.getDatasetMeta(this.index);
  2681. },
  2682. getScaleForId: function(scaleID) {
  2683. return this.chart.scales[scaleID];
  2684. },
  2685. /**
  2686. * @private
  2687. */
  2688. _getValueScaleId: function() {
  2689. return this.getMeta().yAxisID;
  2690. },
  2691. /**
  2692. * @private
  2693. */
  2694. _getIndexScaleId: function() {
  2695. return this.getMeta().xAxisID;
  2696. },
  2697. /**
  2698. * @private
  2699. */
  2700. _getValueScale: function() {
  2701. return this.getScaleForId(this._getValueScaleId());
  2702. },
  2703. /**
  2704. * @private
  2705. */
  2706. _getIndexScale: function() {
  2707. return this.getScaleForId(this._getIndexScaleId());
  2708. },
  2709. reset: function() {
  2710. this.update(true);
  2711. },
  2712. /**
  2713. * @private
  2714. */
  2715. destroy: function() {
  2716. if (this._data) {
  2717. unlistenArrayEvents(this._data, this);
  2718. }
  2719. },
  2720. createMetaDataset: function() {
  2721. var me = this;
  2722. var type = me.datasetElementType;
  2723. return type && new type({
  2724. _chart: me.chart,
  2725. _datasetIndex: me.index
  2726. });
  2727. },
  2728. createMetaData: function(index) {
  2729. var me = this;
  2730. var type = me.dataElementType;
  2731. return type && new type({
  2732. _chart: me.chart,
  2733. _datasetIndex: me.index,
  2734. _index: index
  2735. });
  2736. },
  2737. addElements: function() {
  2738. var me = this;
  2739. var meta = me.getMeta();
  2740. var data = me.getDataset().data || [];
  2741. var metaData = meta.data;
  2742. var i, ilen;
  2743. for (i = 0, ilen = data.length; i < ilen; ++i) {
  2744. metaData[i] = metaData[i] || me.createMetaData(i);
  2745. }
  2746. meta.dataset = meta.dataset || me.createMetaDataset();
  2747. },
  2748. addElementAndReset: function(index) {
  2749. var element = this.createMetaData(index);
  2750. this.getMeta().data.splice(index, 0, element);
  2751. this.updateElement(element, index, true);
  2752. },
  2753. buildOrUpdateElements: function() {
  2754. var me = this;
  2755. var dataset = me.getDataset();
  2756. var data = dataset.data || (dataset.data = []);
  2757. // In order to correctly handle data addition/deletion animation (an thus simulate
  2758. // real-time charts), we need to monitor these data modifications and synchronize
  2759. // the internal meta data accordingly.
  2760. if (me._data !== data) {
  2761. if (me._data) {
  2762. // This case happens when the user replaced the data array instance.
  2763. unlistenArrayEvents(me._data, me);
  2764. }
  2765. if (data && Object.isExtensible(data)) {
  2766. listenArrayEvents(data, me);
  2767. }
  2768. me._data = data;
  2769. }
  2770. // Re-sync meta data in case the user replaced the data array or if we missed
  2771. // any updates and so make sure that we handle number of datapoints changing.
  2772. me.resyncElements();
  2773. },
  2774. update: helpers$1.noop,
  2775. transition: function(easingValue) {
  2776. var meta = this.getMeta();
  2777. var elements = meta.data || [];
  2778. var ilen = elements.length;
  2779. var i = 0;
  2780. for (; i < ilen; ++i) {
  2781. elements[i].transition(easingValue);
  2782. }
  2783. if (meta.dataset) {
  2784. meta.dataset.transition(easingValue);
  2785. }
  2786. },
  2787. draw: function() {
  2788. var meta = this.getMeta();
  2789. var elements = meta.data || [];
  2790. var ilen = elements.length;
  2791. var i = 0;
  2792. if (meta.dataset) {
  2793. meta.dataset.draw();
  2794. }
  2795. for (; i < ilen; ++i) {
  2796. elements[i].draw();
  2797. }
  2798. },
  2799. removeHoverStyle: function(element) {
  2800. helpers$1.merge(element._model, element.$previousStyle || {});
  2801. delete element.$previousStyle;
  2802. },
  2803. setHoverStyle: function(element) {
  2804. var dataset = this.chart.data.datasets[element._datasetIndex];
  2805. var index = element._index;
  2806. var custom = element.custom || {};
  2807. var model = element._model;
  2808. var getHoverColor = helpers$1.getHoverColor;
  2809. element.$previousStyle = {
  2810. backgroundColor: model.backgroundColor,
  2811. borderColor: model.borderColor,
  2812. borderWidth: model.borderWidth
  2813. };
  2814. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  2815. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  2816. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  2817. },
  2818. /**
  2819. * @private
  2820. */
  2821. resyncElements: function() {
  2822. var me = this;
  2823. var meta = me.getMeta();
  2824. var data = me.getDataset().data;
  2825. var numMeta = meta.data.length;
  2826. var numData = data.length;
  2827. if (numData < numMeta) {
  2828. meta.data.splice(numData, numMeta - numData);
  2829. } else if (numData > numMeta) {
  2830. me.insertElements(numMeta, numData - numMeta);
  2831. }
  2832. },
  2833. /**
  2834. * @private
  2835. */
  2836. insertElements: function(start, count) {
  2837. for (var i = 0; i < count; ++i) {
  2838. this.addElementAndReset(start + i);
  2839. }
  2840. },
  2841. /**
  2842. * @private
  2843. */
  2844. onDataPush: function() {
  2845. var count = arguments.length;
  2846. this.insertElements(this.getDataset().data.length - count, count);
  2847. },
  2848. /**
  2849. * @private
  2850. */
  2851. onDataPop: function() {
  2852. this.getMeta().data.pop();
  2853. },
  2854. /**
  2855. * @private
  2856. */
  2857. onDataShift: function() {
  2858. this.getMeta().data.shift();
  2859. },
  2860. /**
  2861. * @private
  2862. */
  2863. onDataSplice: function(start, count) {
  2864. this.getMeta().data.splice(start, count);
  2865. this.insertElements(start, arguments.length - 2);
  2866. },
  2867. /**
  2868. * @private
  2869. */
  2870. onDataUnshift: function() {
  2871. this.insertElements(0, arguments.length);
  2872. }
  2873. });
  2874. DatasetController.extend = helpers$1.inherits;
  2875. var core_datasetController = DatasetController;
  2876. core_defaults._set('global', {
  2877. elements: {
  2878. arc: {
  2879. backgroundColor: core_defaults.global.defaultColor,
  2880. borderColor: '#fff',
  2881. borderWidth: 2,
  2882. borderAlign: 'center'
  2883. }
  2884. }
  2885. });
  2886. var element_arc = core_element.extend({
  2887. inLabelRange: function(mouseX) {
  2888. var vm = this._view;
  2889. if (vm) {
  2890. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  2891. }
  2892. return false;
  2893. },
  2894. inRange: function(chartX, chartY) {
  2895. var vm = this._view;
  2896. if (vm) {
  2897. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  2898. var angle = pointRelativePosition.angle;
  2899. var distance = pointRelativePosition.distance;
  2900. // Sanitise angle range
  2901. var startAngle = vm.startAngle;
  2902. var endAngle = vm.endAngle;
  2903. while (endAngle < startAngle) {
  2904. endAngle += 2.0 * Math.PI;
  2905. }
  2906. while (angle > endAngle) {
  2907. angle -= 2.0 * Math.PI;
  2908. }
  2909. while (angle < startAngle) {
  2910. angle += 2.0 * Math.PI;
  2911. }
  2912. // Check if within the range of the open/close angle
  2913. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  2914. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  2915. return (betweenAngles && withinRadius);
  2916. }
  2917. return false;
  2918. },
  2919. getCenterPoint: function() {
  2920. var vm = this._view;
  2921. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  2922. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  2923. return {
  2924. x: vm.x + Math.cos(halfAngle) * halfRadius,
  2925. y: vm.y + Math.sin(halfAngle) * halfRadius
  2926. };
  2927. },
  2928. getArea: function() {
  2929. var vm = this._view;
  2930. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  2931. },
  2932. tooltipPosition: function() {
  2933. var vm = this._view;
  2934. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  2935. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  2936. return {
  2937. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  2938. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  2939. };
  2940. },
  2941. draw: function() {
  2942. var ctx = this._chart.ctx;
  2943. var vm = this._view;
  2944. var sA = vm.startAngle;
  2945. var eA = vm.endAngle;
  2946. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  2947. var angleMargin;
  2948. ctx.save();
  2949. ctx.beginPath();
  2950. ctx.arc(vm.x, vm.y, Math.max(vm.outerRadius - pixelMargin, 0), sA, eA);
  2951. ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
  2952. ctx.closePath();
  2953. ctx.fillStyle = vm.backgroundColor;
  2954. ctx.fill();
  2955. if (vm.borderWidth) {
  2956. if (vm.borderAlign === 'inner') {
  2957. // Draw an inner border by cliping the arc and drawing a double-width border
  2958. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  2959. ctx.beginPath();
  2960. angleMargin = pixelMargin / vm.outerRadius;
  2961. ctx.arc(vm.x, vm.y, vm.outerRadius, sA - angleMargin, eA + angleMargin);
  2962. if (vm.innerRadius > pixelMargin) {
  2963. angleMargin = pixelMargin / vm.innerRadius;
  2964. ctx.arc(vm.x, vm.y, vm.innerRadius - pixelMargin, eA + angleMargin, sA - angleMargin, true);
  2965. } else {
  2966. ctx.arc(vm.x, vm.y, pixelMargin, eA + Math.PI / 2, sA - Math.PI / 2);
  2967. }
  2968. ctx.closePath();
  2969. ctx.clip();
  2970. ctx.beginPath();
  2971. ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
  2972. ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
  2973. ctx.closePath();
  2974. ctx.lineWidth = vm.borderWidth * 2;
  2975. ctx.lineJoin = 'round';
  2976. } else {
  2977. ctx.lineWidth = vm.borderWidth;
  2978. ctx.lineJoin = 'bevel';
  2979. }
  2980. ctx.strokeStyle = vm.borderColor;
  2981. ctx.stroke();
  2982. }
  2983. ctx.restore();
  2984. }
  2985. });
  2986. var valueOrDefault$1 = helpers$1.valueOrDefault;
  2987. var defaultColor = core_defaults.global.defaultColor;
  2988. core_defaults._set('global', {
  2989. elements: {
  2990. line: {
  2991. tension: 0.4,
  2992. backgroundColor: defaultColor,
  2993. borderWidth: 3,
  2994. borderColor: defaultColor,
  2995. borderCapStyle: 'butt',
  2996. borderDash: [],
  2997. borderDashOffset: 0.0,
  2998. borderJoinStyle: 'miter',
  2999. capBezierPoints: true,
  3000. fill: true, // do we fill in the area between the line and its base axis
  3001. }
  3002. }
  3003. });
  3004. var element_line = core_element.extend({
  3005. draw: function() {
  3006. var me = this;
  3007. var vm = me._view;
  3008. var ctx = me._chart.ctx;
  3009. var spanGaps = vm.spanGaps;
  3010. var points = me._children.slice(); // clone array
  3011. var globalDefaults = core_defaults.global;
  3012. var globalOptionLineElements = globalDefaults.elements.line;
  3013. var lastDrawnIndex = -1;
  3014. var index, current, previous, currentVM;
  3015. // If we are looping, adding the first point again
  3016. if (me._loop && points.length) {
  3017. points.push(points[0]);
  3018. }
  3019. ctx.save();
  3020. // Stroke Line Options
  3021. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3022. // IE 9 and 10 do not support line dash
  3023. if (ctx.setLineDash) {
  3024. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3025. }
  3026. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3027. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3028. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3029. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3030. // Stroke Line
  3031. ctx.beginPath();
  3032. lastDrawnIndex = -1;
  3033. for (index = 0; index < points.length; ++index) {
  3034. current = points[index];
  3035. previous = helpers$1.previousItem(points, index);
  3036. currentVM = current._view;
  3037. // First point moves to it's starting position no matter what
  3038. if (index === 0) {
  3039. if (!currentVM.skip) {
  3040. ctx.moveTo(currentVM.x, currentVM.y);
  3041. lastDrawnIndex = index;
  3042. }
  3043. } else {
  3044. previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
  3045. if (!currentVM.skip) {
  3046. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3047. // There was a gap and this is the first point after the gap
  3048. ctx.moveTo(currentVM.x, currentVM.y);
  3049. } else {
  3050. // Line to next point
  3051. helpers$1.canvas.lineTo(ctx, previous._view, current._view);
  3052. }
  3053. lastDrawnIndex = index;
  3054. }
  3055. }
  3056. }
  3057. ctx.stroke();
  3058. ctx.restore();
  3059. }
  3060. });
  3061. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3062. var defaultColor$1 = core_defaults.global.defaultColor;
  3063. core_defaults._set('global', {
  3064. elements: {
  3065. point: {
  3066. radius: 3,
  3067. pointStyle: 'circle',
  3068. backgroundColor: defaultColor$1,
  3069. borderColor: defaultColor$1,
  3070. borderWidth: 1,
  3071. // Hover
  3072. hitRadius: 1,
  3073. hoverRadius: 4,
  3074. hoverBorderWidth: 1
  3075. }
  3076. }
  3077. });
  3078. function xRange(mouseX) {
  3079. var vm = this._view;
  3080. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3081. }
  3082. function yRange(mouseY) {
  3083. var vm = this._view;
  3084. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3085. }
  3086. var element_point = core_element.extend({
  3087. inRange: function(mouseX, mouseY) {
  3088. var vm = this._view;
  3089. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3090. },
  3091. inLabelRange: xRange,
  3092. inXRange: xRange,
  3093. inYRange: yRange,
  3094. getCenterPoint: function() {
  3095. var vm = this._view;
  3096. return {
  3097. x: vm.x,
  3098. y: vm.y
  3099. };
  3100. },
  3101. getArea: function() {
  3102. return Math.PI * Math.pow(this._view.radius, 2);
  3103. },
  3104. tooltipPosition: function() {
  3105. var vm = this._view;
  3106. return {
  3107. x: vm.x,
  3108. y: vm.y,
  3109. padding: vm.radius + vm.borderWidth
  3110. };
  3111. },
  3112. draw: function(chartArea) {
  3113. var vm = this._view;
  3114. var ctx = this._chart.ctx;
  3115. var pointStyle = vm.pointStyle;
  3116. var rotation = vm.rotation;
  3117. var radius = vm.radius;
  3118. var x = vm.x;
  3119. var y = vm.y;
  3120. var globalDefaults = core_defaults.global;
  3121. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3122. if (vm.skip) {
  3123. return;
  3124. }
  3125. // Clipping for Points.
  3126. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3127. ctx.strokeStyle = vm.borderColor || defaultColor;
  3128. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3129. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3130. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3131. }
  3132. }
  3133. });
  3134. var defaultColor$2 = core_defaults.global.defaultColor;
  3135. core_defaults._set('global', {
  3136. elements: {
  3137. rectangle: {
  3138. backgroundColor: defaultColor$2,
  3139. borderColor: defaultColor$2,
  3140. borderSkipped: 'bottom',
  3141. borderWidth: 0
  3142. }
  3143. }
  3144. });
  3145. function isVertical(vm) {
  3146. return vm && vm.width !== undefined;
  3147. }
  3148. /**
  3149. * Helper function to get the bounds of the bar regardless of the orientation
  3150. * @param bar {Chart.Element.Rectangle} the bar
  3151. * @return {Bounds} bounds of the bar
  3152. * @private
  3153. */
  3154. function getBarBounds(vm) {
  3155. var x1, x2, y1, y2, half;
  3156. if (isVertical(vm)) {
  3157. half = vm.width / 2;
  3158. x1 = vm.x - half;
  3159. x2 = vm.x + half;
  3160. y1 = Math.min(vm.y, vm.base);
  3161. y2 = Math.max(vm.y, vm.base);
  3162. } else {
  3163. half = vm.height / 2;
  3164. x1 = Math.min(vm.x, vm.base);
  3165. x2 = Math.max(vm.x, vm.base);
  3166. y1 = vm.y - half;
  3167. y2 = vm.y + half;
  3168. }
  3169. return {
  3170. left: x1,
  3171. top: y1,
  3172. right: x2,
  3173. bottom: y2
  3174. };
  3175. }
  3176. function swap(orig, v1, v2) {
  3177. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3178. }
  3179. function parseBorderSkipped(vm) {
  3180. var edge = vm.borderSkipped;
  3181. var res = {};
  3182. if (!edge) {
  3183. return res;
  3184. }
  3185. if (vm.horizontal) {
  3186. if (vm.base > vm.x) {
  3187. edge = swap(edge, 'left', 'right');
  3188. }
  3189. } else if (vm.base < vm.y) {
  3190. edge = swap(edge, 'bottom', 'top');
  3191. }
  3192. res[edge] = true;
  3193. return res;
  3194. }
  3195. function parseBorderWidth(vm, maxW, maxH) {
  3196. var value = vm.borderWidth;
  3197. var skip = parseBorderSkipped(vm);
  3198. var t, r, b, l;
  3199. if (helpers$1.isObject(value)) {
  3200. t = +value.top || 0;
  3201. r = +value.right || 0;
  3202. b = +value.bottom || 0;
  3203. l = +value.left || 0;
  3204. } else {
  3205. t = r = b = l = +value || 0;
  3206. }
  3207. return {
  3208. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  3209. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  3210. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  3211. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  3212. };
  3213. }
  3214. function boundingRects(vm) {
  3215. var bounds = getBarBounds(vm);
  3216. var width = bounds.right - bounds.left;
  3217. var height = bounds.bottom - bounds.top;
  3218. var border = parseBorderWidth(vm, width / 2, height / 2);
  3219. return {
  3220. outer: {
  3221. x: bounds.left,
  3222. y: bounds.top,
  3223. w: width,
  3224. h: height
  3225. },
  3226. inner: {
  3227. x: bounds.left + border.l,
  3228. y: bounds.top + border.t,
  3229. w: width - border.l - border.r,
  3230. h: height - border.t - border.b
  3231. }
  3232. };
  3233. }
  3234. function inRange(vm, x, y) {
  3235. var skipX = x === null;
  3236. var skipY = y === null;
  3237. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  3238. return bounds
  3239. && (skipX || x >= bounds.left && x <= bounds.right)
  3240. && (skipY || y >= bounds.top && y <= bounds.bottom);
  3241. }
  3242. var element_rectangle = core_element.extend({
  3243. draw: function() {
  3244. var ctx = this._chart.ctx;
  3245. var vm = this._view;
  3246. var rects = boundingRects(vm);
  3247. var outer = rects.outer;
  3248. var inner = rects.inner;
  3249. ctx.fillStyle = vm.backgroundColor;
  3250. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  3251. if (outer.w === inner.w && outer.h === inner.h) {
  3252. return;
  3253. }
  3254. ctx.save();
  3255. ctx.beginPath();
  3256. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  3257. ctx.clip();
  3258. ctx.fillStyle = vm.borderColor;
  3259. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  3260. ctx.fill('evenodd');
  3261. ctx.restore();
  3262. },
  3263. height: function() {
  3264. var vm = this._view;
  3265. return vm.base - vm.y;
  3266. },
  3267. inRange: function(mouseX, mouseY) {
  3268. return inRange(this._view, mouseX, mouseY);
  3269. },
  3270. inLabelRange: function(mouseX, mouseY) {
  3271. var vm = this._view;
  3272. return isVertical(vm)
  3273. ? inRange(vm, mouseX, null)
  3274. : inRange(vm, null, mouseY);
  3275. },
  3276. inXRange: function(mouseX) {
  3277. return inRange(this._view, mouseX, null);
  3278. },
  3279. inYRange: function(mouseY) {
  3280. return inRange(this._view, null, mouseY);
  3281. },
  3282. getCenterPoint: function() {
  3283. var vm = this._view;
  3284. var x, y;
  3285. if (isVertical(vm)) {
  3286. x = vm.x;
  3287. y = (vm.y + vm.base) / 2;
  3288. } else {
  3289. x = (vm.x + vm.base) / 2;
  3290. y = vm.y;
  3291. }
  3292. return {x: x, y: y};
  3293. },
  3294. getArea: function() {
  3295. var vm = this._view;
  3296. return isVertical(vm)
  3297. ? vm.width * Math.abs(vm.y - vm.base)
  3298. : vm.height * Math.abs(vm.x - vm.base);
  3299. },
  3300. tooltipPosition: function() {
  3301. var vm = this._view;
  3302. return {
  3303. x: vm.x,
  3304. y: vm.y
  3305. };
  3306. }
  3307. });
  3308. var elements = {};
  3309. var Arc = element_arc;
  3310. var Line = element_line;
  3311. var Point = element_point;
  3312. var Rectangle = element_rectangle;
  3313. elements.Arc = Arc;
  3314. elements.Line = Line;
  3315. elements.Point = Point;
  3316. elements.Rectangle = Rectangle;
  3317. var resolve$1 = helpers$1.options.resolve;
  3318. core_defaults._set('bar', {
  3319. hover: {
  3320. mode: 'label'
  3321. },
  3322. scales: {
  3323. xAxes: [{
  3324. type: 'category',
  3325. categoryPercentage: 0.8,
  3326. barPercentage: 0.9,
  3327. offset: true,
  3328. gridLines: {
  3329. offsetGridLines: true
  3330. }
  3331. }],
  3332. yAxes: [{
  3333. type: 'linear'
  3334. }]
  3335. }
  3336. });
  3337. /**
  3338. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  3339. * @private
  3340. */
  3341. function computeMinSampleSize(scale, pixels) {
  3342. var min = scale.isHorizontal() ? scale.width : scale.height;
  3343. var ticks = scale.getTicks();
  3344. var prev, curr, i, ilen;
  3345. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  3346. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  3347. }
  3348. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  3349. curr = scale.getPixelForTick(i);
  3350. min = i > 0 ? Math.min(min, curr - prev) : min;
  3351. prev = curr;
  3352. }
  3353. return min;
  3354. }
  3355. /**
  3356. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  3357. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  3358. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  3359. * @private
  3360. */
  3361. function computeFitCategoryTraits(index, ruler, options) {
  3362. var thickness = options.barThickness;
  3363. var count = ruler.stackCount;
  3364. var curr = ruler.pixels[index];
  3365. var size, ratio;
  3366. if (helpers$1.isNullOrUndef(thickness)) {
  3367. size = ruler.min * options.categoryPercentage;
  3368. ratio = options.barPercentage;
  3369. } else {
  3370. // When bar thickness is enforced, category and bar percentages are ignored.
  3371. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  3372. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  3373. size = thickness * count;
  3374. ratio = 1;
  3375. }
  3376. return {
  3377. chunk: size / count,
  3378. ratio: ratio,
  3379. start: curr - (size / 2)
  3380. };
  3381. }
  3382. /**
  3383. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  3384. * percentage options are 1), based on the previous and following categories. This mode
  3385. * generates bars with different widths when data are not evenly spaced.
  3386. * @private
  3387. */
  3388. function computeFlexCategoryTraits(index, ruler, options) {
  3389. var pixels = ruler.pixels;
  3390. var curr = pixels[index];
  3391. var prev = index > 0 ? pixels[index - 1] : null;
  3392. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  3393. var percent = options.categoryPercentage;
  3394. var start, size;
  3395. if (prev === null) {
  3396. // first data: its size is double based on the next point or,
  3397. // if it's also the last data, we use the scale size.
  3398. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  3399. }
  3400. if (next === null) {
  3401. // last data: its size is also double based on the previous point.
  3402. next = curr + curr - prev;
  3403. }
  3404. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  3405. size = Math.abs(next - prev) / 2 * percent;
  3406. return {
  3407. chunk: size / ruler.stackCount,
  3408. ratio: options.barPercentage,
  3409. start: start
  3410. };
  3411. }
  3412. var controller_bar = core_datasetController.extend({
  3413. dataElementType: elements.Rectangle,
  3414. initialize: function() {
  3415. var me = this;
  3416. var meta;
  3417. core_datasetController.prototype.initialize.apply(me, arguments);
  3418. meta = me.getMeta();
  3419. meta.stack = me.getDataset().stack;
  3420. meta.bar = true;
  3421. },
  3422. update: function(reset) {
  3423. var me = this;
  3424. var rects = me.getMeta().data;
  3425. var i, ilen;
  3426. me._ruler = me.getRuler();
  3427. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  3428. me.updateElement(rects[i], i, reset);
  3429. }
  3430. },
  3431. updateElement: function(rectangle, index, reset) {
  3432. var me = this;
  3433. var meta = me.getMeta();
  3434. var dataset = me.getDataset();
  3435. var options = me._resolveElementOptions(rectangle, index);
  3436. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  3437. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  3438. rectangle._datasetIndex = me.index;
  3439. rectangle._index = index;
  3440. rectangle._model = {
  3441. backgroundColor: options.backgroundColor,
  3442. borderColor: options.borderColor,
  3443. borderSkipped: options.borderSkipped,
  3444. borderWidth: options.borderWidth,
  3445. datasetLabel: dataset.label,
  3446. label: me.chart.data.labels[index]
  3447. };
  3448. me._updateElementGeometry(rectangle, index, reset);
  3449. rectangle.pivot();
  3450. },
  3451. /**
  3452. * @private
  3453. */
  3454. _updateElementGeometry: function(rectangle, index, reset) {
  3455. var me = this;
  3456. var model = rectangle._model;
  3457. var vscale = me._getValueScale();
  3458. var base = vscale.getBasePixel();
  3459. var horizontal = vscale.isHorizontal();
  3460. var ruler = me._ruler || me.getRuler();
  3461. var vpixels = me.calculateBarValuePixels(me.index, index);
  3462. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
  3463. model.horizontal = horizontal;
  3464. model.base = reset ? base : vpixels.base;
  3465. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  3466. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  3467. model.height = horizontal ? ipixels.size : undefined;
  3468. model.width = horizontal ? undefined : ipixels.size;
  3469. },
  3470. /**
  3471. * Returns the stacks based on groups and bar visibility.
  3472. * @param {number} [last] - The dataset index
  3473. * @returns {string[]} The list of stack IDs
  3474. * @private
  3475. */
  3476. _getStacks: function(last) {
  3477. var me = this;
  3478. var chart = me.chart;
  3479. var scale = me._getIndexScale();
  3480. var stacked = scale.options.stacked;
  3481. var ilen = last === undefined ? chart.data.datasets.length : last + 1;
  3482. var stacks = [];
  3483. var i, meta;
  3484. for (i = 0; i < ilen; ++i) {
  3485. meta = chart.getDatasetMeta(i);
  3486. if (meta.bar && chart.isDatasetVisible(i) &&
  3487. (stacked === false ||
  3488. (stacked === true && stacks.indexOf(meta.stack) === -1) ||
  3489. (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
  3490. stacks.push(meta.stack);
  3491. }
  3492. }
  3493. return stacks;
  3494. },
  3495. /**
  3496. * Returns the effective number of stacks based on groups and bar visibility.
  3497. * @private
  3498. */
  3499. getStackCount: function() {
  3500. return this._getStacks().length;
  3501. },
  3502. /**
  3503. * Returns the stack index for the given dataset based on groups and bar visibility.
  3504. * @param {number} [datasetIndex] - The dataset index
  3505. * @param {string} [name] - The stack name to find
  3506. * @returns {number} The stack index
  3507. * @private
  3508. */
  3509. getStackIndex: function(datasetIndex, name) {
  3510. var stacks = this._getStacks(datasetIndex);
  3511. var index = (name !== undefined)
  3512. ? stacks.indexOf(name)
  3513. : -1; // indexOf returns -1 if element is not present
  3514. return (index === -1)
  3515. ? stacks.length - 1
  3516. : index;
  3517. },
  3518. /**
  3519. * @private
  3520. */
  3521. getRuler: function() {
  3522. var me = this;
  3523. var scale = me._getIndexScale();
  3524. var stackCount = me.getStackCount();
  3525. var datasetIndex = me.index;
  3526. var isHorizontal = scale.isHorizontal();
  3527. var start = isHorizontal ? scale.left : scale.top;
  3528. var end = start + (isHorizontal ? scale.width : scale.height);
  3529. var pixels = [];
  3530. var i, ilen, min;
  3531. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  3532. pixels.push(scale.getPixelForValue(null, i, datasetIndex));
  3533. }
  3534. min = helpers$1.isNullOrUndef(scale.options.barThickness)
  3535. ? computeMinSampleSize(scale, pixels)
  3536. : -1;
  3537. return {
  3538. min: min,
  3539. pixels: pixels,
  3540. start: start,
  3541. end: end,
  3542. stackCount: stackCount,
  3543. scale: scale
  3544. };
  3545. },
  3546. /**
  3547. * Note: pixel values are not clamped to the scale area.
  3548. * @private
  3549. */
  3550. calculateBarValuePixels: function(datasetIndex, index) {
  3551. var me = this;
  3552. var chart = me.chart;
  3553. var meta = me.getMeta();
  3554. var scale = me._getValueScale();
  3555. var isHorizontal = scale.isHorizontal();
  3556. var datasets = chart.data.datasets;
  3557. var value = +scale.getRightValue(datasets[datasetIndex].data[index]);
  3558. var minBarLength = scale.options.minBarLength;
  3559. var stacked = scale.options.stacked;
  3560. var stack = meta.stack;
  3561. var start = 0;
  3562. var i, imeta, ivalue, base, head, size;
  3563. if (stacked || (stacked === undefined && stack !== undefined)) {
  3564. for (i = 0; i < datasetIndex; ++i) {
  3565. imeta = chart.getDatasetMeta(i);
  3566. if (imeta.bar &&
  3567. imeta.stack === stack &&
  3568. imeta.controller._getValueScaleId() === scale.id &&
  3569. chart.isDatasetVisible(i)) {
  3570. ivalue = +scale.getRightValue(datasets[i].data[index]);
  3571. if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
  3572. start += ivalue;
  3573. }
  3574. }
  3575. }
  3576. }
  3577. base = scale.getPixelForValue(start);
  3578. head = scale.getPixelForValue(start + value);
  3579. size = head - base;
  3580. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  3581. size = minBarLength;
  3582. if (value >= 0 && !isHorizontal || value < 0 && isHorizontal) {
  3583. head = base - minBarLength;
  3584. } else {
  3585. head = base + minBarLength;
  3586. }
  3587. }
  3588. return {
  3589. size: size,
  3590. base: base,
  3591. head: head,
  3592. center: head + size / 2
  3593. };
  3594. },
  3595. /**
  3596. * @private
  3597. */
  3598. calculateBarIndexPixels: function(datasetIndex, index, ruler) {
  3599. var me = this;
  3600. var options = ruler.scale.options;
  3601. var range = options.barThickness === 'flex'
  3602. ? computeFlexCategoryTraits(index, ruler, options)
  3603. : computeFitCategoryTraits(index, ruler, options);
  3604. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  3605. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  3606. var size = Math.min(
  3607. helpers$1.valueOrDefault(options.maxBarThickness, Infinity),
  3608. range.chunk * range.ratio);
  3609. return {
  3610. base: center - size / 2,
  3611. head: center + size / 2,
  3612. center: center,
  3613. size: size
  3614. };
  3615. },
  3616. draw: function() {
  3617. var me = this;
  3618. var chart = me.chart;
  3619. var scale = me._getValueScale();
  3620. var rects = me.getMeta().data;
  3621. var dataset = me.getDataset();
  3622. var ilen = rects.length;
  3623. var i = 0;
  3624. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  3625. for (; i < ilen; ++i) {
  3626. if (!isNaN(scale.getRightValue(dataset.data[i]))) {
  3627. rects[i].draw();
  3628. }
  3629. }
  3630. helpers$1.canvas.unclipArea(chart.ctx);
  3631. },
  3632. /**
  3633. * @private
  3634. */
  3635. _resolveElementOptions: function(rectangle, index) {
  3636. var me = this;
  3637. var chart = me.chart;
  3638. var datasets = chart.data.datasets;
  3639. var dataset = datasets[me.index];
  3640. var custom = rectangle.custom || {};
  3641. var options = chart.options.elements.rectangle;
  3642. var values = {};
  3643. var i, ilen, key;
  3644. // Scriptable options
  3645. var context = {
  3646. chart: chart,
  3647. dataIndex: index,
  3648. dataset: dataset,
  3649. datasetIndex: me.index
  3650. };
  3651. var keys = [
  3652. 'backgroundColor',
  3653. 'borderColor',
  3654. 'borderSkipped',
  3655. 'borderWidth'
  3656. ];
  3657. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3658. key = keys[i];
  3659. values[key] = resolve$1([
  3660. custom[key],
  3661. dataset[key],
  3662. options[key]
  3663. ], context, index);
  3664. }
  3665. return values;
  3666. }
  3667. });
  3668. var valueOrDefault$3 = helpers$1.valueOrDefault;
  3669. var resolve$2 = helpers$1.options.resolve;
  3670. core_defaults._set('bubble', {
  3671. hover: {
  3672. mode: 'single'
  3673. },
  3674. scales: {
  3675. xAxes: [{
  3676. type: 'linear', // bubble should probably use a linear scale by default
  3677. position: 'bottom',
  3678. id: 'x-axis-0' // need an ID so datasets can reference the scale
  3679. }],
  3680. yAxes: [{
  3681. type: 'linear',
  3682. position: 'left',
  3683. id: 'y-axis-0'
  3684. }]
  3685. },
  3686. tooltips: {
  3687. callbacks: {
  3688. title: function() {
  3689. // Title doesn't make sense for scatter since we format the data as a point
  3690. return '';
  3691. },
  3692. label: function(item, data) {
  3693. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  3694. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  3695. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  3696. }
  3697. }
  3698. }
  3699. });
  3700. var controller_bubble = core_datasetController.extend({
  3701. /**
  3702. * @protected
  3703. */
  3704. dataElementType: elements.Point,
  3705. /**
  3706. * @protected
  3707. */
  3708. update: function(reset) {
  3709. var me = this;
  3710. var meta = me.getMeta();
  3711. var points = meta.data;
  3712. // Update Points
  3713. helpers$1.each(points, function(point, index) {
  3714. me.updateElement(point, index, reset);
  3715. });
  3716. },
  3717. /**
  3718. * @protected
  3719. */
  3720. updateElement: function(point, index, reset) {
  3721. var me = this;
  3722. var meta = me.getMeta();
  3723. var custom = point.custom || {};
  3724. var xScale = me.getScaleForId(meta.xAxisID);
  3725. var yScale = me.getScaleForId(meta.yAxisID);
  3726. var options = me._resolveElementOptions(point, index);
  3727. var data = me.getDataset().data[index];
  3728. var dsIndex = me.index;
  3729. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  3730. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  3731. point._xScale = xScale;
  3732. point._yScale = yScale;
  3733. point._options = options;
  3734. point._datasetIndex = dsIndex;
  3735. point._index = index;
  3736. point._model = {
  3737. backgroundColor: options.backgroundColor,
  3738. borderColor: options.borderColor,
  3739. borderWidth: options.borderWidth,
  3740. hitRadius: options.hitRadius,
  3741. pointStyle: options.pointStyle,
  3742. rotation: options.rotation,
  3743. radius: reset ? 0 : options.radius,
  3744. skip: custom.skip || isNaN(x) || isNaN(y),
  3745. x: x,
  3746. y: y,
  3747. };
  3748. point.pivot();
  3749. },
  3750. /**
  3751. * @protected
  3752. */
  3753. setHoverStyle: function(point) {
  3754. var model = point._model;
  3755. var options = point._options;
  3756. var getHoverColor = helpers$1.getHoverColor;
  3757. point.$previousStyle = {
  3758. backgroundColor: model.backgroundColor,
  3759. borderColor: model.borderColor,
  3760. borderWidth: model.borderWidth,
  3761. radius: model.radius
  3762. };
  3763. model.backgroundColor = valueOrDefault$3(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  3764. model.borderColor = valueOrDefault$3(options.hoverBorderColor, getHoverColor(options.borderColor));
  3765. model.borderWidth = valueOrDefault$3(options.hoverBorderWidth, options.borderWidth);
  3766. model.radius = options.radius + options.hoverRadius;
  3767. },
  3768. /**
  3769. * @private
  3770. */
  3771. _resolveElementOptions: function(point, index) {
  3772. var me = this;
  3773. var chart = me.chart;
  3774. var datasets = chart.data.datasets;
  3775. var dataset = datasets[me.index];
  3776. var custom = point.custom || {};
  3777. var options = chart.options.elements.point;
  3778. var data = dataset.data[index];
  3779. var values = {};
  3780. var i, ilen, key;
  3781. // Scriptable options
  3782. var context = {
  3783. chart: chart,
  3784. dataIndex: index,
  3785. dataset: dataset,
  3786. datasetIndex: me.index
  3787. };
  3788. var keys = [
  3789. 'backgroundColor',
  3790. 'borderColor',
  3791. 'borderWidth',
  3792. 'hoverBackgroundColor',
  3793. 'hoverBorderColor',
  3794. 'hoverBorderWidth',
  3795. 'hoverRadius',
  3796. 'hitRadius',
  3797. 'pointStyle',
  3798. 'rotation'
  3799. ];
  3800. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3801. key = keys[i];
  3802. values[key] = resolve$2([
  3803. custom[key],
  3804. dataset[key],
  3805. options[key]
  3806. ], context, index);
  3807. }
  3808. // Custom radius resolution
  3809. values.radius = resolve$2([
  3810. custom.radius,
  3811. data ? data.r : undefined,
  3812. dataset.radius,
  3813. options.radius
  3814. ], context, index);
  3815. return values;
  3816. }
  3817. });
  3818. var resolve$3 = helpers$1.options.resolve;
  3819. var valueOrDefault$4 = helpers$1.valueOrDefault;
  3820. core_defaults._set('doughnut', {
  3821. animation: {
  3822. // Boolean - Whether we animate the rotation of the Doughnut
  3823. animateRotate: true,
  3824. // Boolean - Whether we animate scaling the Doughnut from the centre
  3825. animateScale: false
  3826. },
  3827. hover: {
  3828. mode: 'single'
  3829. },
  3830. legendCallback: function(chart) {
  3831. var text = [];
  3832. text.push('<ul class="' + chart.id + '-legend">');
  3833. var data = chart.data;
  3834. var datasets = data.datasets;
  3835. var labels = data.labels;
  3836. if (datasets.length) {
  3837. for (var i = 0; i < datasets[0].data.length; ++i) {
  3838. text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
  3839. if (labels[i]) {
  3840. text.push(labels[i]);
  3841. }
  3842. text.push('</li>');
  3843. }
  3844. }
  3845. text.push('</ul>');
  3846. return text.join('');
  3847. },
  3848. legend: {
  3849. labels: {
  3850. generateLabels: function(chart) {
  3851. var data = chart.data;
  3852. if (data.labels.length && data.datasets.length) {
  3853. return data.labels.map(function(label, i) {
  3854. var meta = chart.getDatasetMeta(0);
  3855. var ds = data.datasets[0];
  3856. var arc = meta.data[i];
  3857. var custom = arc && arc.custom || {};
  3858. var arcOpts = chart.options.elements.arc;
  3859. var fill = resolve$3([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i);
  3860. var stroke = resolve$3([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i);
  3861. var bw = resolve$3([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i);
  3862. return {
  3863. text: label,
  3864. fillStyle: fill,
  3865. strokeStyle: stroke,
  3866. lineWidth: bw,
  3867. hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
  3868. // Extra data used for toggling the correct item
  3869. index: i
  3870. };
  3871. });
  3872. }
  3873. return [];
  3874. }
  3875. },
  3876. onClick: function(e, legendItem) {
  3877. var index = legendItem.index;
  3878. var chart = this.chart;
  3879. var i, ilen, meta;
  3880. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  3881. meta = chart.getDatasetMeta(i);
  3882. // toggle visibility of index if exists
  3883. if (meta.data[index]) {
  3884. meta.data[index].hidden = !meta.data[index].hidden;
  3885. }
  3886. }
  3887. chart.update();
  3888. }
  3889. },
  3890. // The percentage of the chart that we cut out of the middle.
  3891. cutoutPercentage: 50,
  3892. // The rotation of the chart, where the first data arc begins.
  3893. rotation: Math.PI * -0.5,
  3894. // The total circumference of the chart.
  3895. circumference: Math.PI * 2.0,
  3896. // Need to override these to give a nice default
  3897. tooltips: {
  3898. callbacks: {
  3899. title: function() {
  3900. return '';
  3901. },
  3902. label: function(tooltipItem, data) {
  3903. var dataLabel = data.labels[tooltipItem.index];
  3904. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  3905. if (helpers$1.isArray(dataLabel)) {
  3906. // show value on first line of multiline label
  3907. // need to clone because we are changing the value
  3908. dataLabel = dataLabel.slice();
  3909. dataLabel[0] += value;
  3910. } else {
  3911. dataLabel += value;
  3912. }
  3913. return dataLabel;
  3914. }
  3915. }
  3916. }
  3917. });
  3918. var controller_doughnut = core_datasetController.extend({
  3919. dataElementType: elements.Arc,
  3920. linkScales: helpers$1.noop,
  3921. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  3922. getRingIndex: function(datasetIndex) {
  3923. var ringIndex = 0;
  3924. for (var j = 0; j < datasetIndex; ++j) {
  3925. if (this.chart.isDatasetVisible(j)) {
  3926. ++ringIndex;
  3927. }
  3928. }
  3929. return ringIndex;
  3930. },
  3931. update: function(reset) {
  3932. var me = this;
  3933. var chart = me.chart;
  3934. var chartArea = chart.chartArea;
  3935. var opts = chart.options;
  3936. var availableWidth = chartArea.right - chartArea.left;
  3937. var availableHeight = chartArea.bottom - chartArea.top;
  3938. var minSize = Math.min(availableWidth, availableHeight);
  3939. var offset = {x: 0, y: 0};
  3940. var meta = me.getMeta();
  3941. var arcs = meta.data;
  3942. var cutoutPercentage = opts.cutoutPercentage;
  3943. var circumference = opts.circumference;
  3944. var chartWeight = me._getRingWeight(me.index);
  3945. var i, ilen;
  3946. // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
  3947. if (circumference < Math.PI * 2.0) {
  3948. var startAngle = opts.rotation % (Math.PI * 2.0);
  3949. startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
  3950. var endAngle = startAngle + circumference;
  3951. var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
  3952. var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
  3953. var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
  3954. var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
  3955. var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
  3956. var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
  3957. var cutout = cutoutPercentage / 100.0;
  3958. var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))};
  3959. var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))};
  3960. var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
  3961. minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
  3962. offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
  3963. }
  3964. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  3965. arcs[i]._options = me._resolveElementOptions(arcs[i], i);
  3966. }
  3967. chart.borderWidth = me.getMaxBorderWidth();
  3968. chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
  3969. chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
  3970. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  3971. chart.offsetX = offset.x * chart.outerRadius;
  3972. chart.offsetY = offset.y * chart.outerRadius;
  3973. meta.total = me.calculateTotal();
  3974. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  3975. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  3976. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  3977. me.updateElement(arcs[i], i, reset);
  3978. }
  3979. },
  3980. updateElement: function(arc, index, reset) {
  3981. var me = this;
  3982. var chart = me.chart;
  3983. var chartArea = chart.chartArea;
  3984. var opts = chart.options;
  3985. var animationOpts = opts.animation;
  3986. var centerX = (chartArea.left + chartArea.right) / 2;
  3987. var centerY = (chartArea.top + chartArea.bottom) / 2;
  3988. var startAngle = opts.rotation; // non reset case handled later
  3989. var endAngle = opts.rotation; // non reset case handled later
  3990. var dataset = me.getDataset();
  3991. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI));
  3992. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  3993. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  3994. var options = arc._options || {};
  3995. helpers$1.extend(arc, {
  3996. // Utility
  3997. _datasetIndex: me.index,
  3998. _index: index,
  3999. // Desired view properties
  4000. _model: {
  4001. backgroundColor: options.backgroundColor,
  4002. borderColor: options.borderColor,
  4003. borderWidth: options.borderWidth,
  4004. borderAlign: options.borderAlign,
  4005. x: centerX + chart.offsetX,
  4006. y: centerY + chart.offsetY,
  4007. startAngle: startAngle,
  4008. endAngle: endAngle,
  4009. circumference: circumference,
  4010. outerRadius: outerRadius,
  4011. innerRadius: innerRadius,
  4012. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4013. }
  4014. });
  4015. var model = arc._model;
  4016. // Set correct angles if not resetting
  4017. if (!reset || !animationOpts.animateRotate) {
  4018. if (index === 0) {
  4019. model.startAngle = opts.rotation;
  4020. } else {
  4021. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4022. }
  4023. model.endAngle = model.startAngle + model.circumference;
  4024. }
  4025. arc.pivot();
  4026. },
  4027. calculateTotal: function() {
  4028. var dataset = this.getDataset();
  4029. var meta = this.getMeta();
  4030. var total = 0;
  4031. var value;
  4032. helpers$1.each(meta.data, function(element, index) {
  4033. value = dataset.data[index];
  4034. if (!isNaN(value) && !element.hidden) {
  4035. total += Math.abs(value);
  4036. }
  4037. });
  4038. /* if (total === 0) {
  4039. total = NaN;
  4040. }*/
  4041. return total;
  4042. },
  4043. calculateCircumference: function(value) {
  4044. var total = this.getMeta().total;
  4045. if (total > 0 && !isNaN(value)) {
  4046. return (Math.PI * 2.0) * (Math.abs(value) / total);
  4047. }
  4048. return 0;
  4049. },
  4050. // gets the max border or hover width to properly scale pie charts
  4051. getMaxBorderWidth: function(arcs) {
  4052. var me = this;
  4053. var max = 0;
  4054. var chart = me.chart;
  4055. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4056. if (!arcs) {
  4057. // Find the outmost visible dataset
  4058. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4059. if (chart.isDatasetVisible(i)) {
  4060. meta = chart.getDatasetMeta(i);
  4061. arcs = meta.data;
  4062. if (i !== me.index) {
  4063. controller = meta.controller;
  4064. }
  4065. break;
  4066. }
  4067. }
  4068. }
  4069. if (!arcs) {
  4070. return 0;
  4071. }
  4072. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4073. arc = arcs[i];
  4074. options = controller ? controller._resolveElementOptions(arc, i) : arc._options;
  4075. if (options.borderAlign !== 'inner') {
  4076. borderWidth = options.borderWidth;
  4077. hoverWidth = options.hoverBorderWidth;
  4078. max = borderWidth > max ? borderWidth : max;
  4079. max = hoverWidth > max ? hoverWidth : max;
  4080. }
  4081. }
  4082. return max;
  4083. },
  4084. /**
  4085. * @protected
  4086. */
  4087. setHoverStyle: function(arc) {
  4088. var model = arc._model;
  4089. var options = arc._options;
  4090. var getHoverColor = helpers$1.getHoverColor;
  4091. arc.$previousStyle = {
  4092. backgroundColor: model.backgroundColor,
  4093. borderColor: model.borderColor,
  4094. borderWidth: model.borderWidth,
  4095. };
  4096. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4097. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4098. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4099. },
  4100. /**
  4101. * @private
  4102. */
  4103. _resolveElementOptions: function(arc, index) {
  4104. var me = this;
  4105. var chart = me.chart;
  4106. var dataset = me.getDataset();
  4107. var custom = arc.custom || {};
  4108. var options = chart.options.elements.arc;
  4109. var values = {};
  4110. var i, ilen, key;
  4111. // Scriptable options
  4112. var context = {
  4113. chart: chart,
  4114. dataIndex: index,
  4115. dataset: dataset,
  4116. datasetIndex: me.index
  4117. };
  4118. var keys = [
  4119. 'backgroundColor',
  4120. 'borderColor',
  4121. 'borderWidth',
  4122. 'borderAlign',
  4123. 'hoverBackgroundColor',
  4124. 'hoverBorderColor',
  4125. 'hoverBorderWidth',
  4126. ];
  4127. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4128. key = keys[i];
  4129. values[key] = resolve$3([
  4130. custom[key],
  4131. dataset[key],
  4132. options[key]
  4133. ], context, index);
  4134. }
  4135. return values;
  4136. },
  4137. /**
  4138. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4139. * @private
  4140. */
  4141. _getRingWeightOffset: function(datasetIndex) {
  4142. var ringWeightOffset = 0;
  4143. for (var i = 0; i < datasetIndex; ++i) {
  4144. if (this.chart.isDatasetVisible(i)) {
  4145. ringWeightOffset += this._getRingWeight(i);
  4146. }
  4147. }
  4148. return ringWeightOffset;
  4149. },
  4150. /**
  4151. * @private
  4152. */
  4153. _getRingWeight: function(dataSetIndex) {
  4154. return Math.max(valueOrDefault$4(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4155. },
  4156. /**
  4157. * Returns the sum of all visibile data set weights. This value can be 0.
  4158. * @private
  4159. */
  4160. _getVisibleDatasetWeightTotal: function() {
  4161. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4162. }
  4163. });
  4164. core_defaults._set('horizontalBar', {
  4165. hover: {
  4166. mode: 'index',
  4167. axis: 'y'
  4168. },
  4169. scales: {
  4170. xAxes: [{
  4171. type: 'linear',
  4172. position: 'bottom'
  4173. }],
  4174. yAxes: [{
  4175. type: 'category',
  4176. position: 'left',
  4177. categoryPercentage: 0.8,
  4178. barPercentage: 0.9,
  4179. offset: true,
  4180. gridLines: {
  4181. offsetGridLines: true
  4182. }
  4183. }]
  4184. },
  4185. elements: {
  4186. rectangle: {
  4187. borderSkipped: 'left'
  4188. }
  4189. },
  4190. tooltips: {
  4191. mode: 'index',
  4192. axis: 'y'
  4193. }
  4194. });
  4195. var controller_horizontalBar = controller_bar.extend({
  4196. /**
  4197. * @private
  4198. */
  4199. _getValueScaleId: function() {
  4200. return this.getMeta().xAxisID;
  4201. },
  4202. /**
  4203. * @private
  4204. */
  4205. _getIndexScaleId: function() {
  4206. return this.getMeta().yAxisID;
  4207. }
  4208. });
  4209. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4210. var resolve$4 = helpers$1.options.resolve;
  4211. var isPointInArea = helpers$1.canvas._isPointInArea;
  4212. core_defaults._set('line', {
  4213. showLines: true,
  4214. spanGaps: false,
  4215. hover: {
  4216. mode: 'label'
  4217. },
  4218. scales: {
  4219. xAxes: [{
  4220. type: 'category',
  4221. id: 'x-axis-0'
  4222. }],
  4223. yAxes: [{
  4224. type: 'linear',
  4225. id: 'y-axis-0'
  4226. }]
  4227. }
  4228. });
  4229. function lineEnabled(dataset, options) {
  4230. return valueOrDefault$5(dataset.showLine, options.showLines);
  4231. }
  4232. var controller_line = core_datasetController.extend({
  4233. datasetElementType: elements.Line,
  4234. dataElementType: elements.Point,
  4235. update: function(reset) {
  4236. var me = this;
  4237. var meta = me.getMeta();
  4238. var line = meta.dataset;
  4239. var points = meta.data || [];
  4240. var scale = me.getScaleForId(meta.yAxisID);
  4241. var dataset = me.getDataset();
  4242. var showLine = lineEnabled(dataset, me.chart.options);
  4243. var i, ilen;
  4244. // Update Line
  4245. if (showLine) {
  4246. // Compatibility: If the properties are defined with only the old name, use those values
  4247. if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
  4248. dataset.lineTension = dataset.tension;
  4249. }
  4250. // Utility
  4251. line._scale = scale;
  4252. line._datasetIndex = me.index;
  4253. // Data
  4254. line._children = points;
  4255. // Model
  4256. line._model = me._resolveLineOptions(line);
  4257. line.pivot();
  4258. }
  4259. // Update Points
  4260. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4261. me.updateElement(points[i], i, reset);
  4262. }
  4263. if (showLine && line._model.tension !== 0) {
  4264. me.updateBezierControlPoints();
  4265. }
  4266. // Now pivot the point for animation
  4267. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4268. points[i].pivot();
  4269. }
  4270. },
  4271. updateElement: function(point, index, reset) {
  4272. var me = this;
  4273. var meta = me.getMeta();
  4274. var custom = point.custom || {};
  4275. var dataset = me.getDataset();
  4276. var datasetIndex = me.index;
  4277. var value = dataset.data[index];
  4278. var yScale = me.getScaleForId(meta.yAxisID);
  4279. var xScale = me.getScaleForId(meta.xAxisID);
  4280. var lineModel = meta.dataset._model;
  4281. var x, y;
  4282. var options = me._resolvePointOptions(point, index);
  4283. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  4284. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  4285. // Utility
  4286. point._xScale = xScale;
  4287. point._yScale = yScale;
  4288. point._options = options;
  4289. point._datasetIndex = datasetIndex;
  4290. point._index = index;
  4291. // Desired view properties
  4292. point._model = {
  4293. x: x,
  4294. y: y,
  4295. skip: custom.skip || isNaN(x) || isNaN(y),
  4296. // Appearance
  4297. radius: options.radius,
  4298. pointStyle: options.pointStyle,
  4299. rotation: options.rotation,
  4300. backgroundColor: options.backgroundColor,
  4301. borderColor: options.borderColor,
  4302. borderWidth: options.borderWidth,
  4303. tension: valueOrDefault$5(custom.tension, lineModel ? lineModel.tension : 0),
  4304. steppedLine: lineModel ? lineModel.steppedLine : false,
  4305. // Tooltip
  4306. hitRadius: options.hitRadius
  4307. };
  4308. },
  4309. /**
  4310. * @private
  4311. */
  4312. _resolvePointOptions: function(element, index) {
  4313. var me = this;
  4314. var chart = me.chart;
  4315. var dataset = chart.data.datasets[me.index];
  4316. var custom = element.custom || {};
  4317. var options = chart.options.elements.point;
  4318. var values = {};
  4319. var i, ilen, key;
  4320. // Scriptable options
  4321. var context = {
  4322. chart: chart,
  4323. dataIndex: index,
  4324. dataset: dataset,
  4325. datasetIndex: me.index
  4326. };
  4327. var ELEMENT_OPTIONS = {
  4328. backgroundColor: 'pointBackgroundColor',
  4329. borderColor: 'pointBorderColor',
  4330. borderWidth: 'pointBorderWidth',
  4331. hitRadius: 'pointHitRadius',
  4332. hoverBackgroundColor: 'pointHoverBackgroundColor',
  4333. hoverBorderColor: 'pointHoverBorderColor',
  4334. hoverBorderWidth: 'pointHoverBorderWidth',
  4335. hoverRadius: 'pointHoverRadius',
  4336. pointStyle: 'pointStyle',
  4337. radius: 'pointRadius',
  4338. rotation: 'pointRotation'
  4339. };
  4340. var keys = Object.keys(ELEMENT_OPTIONS);
  4341. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4342. key = keys[i];
  4343. values[key] = resolve$4([
  4344. custom[key],
  4345. dataset[ELEMENT_OPTIONS[key]],
  4346. dataset[key],
  4347. options[key]
  4348. ], context, index);
  4349. }
  4350. return values;
  4351. },
  4352. /**
  4353. * @private
  4354. */
  4355. _resolveLineOptions: function(element) {
  4356. var me = this;
  4357. var chart = me.chart;
  4358. var dataset = chart.data.datasets[me.index];
  4359. var custom = element.custom || {};
  4360. var options = chart.options;
  4361. var elementOptions = options.elements.line;
  4362. var values = {};
  4363. var i, ilen, key;
  4364. var keys = [
  4365. 'backgroundColor',
  4366. 'borderWidth',
  4367. 'borderColor',
  4368. 'borderCapStyle',
  4369. 'borderDash',
  4370. 'borderDashOffset',
  4371. 'borderJoinStyle',
  4372. 'fill',
  4373. 'cubicInterpolationMode'
  4374. ];
  4375. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4376. key = keys[i];
  4377. values[key] = resolve$4([
  4378. custom[key],
  4379. dataset[key],
  4380. elementOptions[key]
  4381. ]);
  4382. }
  4383. // The default behavior of lines is to break at null values, according
  4384. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  4385. // This option gives lines the ability to span gaps
  4386. values.spanGaps = valueOrDefault$5(dataset.spanGaps, options.spanGaps);
  4387. values.tension = valueOrDefault$5(dataset.lineTension, elementOptions.tension);
  4388. values.steppedLine = resolve$4([custom.steppedLine, dataset.steppedLine, elementOptions.stepped]);
  4389. return values;
  4390. },
  4391. calculatePointY: function(value, index, datasetIndex) {
  4392. var me = this;
  4393. var chart = me.chart;
  4394. var meta = me.getMeta();
  4395. var yScale = me.getScaleForId(meta.yAxisID);
  4396. var sumPos = 0;
  4397. var sumNeg = 0;
  4398. var i, ds, dsMeta;
  4399. if (yScale.options.stacked) {
  4400. for (i = 0; i < datasetIndex; i++) {
  4401. ds = chart.data.datasets[i];
  4402. dsMeta = chart.getDatasetMeta(i);
  4403. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
  4404. var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
  4405. if (stackedRightValue < 0) {
  4406. sumNeg += stackedRightValue || 0;
  4407. } else {
  4408. sumPos += stackedRightValue || 0;
  4409. }
  4410. }
  4411. }
  4412. var rightValue = Number(yScale.getRightValue(value));
  4413. if (rightValue < 0) {
  4414. return yScale.getPixelForValue(sumNeg + rightValue);
  4415. }
  4416. return yScale.getPixelForValue(sumPos + rightValue);
  4417. }
  4418. return yScale.getPixelForValue(value);
  4419. },
  4420. updateBezierControlPoints: function() {
  4421. var me = this;
  4422. var chart = me.chart;
  4423. var meta = me.getMeta();
  4424. var lineModel = meta.dataset._model;
  4425. var area = chart.chartArea;
  4426. var points = meta.data || [];
  4427. var i, ilen, model, controlPoints;
  4428. // Only consider points that are drawn in case the spanGaps option is used
  4429. if (lineModel.spanGaps) {
  4430. points = points.filter(function(pt) {
  4431. return !pt._model.skip;
  4432. });
  4433. }
  4434. function capControlPoint(pt, min, max) {
  4435. return Math.max(Math.min(pt, max), min);
  4436. }
  4437. if (lineModel.cubicInterpolationMode === 'monotone') {
  4438. helpers$1.splineCurveMonotone(points);
  4439. } else {
  4440. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4441. model = points[i]._model;
  4442. controlPoints = helpers$1.splineCurve(
  4443. helpers$1.previousItem(points, i)._model,
  4444. model,
  4445. helpers$1.nextItem(points, i)._model,
  4446. lineModel.tension
  4447. );
  4448. model.controlPointPreviousX = controlPoints.previous.x;
  4449. model.controlPointPreviousY = controlPoints.previous.y;
  4450. model.controlPointNextX = controlPoints.next.x;
  4451. model.controlPointNextY = controlPoints.next.y;
  4452. }
  4453. }
  4454. if (chart.options.elements.line.capBezierPoints) {
  4455. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4456. model = points[i]._model;
  4457. if (isPointInArea(model, area)) {
  4458. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  4459. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  4460. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  4461. }
  4462. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  4463. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  4464. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  4465. }
  4466. }
  4467. }
  4468. }
  4469. },
  4470. draw: function() {
  4471. var me = this;
  4472. var chart = me.chart;
  4473. var meta = me.getMeta();
  4474. var points = meta.data || [];
  4475. var area = chart.chartArea;
  4476. var ilen = points.length;
  4477. var halfBorderWidth;
  4478. var i = 0;
  4479. if (lineEnabled(me.getDataset(), chart.options)) {
  4480. halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2;
  4481. helpers$1.canvas.clipArea(chart.ctx, {
  4482. left: area.left,
  4483. right: area.right,
  4484. top: area.top - halfBorderWidth,
  4485. bottom: area.bottom + halfBorderWidth
  4486. });
  4487. meta.dataset.draw();
  4488. helpers$1.canvas.unclipArea(chart.ctx);
  4489. }
  4490. // Draw the points
  4491. for (; i < ilen; ++i) {
  4492. points[i].draw(area);
  4493. }
  4494. },
  4495. /**
  4496. * @protected
  4497. */
  4498. setHoverStyle: function(point) {
  4499. var model = point._model;
  4500. var options = point._options;
  4501. var getHoverColor = helpers$1.getHoverColor;
  4502. point.$previousStyle = {
  4503. backgroundColor: model.backgroundColor,
  4504. borderColor: model.borderColor,
  4505. borderWidth: model.borderWidth,
  4506. radius: model.radius
  4507. };
  4508. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4509. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4510. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4511. model.radius = valueOrDefault$5(options.hoverRadius, options.radius);
  4512. },
  4513. });
  4514. var resolve$5 = helpers$1.options.resolve;
  4515. core_defaults._set('polarArea', {
  4516. scale: {
  4517. type: 'radialLinear',
  4518. angleLines: {
  4519. display: false
  4520. },
  4521. gridLines: {
  4522. circular: true
  4523. },
  4524. pointLabels: {
  4525. display: false
  4526. },
  4527. ticks: {
  4528. beginAtZero: true
  4529. }
  4530. },
  4531. // Boolean - Whether to animate the rotation of the chart
  4532. animation: {
  4533. animateRotate: true,
  4534. animateScale: true
  4535. },
  4536. startAngle: -0.5 * Math.PI,
  4537. legendCallback: function(chart) {
  4538. var text = [];
  4539. text.push('<ul class="' + chart.id + '-legend">');
  4540. var data = chart.data;
  4541. var datasets = data.datasets;
  4542. var labels = data.labels;
  4543. if (datasets.length) {
  4544. for (var i = 0; i < datasets[0].data.length; ++i) {
  4545. text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
  4546. if (labels[i]) {
  4547. text.push(labels[i]);
  4548. }
  4549. text.push('</li>');
  4550. }
  4551. }
  4552. text.push('</ul>');
  4553. return text.join('');
  4554. },
  4555. legend: {
  4556. labels: {
  4557. generateLabels: function(chart) {
  4558. var data = chart.data;
  4559. if (data.labels.length && data.datasets.length) {
  4560. return data.labels.map(function(label, i) {
  4561. var meta = chart.getDatasetMeta(0);
  4562. var ds = data.datasets[0];
  4563. var arc = meta.data[i];
  4564. var custom = arc.custom || {};
  4565. var arcOpts = chart.options.elements.arc;
  4566. var fill = resolve$5([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i);
  4567. var stroke = resolve$5([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i);
  4568. var bw = resolve$5([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i);
  4569. return {
  4570. text: label,
  4571. fillStyle: fill,
  4572. strokeStyle: stroke,
  4573. lineWidth: bw,
  4574. hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
  4575. // Extra data used for toggling the correct item
  4576. index: i
  4577. };
  4578. });
  4579. }
  4580. return [];
  4581. }
  4582. },
  4583. onClick: function(e, legendItem) {
  4584. var index = legendItem.index;
  4585. var chart = this.chart;
  4586. var i, ilen, meta;
  4587. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4588. meta = chart.getDatasetMeta(i);
  4589. meta.data[index].hidden = !meta.data[index].hidden;
  4590. }
  4591. chart.update();
  4592. }
  4593. },
  4594. // Need to override these to give a nice default
  4595. tooltips: {
  4596. callbacks: {
  4597. title: function() {
  4598. return '';
  4599. },
  4600. label: function(item, data) {
  4601. return data.labels[item.index] + ': ' + item.yLabel;
  4602. }
  4603. }
  4604. }
  4605. });
  4606. var controller_polarArea = core_datasetController.extend({
  4607. dataElementType: elements.Arc,
  4608. linkScales: helpers$1.noop,
  4609. update: function(reset) {
  4610. var me = this;
  4611. var dataset = me.getDataset();
  4612. var meta = me.getMeta();
  4613. var start = me.chart.options.startAngle || 0;
  4614. var starts = me._starts = [];
  4615. var angles = me._angles = [];
  4616. var arcs = meta.data;
  4617. var i, ilen, angle;
  4618. me._updateRadius();
  4619. meta.count = me.countVisibleElements();
  4620. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  4621. starts[i] = start;
  4622. angle = me._computeAngle(i);
  4623. angles[i] = angle;
  4624. start += angle;
  4625. }
  4626. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4627. arcs[i]._options = me._resolveElementOptions(arcs[i], i);
  4628. me.updateElement(arcs[i], i, reset);
  4629. }
  4630. },
  4631. /**
  4632. * @private
  4633. */
  4634. _updateRadius: function() {
  4635. var me = this;
  4636. var chart = me.chart;
  4637. var chartArea = chart.chartArea;
  4638. var opts = chart.options;
  4639. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  4640. chart.outerRadius = Math.max(minSize / 2, 0);
  4641. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  4642. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  4643. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  4644. me.innerRadius = me.outerRadius - chart.radiusLength;
  4645. },
  4646. updateElement: function(arc, index, reset) {
  4647. var me = this;
  4648. var chart = me.chart;
  4649. var dataset = me.getDataset();
  4650. var opts = chart.options;
  4651. var animationOpts = opts.animation;
  4652. var scale = chart.scale;
  4653. var labels = chart.data.labels;
  4654. var centerX = scale.xCenter;
  4655. var centerY = scale.yCenter;
  4656. // var negHalfPI = -0.5 * Math.PI;
  4657. var datasetStartAngle = opts.startAngle;
  4658. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  4659. var startAngle = me._starts[index];
  4660. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  4661. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  4662. var options = arc._options || {};
  4663. helpers$1.extend(arc, {
  4664. // Utility
  4665. _datasetIndex: me.index,
  4666. _index: index,
  4667. _scale: scale,
  4668. // Desired view properties
  4669. _model: {
  4670. backgroundColor: options.backgroundColor,
  4671. borderColor: options.borderColor,
  4672. borderWidth: options.borderWidth,
  4673. borderAlign: options.borderAlign,
  4674. x: centerX,
  4675. y: centerY,
  4676. innerRadius: 0,
  4677. outerRadius: reset ? resetRadius : distance,
  4678. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  4679. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  4680. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  4681. }
  4682. });
  4683. arc.pivot();
  4684. },
  4685. countVisibleElements: function() {
  4686. var dataset = this.getDataset();
  4687. var meta = this.getMeta();
  4688. var count = 0;
  4689. helpers$1.each(meta.data, function(element, index) {
  4690. if (!isNaN(dataset.data[index]) && !element.hidden) {
  4691. count++;
  4692. }
  4693. });
  4694. return count;
  4695. },
  4696. /**
  4697. * @protected
  4698. */
  4699. setHoverStyle: function(arc) {
  4700. var model = arc._model;
  4701. var options = arc._options;
  4702. var getHoverColor = helpers$1.getHoverColor;
  4703. var valueOrDefault = helpers$1.valueOrDefault;
  4704. arc.$previousStyle = {
  4705. backgroundColor: model.backgroundColor,
  4706. borderColor: model.borderColor,
  4707. borderWidth: model.borderWidth,
  4708. };
  4709. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4710. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  4711. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  4712. },
  4713. /**
  4714. * @private
  4715. */
  4716. _resolveElementOptions: function(arc, index) {
  4717. var me = this;
  4718. var chart = me.chart;
  4719. var dataset = me.getDataset();
  4720. var custom = arc.custom || {};
  4721. var options = chart.options.elements.arc;
  4722. var values = {};
  4723. var i, ilen, key;
  4724. // Scriptable options
  4725. var context = {
  4726. chart: chart,
  4727. dataIndex: index,
  4728. dataset: dataset,
  4729. datasetIndex: me.index
  4730. };
  4731. var keys = [
  4732. 'backgroundColor',
  4733. 'borderColor',
  4734. 'borderWidth',
  4735. 'borderAlign',
  4736. 'hoverBackgroundColor',
  4737. 'hoverBorderColor',
  4738. 'hoverBorderWidth',
  4739. ];
  4740. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4741. key = keys[i];
  4742. values[key] = resolve$5([
  4743. custom[key],
  4744. dataset[key],
  4745. options[key]
  4746. ], context, index);
  4747. }
  4748. return values;
  4749. },
  4750. /**
  4751. * @private
  4752. */
  4753. _computeAngle: function(index) {
  4754. var me = this;
  4755. var count = this.getMeta().count;
  4756. var dataset = me.getDataset();
  4757. var meta = me.getMeta();
  4758. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  4759. return 0;
  4760. }
  4761. // Scriptable options
  4762. var context = {
  4763. chart: me.chart,
  4764. dataIndex: index,
  4765. dataset: dataset,
  4766. datasetIndex: me.index
  4767. };
  4768. return resolve$5([
  4769. me.chart.options.elements.arc.angle,
  4770. (2 * Math.PI) / count
  4771. ], context, index);
  4772. }
  4773. });
  4774. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  4775. core_defaults._set('pie', {
  4776. cutoutPercentage: 0
  4777. });
  4778. // Pie charts are Doughnut chart with different defaults
  4779. var controller_pie = controller_doughnut;
  4780. var valueOrDefault$6 = helpers$1.valueOrDefault;
  4781. var resolve$6 = helpers$1.options.resolve;
  4782. core_defaults._set('radar', {
  4783. scale: {
  4784. type: 'radialLinear'
  4785. },
  4786. elements: {
  4787. line: {
  4788. tension: 0 // no bezier in radar
  4789. }
  4790. }
  4791. });
  4792. var controller_radar = core_datasetController.extend({
  4793. datasetElementType: elements.Line,
  4794. dataElementType: elements.Point,
  4795. linkScales: helpers$1.noop,
  4796. update: function(reset) {
  4797. var me = this;
  4798. var meta = me.getMeta();
  4799. var line = meta.dataset;
  4800. var points = meta.data || [];
  4801. var scale = me.chart.scale;
  4802. var dataset = me.getDataset();
  4803. var i, ilen;
  4804. // Compatibility: If the properties are defined with only the old name, use those values
  4805. if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
  4806. dataset.lineTension = dataset.tension;
  4807. }
  4808. // Utility
  4809. line._scale = scale;
  4810. line._datasetIndex = me.index;
  4811. // Data
  4812. line._children = points;
  4813. line._loop = true;
  4814. // Model
  4815. line._model = me._resolveLineOptions(line);
  4816. line.pivot();
  4817. // Update Points
  4818. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4819. me.updateElement(points[i], i, reset);
  4820. }
  4821. // Update bezier control points
  4822. me.updateBezierControlPoints();
  4823. // Now pivot the point for animation
  4824. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4825. points[i].pivot();
  4826. }
  4827. },
  4828. updateElement: function(point, index, reset) {
  4829. var me = this;
  4830. var custom = point.custom || {};
  4831. var dataset = me.getDataset();
  4832. var scale = me.chart.scale;
  4833. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  4834. var options = me._resolvePointOptions(point, index);
  4835. var lineModel = me.getMeta().dataset._model;
  4836. var x = reset ? scale.xCenter : pointPosition.x;
  4837. var y = reset ? scale.yCenter : pointPosition.y;
  4838. // Utility
  4839. point._scale = scale;
  4840. point._options = options;
  4841. point._datasetIndex = me.index;
  4842. point._index = index;
  4843. // Desired view properties
  4844. point._model = {
  4845. x: x, // value not used in dataset scale, but we want a consistent API between scales
  4846. y: y,
  4847. skip: custom.skip || isNaN(x) || isNaN(y),
  4848. // Appearance
  4849. radius: options.radius,
  4850. pointStyle: options.pointStyle,
  4851. rotation: options.rotation,
  4852. backgroundColor: options.backgroundColor,
  4853. borderColor: options.borderColor,
  4854. borderWidth: options.borderWidth,
  4855. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  4856. // Tooltip
  4857. hitRadius: options.hitRadius
  4858. };
  4859. },
  4860. /**
  4861. * @private
  4862. */
  4863. _resolvePointOptions: function(element, index) {
  4864. var me = this;
  4865. var chart = me.chart;
  4866. var dataset = chart.data.datasets[me.index];
  4867. var custom = element.custom || {};
  4868. var options = chart.options.elements.point;
  4869. var values = {};
  4870. var i, ilen, key;
  4871. // Scriptable options
  4872. var context = {
  4873. chart: chart,
  4874. dataIndex: index,
  4875. dataset: dataset,
  4876. datasetIndex: me.index
  4877. };
  4878. var ELEMENT_OPTIONS = {
  4879. backgroundColor: 'pointBackgroundColor',
  4880. borderColor: 'pointBorderColor',
  4881. borderWidth: 'pointBorderWidth',
  4882. hitRadius: 'pointHitRadius',
  4883. hoverBackgroundColor: 'pointHoverBackgroundColor',
  4884. hoverBorderColor: 'pointHoverBorderColor',
  4885. hoverBorderWidth: 'pointHoverBorderWidth',
  4886. hoverRadius: 'pointHoverRadius',
  4887. pointStyle: 'pointStyle',
  4888. radius: 'pointRadius',
  4889. rotation: 'pointRotation'
  4890. };
  4891. var keys = Object.keys(ELEMENT_OPTIONS);
  4892. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4893. key = keys[i];
  4894. values[key] = resolve$6([
  4895. custom[key],
  4896. dataset[ELEMENT_OPTIONS[key]],
  4897. dataset[key],
  4898. options[key]
  4899. ], context, index);
  4900. }
  4901. return values;
  4902. },
  4903. /**
  4904. * @private
  4905. */
  4906. _resolveLineOptions: function(element) {
  4907. var me = this;
  4908. var chart = me.chart;
  4909. var dataset = chart.data.datasets[me.index];
  4910. var custom = element.custom || {};
  4911. var options = chart.options.elements.line;
  4912. var values = {};
  4913. var i, ilen, key;
  4914. var keys = [
  4915. 'backgroundColor',
  4916. 'borderWidth',
  4917. 'borderColor',
  4918. 'borderCapStyle',
  4919. 'borderDash',
  4920. 'borderDashOffset',
  4921. 'borderJoinStyle',
  4922. 'fill'
  4923. ];
  4924. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4925. key = keys[i];
  4926. values[key] = resolve$6([
  4927. custom[key],
  4928. dataset[key],
  4929. options[key]
  4930. ]);
  4931. }
  4932. values.tension = valueOrDefault$6(dataset.lineTension, options.tension);
  4933. return values;
  4934. },
  4935. updateBezierControlPoints: function() {
  4936. var me = this;
  4937. var meta = me.getMeta();
  4938. var area = me.chart.chartArea;
  4939. var points = meta.data || [];
  4940. var i, ilen, model, controlPoints;
  4941. function capControlPoint(pt, min, max) {
  4942. return Math.max(Math.min(pt, max), min);
  4943. }
  4944. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4945. model = points[i]._model;
  4946. controlPoints = helpers$1.splineCurve(
  4947. helpers$1.previousItem(points, i, true)._model,
  4948. model,
  4949. helpers$1.nextItem(points, i, true)._model,
  4950. model.tension
  4951. );
  4952. // Prevent the bezier going outside of the bounds of the graph
  4953. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  4954. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  4955. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  4956. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  4957. }
  4958. },
  4959. setHoverStyle: function(point) {
  4960. var model = point._model;
  4961. var options = point._options;
  4962. var getHoverColor = helpers$1.getHoverColor;
  4963. point.$previousStyle = {
  4964. backgroundColor: model.backgroundColor,
  4965. borderColor: model.borderColor,
  4966. borderWidth: model.borderWidth,
  4967. radius: model.radius
  4968. };
  4969. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4970. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  4971. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  4972. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  4973. }
  4974. });
  4975. core_defaults._set('scatter', {
  4976. hover: {
  4977. mode: 'single'
  4978. },
  4979. scales: {
  4980. xAxes: [{
  4981. id: 'x-axis-1', // need an ID so datasets can reference the scale
  4982. type: 'linear', // scatter should not use a category axis
  4983. position: 'bottom'
  4984. }],
  4985. yAxes: [{
  4986. id: 'y-axis-1',
  4987. type: 'linear',
  4988. position: 'left'
  4989. }]
  4990. },
  4991. showLines: false,
  4992. tooltips: {
  4993. callbacks: {
  4994. title: function() {
  4995. return ''; // doesn't make sense for scatter since data are formatted as a point
  4996. },
  4997. label: function(item) {
  4998. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  4999. }
  5000. }
  5001. }
  5002. });
  5003. // Scatter charts use line controllers
  5004. var controller_scatter = controller_line;
  5005. // NOTE export a map in which the key represents the controller type, not
  5006. // the class, and so must be CamelCase in order to be correctly retrieved
  5007. // by the controller in core.controller.js (`controllers[meta.type]`).
  5008. var controllers = {
  5009. bar: controller_bar,
  5010. bubble: controller_bubble,
  5011. doughnut: controller_doughnut,
  5012. horizontalBar: controller_horizontalBar,
  5013. line: controller_line,
  5014. polarArea: controller_polarArea,
  5015. pie: controller_pie,
  5016. radar: controller_radar,
  5017. scatter: controller_scatter
  5018. };
  5019. /**
  5020. * Helper function to get relative position for an event
  5021. * @param {Event|IEvent} event - The event to get the position for
  5022. * @param {Chart} chart - The chart
  5023. * @returns {object} the event position
  5024. */
  5025. function getRelativePosition(e, chart) {
  5026. if (e.native) {
  5027. return {
  5028. x: e.x,
  5029. y: e.y
  5030. };
  5031. }
  5032. return helpers$1.getRelativePosition(e, chart);
  5033. }
  5034. /**
  5035. * Helper function to traverse all of the visible elements in the chart
  5036. * @param {Chart} chart - the chart
  5037. * @param {function} handler - the callback to execute for each visible item
  5038. */
  5039. function parseVisibleItems(chart, handler) {
  5040. var datasets = chart.data.datasets;
  5041. var meta, i, j, ilen, jlen;
  5042. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  5043. if (!chart.isDatasetVisible(i)) {
  5044. continue;
  5045. }
  5046. meta = chart.getDatasetMeta(i);
  5047. for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
  5048. var element = meta.data[j];
  5049. if (!element._view.skip) {
  5050. handler(element);
  5051. }
  5052. }
  5053. }
  5054. }
  5055. /**
  5056. * Helper function to get the items that intersect the event position
  5057. * @param {ChartElement[]} items - elements to filter
  5058. * @param {object} position - the point to be nearest to
  5059. * @return {ChartElement[]} the nearest items
  5060. */
  5061. function getIntersectItems(chart, position) {
  5062. var elements = [];
  5063. parseVisibleItems(chart, function(element) {
  5064. if (element.inRange(position.x, position.y)) {
  5065. elements.push(element);
  5066. }
  5067. });
  5068. return elements;
  5069. }
  5070. /**
  5071. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5072. * @param {Chart} chart - the chart to look at elements from
  5073. * @param {object} position - the point to be nearest to
  5074. * @param {boolean} intersect - if true, only consider items that intersect the position
  5075. * @param {function} distanceMetric - function to provide the distance between points
  5076. * @return {ChartElement[]} the nearest items
  5077. */
  5078. function getNearestItems(chart, position, intersect, distanceMetric) {
  5079. var minDistance = Number.POSITIVE_INFINITY;
  5080. var nearestItems = [];
  5081. parseVisibleItems(chart, function(element) {
  5082. if (intersect && !element.inRange(position.x, position.y)) {
  5083. return;
  5084. }
  5085. var center = element.getCenterPoint();
  5086. var distance = distanceMetric(position, center);
  5087. if (distance < minDistance) {
  5088. nearestItems = [element];
  5089. minDistance = distance;
  5090. } else if (distance === minDistance) {
  5091. // Can have multiple items at the same distance in which case we sort by size
  5092. nearestItems.push(element);
  5093. }
  5094. });
  5095. return nearestItems;
  5096. }
  5097. /**
  5098. * Get a distance metric function for two points based on the
  5099. * axis mode setting
  5100. * @param {string} axis - the axis mode. x|y|xy
  5101. */
  5102. function getDistanceMetricForAxis(axis) {
  5103. var useX = axis.indexOf('x') !== -1;
  5104. var useY = axis.indexOf('y') !== -1;
  5105. return function(pt1, pt2) {
  5106. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5107. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5108. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5109. };
  5110. }
  5111. function indexMode(chart, e, options) {
  5112. var position = getRelativePosition(e, chart);
  5113. // Default axis for index mode is 'x' to match old behaviour
  5114. options.axis = options.axis || 'x';
  5115. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5116. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5117. var elements = [];
  5118. if (!items.length) {
  5119. return [];
  5120. }
  5121. chart.data.datasets.forEach(function(dataset, datasetIndex) {
  5122. if (chart.isDatasetVisible(datasetIndex)) {
  5123. var meta = chart.getDatasetMeta(datasetIndex);
  5124. var element = meta.data[items[0]._index];
  5125. // don't count items that are skipped (null data)
  5126. if (element && !element._view.skip) {
  5127. elements.push(element);
  5128. }
  5129. }
  5130. });
  5131. return elements;
  5132. }
  5133. /**
  5134. * @interface IInteractionOptions
  5135. */
  5136. /**
  5137. * If true, only consider items that intersect the point
  5138. * @name IInterfaceOptions#boolean
  5139. * @type Boolean
  5140. */
  5141. /**
  5142. * Contains interaction related functions
  5143. * @namespace Chart.Interaction
  5144. */
  5145. var core_interaction = {
  5146. // Helper function for different modes
  5147. modes: {
  5148. single: function(chart, e) {
  5149. var position = getRelativePosition(e, chart);
  5150. var elements = [];
  5151. parseVisibleItems(chart, function(element) {
  5152. if (element.inRange(position.x, position.y)) {
  5153. elements.push(element);
  5154. return elements;
  5155. }
  5156. });
  5157. return elements.slice(0, 1);
  5158. },
  5159. /**
  5160. * @function Chart.Interaction.modes.label
  5161. * @deprecated since version 2.4.0
  5162. * @todo remove at version 3
  5163. * @private
  5164. */
  5165. label: indexMode,
  5166. /**
  5167. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5168. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5169. * @function Chart.Interaction.modes.index
  5170. * @since v2.4.0
  5171. * @param {Chart} chart - the chart we are returning items from
  5172. * @param {Event} e - the event we are find things at
  5173. * @param {IInteractionOptions} options - options to use during interaction
  5174. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5175. */
  5176. index: indexMode,
  5177. /**
  5178. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5179. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5180. * @function Chart.Interaction.modes.dataset
  5181. * @param {Chart} chart - the chart we are returning items from
  5182. * @param {Event} e - the event we are find things at
  5183. * @param {IInteractionOptions} options - options to use during interaction
  5184. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5185. */
  5186. dataset: function(chart, e, options) {
  5187. var position = getRelativePosition(e, chart);
  5188. options.axis = options.axis || 'xy';
  5189. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5190. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5191. if (items.length > 0) {
  5192. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5193. }
  5194. return items;
  5195. },
  5196. /**
  5197. * @function Chart.Interaction.modes.x-axis
  5198. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5199. * @todo remove at version 3
  5200. * @private
  5201. */
  5202. 'x-axis': function(chart, e) {
  5203. return indexMode(chart, e, {intersect: false});
  5204. },
  5205. /**
  5206. * Point mode returns all elements that hit test based on the event position
  5207. * of the event
  5208. * @function Chart.Interaction.modes.intersect
  5209. * @param {Chart} chart - the chart we are returning items from
  5210. * @param {Event} e - the event we are find things at
  5211. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5212. */
  5213. point: function(chart, e) {
  5214. var position = getRelativePosition(e, chart);
  5215. return getIntersectItems(chart, position);
  5216. },
  5217. /**
  5218. * nearest mode returns the element closest to the point
  5219. * @function Chart.Interaction.modes.intersect
  5220. * @param {Chart} chart - the chart we are returning items from
  5221. * @param {Event} e - the event we are find things at
  5222. * @param {IInteractionOptions} options - options to use
  5223. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5224. */
  5225. nearest: function(chart, e, options) {
  5226. var position = getRelativePosition(e, chart);
  5227. options.axis = options.axis || 'xy';
  5228. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5229. return getNearestItems(chart, position, options.intersect, distanceMetric);
  5230. },
  5231. /**
  5232. * x mode returns the elements that hit-test at the current x coordinate
  5233. * @function Chart.Interaction.modes.x
  5234. * @param {Chart} chart - the chart we are returning items from
  5235. * @param {Event} e - the event we are find things at
  5236. * @param {IInteractionOptions} options - options to use
  5237. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5238. */
  5239. x: function(chart, e, options) {
  5240. var position = getRelativePosition(e, chart);
  5241. var items = [];
  5242. var intersectsItem = false;
  5243. parseVisibleItems(chart, function(element) {
  5244. if (element.inXRange(position.x)) {
  5245. items.push(element);
  5246. }
  5247. if (element.inRange(position.x, position.y)) {
  5248. intersectsItem = true;
  5249. }
  5250. });
  5251. // If we want to trigger on an intersect and we don't have any items
  5252. // that intersect the position, return nothing
  5253. if (options.intersect && !intersectsItem) {
  5254. items = [];
  5255. }
  5256. return items;
  5257. },
  5258. /**
  5259. * y mode returns the elements that hit-test at the current y coordinate
  5260. * @function Chart.Interaction.modes.y
  5261. * @param {Chart} chart - the chart we are returning items from
  5262. * @param {Event} e - the event we are find things at
  5263. * @param {IInteractionOptions} options - options to use
  5264. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5265. */
  5266. y: function(chart, e, options) {
  5267. var position = getRelativePosition(e, chart);
  5268. var items = [];
  5269. var intersectsItem = false;
  5270. parseVisibleItems(chart, function(element) {
  5271. if (element.inYRange(position.y)) {
  5272. items.push(element);
  5273. }
  5274. if (element.inRange(position.x, position.y)) {
  5275. intersectsItem = true;
  5276. }
  5277. });
  5278. // If we want to trigger on an intersect and we don't have any items
  5279. // that intersect the position, return nothing
  5280. if (options.intersect && !intersectsItem) {
  5281. items = [];
  5282. }
  5283. return items;
  5284. }
  5285. }
  5286. };
  5287. function filterByPosition(array, position) {
  5288. return helpers$1.where(array, function(v) {
  5289. return v.position === position;
  5290. });
  5291. }
  5292. function sortByWeight(array, reverse) {
  5293. array.forEach(function(v, i) {
  5294. v._tmpIndex_ = i;
  5295. return v;
  5296. });
  5297. array.sort(function(a, b) {
  5298. var v0 = reverse ? b : a;
  5299. var v1 = reverse ? a : b;
  5300. return v0.weight === v1.weight ?
  5301. v0._tmpIndex_ - v1._tmpIndex_ :
  5302. v0.weight - v1.weight;
  5303. });
  5304. array.forEach(function(v) {
  5305. delete v._tmpIndex_;
  5306. });
  5307. }
  5308. function findMaxPadding(boxes) {
  5309. var top = 0;
  5310. var left = 0;
  5311. var bottom = 0;
  5312. var right = 0;
  5313. helpers$1.each(boxes, function(box) {
  5314. if (box.getPadding) {
  5315. var boxPadding = box.getPadding();
  5316. top = Math.max(top, boxPadding.top);
  5317. left = Math.max(left, boxPadding.left);
  5318. bottom = Math.max(bottom, boxPadding.bottom);
  5319. right = Math.max(right, boxPadding.right);
  5320. }
  5321. });
  5322. return {
  5323. top: top,
  5324. left: left,
  5325. bottom: bottom,
  5326. right: right
  5327. };
  5328. }
  5329. function addSizeByPosition(boxes, size) {
  5330. helpers$1.each(boxes, function(box) {
  5331. size[box.position] += box.isHorizontal() ? box.height : box.width;
  5332. });
  5333. }
  5334. core_defaults._set('global', {
  5335. layout: {
  5336. padding: {
  5337. top: 0,
  5338. right: 0,
  5339. bottom: 0,
  5340. left: 0
  5341. }
  5342. }
  5343. });
  5344. /**
  5345. * @interface ILayoutItem
  5346. * @prop {string} position - The position of the item in the chart layout. Possible values are
  5347. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  5348. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  5349. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  5350. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  5351. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  5352. * @prop {function} getPadding - Returns an object with padding on the edges
  5353. * @prop {number} width - Width of item. Must be valid after update()
  5354. * @prop {number} height - Height of item. Must be valid after update()
  5355. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  5356. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  5357. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  5358. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  5359. */
  5360. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  5361. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  5362. // It is this service's responsibility of carrying out that layout.
  5363. var core_layouts = {
  5364. defaults: {},
  5365. /**
  5366. * Register a box to a chart.
  5367. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  5368. * @param {Chart} chart - the chart to use
  5369. * @param {ILayoutItem} item - the item to add to be layed out
  5370. */
  5371. addBox: function(chart, item) {
  5372. if (!chart.boxes) {
  5373. chart.boxes = [];
  5374. }
  5375. // initialize item with default values
  5376. item.fullWidth = item.fullWidth || false;
  5377. item.position = item.position || 'top';
  5378. item.weight = item.weight || 0;
  5379. chart.boxes.push(item);
  5380. },
  5381. /**
  5382. * Remove a layoutItem from a chart
  5383. * @param {Chart} chart - the chart to remove the box from
  5384. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  5385. */
  5386. removeBox: function(chart, layoutItem) {
  5387. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  5388. if (index !== -1) {
  5389. chart.boxes.splice(index, 1);
  5390. }
  5391. },
  5392. /**
  5393. * Sets (or updates) options on the given `item`.
  5394. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  5395. * @param {ILayoutItem} item - the item to configure with the given options
  5396. * @param {object} options - the new item options.
  5397. */
  5398. configure: function(chart, item, options) {
  5399. var props = ['fullWidth', 'position', 'weight'];
  5400. var ilen = props.length;
  5401. var i = 0;
  5402. var prop;
  5403. for (; i < ilen; ++i) {
  5404. prop = props[i];
  5405. if (options.hasOwnProperty(prop)) {
  5406. item[prop] = options[prop];
  5407. }
  5408. }
  5409. },
  5410. /**
  5411. * Fits boxes of the given chart into the given size by having each box measure itself
  5412. * then running a fitting algorithm
  5413. * @param {Chart} chart - the chart
  5414. * @param {number} width - the width to fit into
  5415. * @param {number} height - the height to fit into
  5416. */
  5417. update: function(chart, width, height) {
  5418. if (!chart) {
  5419. return;
  5420. }
  5421. var layoutOptions = chart.options.layout || {};
  5422. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  5423. var leftPadding = padding.left;
  5424. var rightPadding = padding.right;
  5425. var topPadding = padding.top;
  5426. var bottomPadding = padding.bottom;
  5427. var leftBoxes = filterByPosition(chart.boxes, 'left');
  5428. var rightBoxes = filterByPosition(chart.boxes, 'right');
  5429. var topBoxes = filterByPosition(chart.boxes, 'top');
  5430. var bottomBoxes = filterByPosition(chart.boxes, 'bottom');
  5431. var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');
  5432. // Sort boxes by weight. A higher weight is further away from the chart area
  5433. sortByWeight(leftBoxes, true);
  5434. sortByWeight(rightBoxes, false);
  5435. sortByWeight(topBoxes, true);
  5436. sortByWeight(bottomBoxes, false);
  5437. var verticalBoxes = leftBoxes.concat(rightBoxes);
  5438. var horizontalBoxes = topBoxes.concat(bottomBoxes);
  5439. var outerBoxes = verticalBoxes.concat(horizontalBoxes);
  5440. // Essentially we now have any number of boxes on each of the 4 sides.
  5441. // Our canvas looks like the following.
  5442. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  5443. // B1 is the bottom axis
  5444. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  5445. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  5446. // an error will be thrown.
  5447. //
  5448. // |----------------------------------------------------|
  5449. // | T1 (Full Width) |
  5450. // |----------------------------------------------------|
  5451. // | | | T2 | |
  5452. // | |----|-------------------------------------|----|
  5453. // | | | C1 | | C2 | |
  5454. // | | |----| |----| |
  5455. // | | | | |
  5456. // | L1 | L2 | ChartArea (C0) | R1 |
  5457. // | | | | |
  5458. // | | |----| |----| |
  5459. // | | | C3 | | C4 | |
  5460. // | |----|-------------------------------------|----|
  5461. // | | | B1 | |
  5462. // |----------------------------------------------------|
  5463. // | B2 (Full Width) |
  5464. // |----------------------------------------------------|
  5465. //
  5466. // What we do to find the best sizing, we do the following
  5467. // 1. Determine the minimum size of the chart area.
  5468. // 2. Split the remaining width equally between each vertical axis
  5469. // 3. Split the remaining height equally between each horizontal axis
  5470. // 4. Give each layout the maximum size it can be. The layout will return it's minimum size
  5471. // 5. Adjust the sizes of each axis based on it's minimum reported size.
  5472. // 6. Refit each axis
  5473. // 7. Position each axis in the final location
  5474. // 8. Tell the chart the final location of the chart area
  5475. // 9. Tell any axes that overlay the chart area the positions of the chart area
  5476. // Step 1
  5477. var chartWidth = width - leftPadding - rightPadding;
  5478. var chartHeight = height - topPadding - bottomPadding;
  5479. var chartAreaWidth = chartWidth / 2; // min 50%
  5480. // Step 2
  5481. var verticalBoxWidth = (width - chartAreaWidth) / verticalBoxes.length;
  5482. // Step 3
  5483. // TODO re-limit horizontal axis height (this limit has affected only padding calculation since PR 1837)
  5484. // var horizontalBoxHeight = (height - chartAreaHeight) / horizontalBoxes.length;
  5485. // Step 4
  5486. var maxChartAreaWidth = chartWidth;
  5487. var maxChartAreaHeight = chartHeight;
  5488. var outerBoxSizes = {top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding};
  5489. var minBoxSizes = [];
  5490. var maxPadding;
  5491. function getMinimumBoxSize(box) {
  5492. var minSize;
  5493. var isHorizontal = box.isHorizontal();
  5494. if (isHorizontal) {
  5495. minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2);
  5496. maxChartAreaHeight -= minSize.height;
  5497. } else {
  5498. minSize = box.update(verticalBoxWidth, maxChartAreaHeight);
  5499. maxChartAreaWidth -= minSize.width;
  5500. }
  5501. minBoxSizes.push({
  5502. horizontal: isHorizontal,
  5503. width: minSize.width,
  5504. box: box,
  5505. });
  5506. }
  5507. helpers$1.each(outerBoxes, getMinimumBoxSize);
  5508. // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
  5509. maxPadding = findMaxPadding(outerBoxes);
  5510. // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
  5511. // be if the axes are drawn at their minimum sizes.
  5512. // Steps 5 & 6
  5513. // Function to fit a box
  5514. function fitBox(box) {
  5515. var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minBox) {
  5516. return minBox.box === box;
  5517. });
  5518. if (minBoxSize) {
  5519. if (minBoxSize.horizontal) {
  5520. var scaleMargin = {
  5521. left: Math.max(outerBoxSizes.left, maxPadding.left),
  5522. right: Math.max(outerBoxSizes.right, maxPadding.right),
  5523. top: 0,
  5524. bottom: 0
  5525. };
  5526. // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
  5527. // on the margin. Sometimes they need to increase in size slightly
  5528. box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
  5529. } else {
  5530. box.update(minBoxSize.width, maxChartAreaHeight);
  5531. }
  5532. }
  5533. }
  5534. // Update, and calculate the left and right margins for the horizontal boxes
  5535. helpers$1.each(verticalBoxes, fitBox);
  5536. addSizeByPosition(verticalBoxes, outerBoxSizes);
  5537. // Set the Left and Right margins for the horizontal boxes
  5538. helpers$1.each(horizontalBoxes, fitBox);
  5539. addSizeByPosition(horizontalBoxes, outerBoxSizes);
  5540. function finalFitVerticalBox(box) {
  5541. var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minSize) {
  5542. return minSize.box === box;
  5543. });
  5544. var scaleMargin = {
  5545. left: 0,
  5546. right: 0,
  5547. top: outerBoxSizes.top,
  5548. bottom: outerBoxSizes.bottom
  5549. };
  5550. if (minBoxSize) {
  5551. box.update(minBoxSize.width, maxChartAreaHeight, scaleMargin);
  5552. }
  5553. }
  5554. // Let the left layout know the final margin
  5555. helpers$1.each(verticalBoxes, finalFitVerticalBox);
  5556. // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
  5557. outerBoxSizes = {top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding};
  5558. addSizeByPosition(outerBoxes, outerBoxSizes);
  5559. // We may be adding some padding to account for rotated x axis labels
  5560. var leftPaddingAddition = Math.max(maxPadding.left - outerBoxSizes.left, 0);
  5561. outerBoxSizes.left += leftPaddingAddition;
  5562. outerBoxSizes.right += Math.max(maxPadding.right - outerBoxSizes.right, 0);
  5563. var topPaddingAddition = Math.max(maxPadding.top - outerBoxSizes.top, 0);
  5564. outerBoxSizes.top += topPaddingAddition;
  5565. outerBoxSizes.bottom += Math.max(maxPadding.bottom - outerBoxSizes.bottom, 0);
  5566. // Figure out if our chart area changed. This would occur if the dataset layout label rotation
  5567. // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
  5568. // without calling `fit` again
  5569. var newMaxChartAreaHeight = height - outerBoxSizes.top - outerBoxSizes.bottom;
  5570. var newMaxChartAreaWidth = width - outerBoxSizes.left - outerBoxSizes.right;
  5571. if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
  5572. helpers$1.each(verticalBoxes, function(box) {
  5573. box.height = newMaxChartAreaHeight;
  5574. });
  5575. helpers$1.each(horizontalBoxes, function(box) {
  5576. if (!box.fullWidth) {
  5577. box.width = newMaxChartAreaWidth;
  5578. }
  5579. });
  5580. maxChartAreaHeight = newMaxChartAreaHeight;
  5581. maxChartAreaWidth = newMaxChartAreaWidth;
  5582. }
  5583. // Step 7 - Position the boxes
  5584. var left = leftPadding + leftPaddingAddition;
  5585. var top = topPadding + topPaddingAddition;
  5586. function placeBox(box) {
  5587. if (box.isHorizontal()) {
  5588. box.left = box.fullWidth ? leftPadding : outerBoxSizes.left;
  5589. box.right = box.fullWidth ? width - rightPadding : outerBoxSizes.left + maxChartAreaWidth;
  5590. box.top = top;
  5591. box.bottom = top + box.height;
  5592. // Move to next point
  5593. top = box.bottom;
  5594. } else {
  5595. box.left = left;
  5596. box.right = left + box.width;
  5597. box.top = outerBoxSizes.top;
  5598. box.bottom = outerBoxSizes.top + maxChartAreaHeight;
  5599. // Move to next point
  5600. left = box.right;
  5601. }
  5602. }
  5603. helpers$1.each(leftBoxes.concat(topBoxes), placeBox);
  5604. // Account for chart width and height
  5605. left += maxChartAreaWidth;
  5606. top += maxChartAreaHeight;
  5607. helpers$1.each(rightBoxes, placeBox);
  5608. helpers$1.each(bottomBoxes, placeBox);
  5609. // Step 8
  5610. chart.chartArea = {
  5611. left: outerBoxSizes.left,
  5612. top: outerBoxSizes.top,
  5613. right: outerBoxSizes.left + maxChartAreaWidth,
  5614. bottom: outerBoxSizes.top + maxChartAreaHeight
  5615. };
  5616. // Step 9
  5617. helpers$1.each(chartAreaBoxes, function(box) {
  5618. box.left = chart.chartArea.left;
  5619. box.top = chart.chartArea.top;
  5620. box.right = chart.chartArea.right;
  5621. box.bottom = chart.chartArea.bottom;
  5622. box.update(maxChartAreaWidth, maxChartAreaHeight);
  5623. });
  5624. }
  5625. };
  5626. /**
  5627. * Platform fallback implementation (minimal).
  5628. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  5629. */
  5630. var platform_basic = {
  5631. acquireContext: function(item) {
  5632. if (item && item.canvas) {
  5633. // Support for any object associated to a canvas (including a context2d)
  5634. item = item.canvas;
  5635. }
  5636. return item && item.getContext('2d') || null;
  5637. }
  5638. };
  5639. var platform_dom = "/*\n * DOM element rendering detection\n * https://davidwalsh.name/detect-node-insertion\n */\n@keyframes chartjs-render-animation {\n\tfrom { opacity: 0.99; }\n\tto { opacity: 1; }\n}\n\n.chartjs-render-monitor {\n\tanimation: chartjs-render-animation 0.001s;\n}\n\n/*\n * DOM element resizing detection\n * https://github.com/marcj/css-element-queries\n */\n.chartjs-size-monitor,\n.chartjs-size-monitor-expand,\n.chartjs-size-monitor-shrink {\n\tposition: absolute;\n\tdirection: ltr;\n\tleft: 0;\n\ttop: 0;\n\tright: 0;\n\tbottom: 0;\n\toverflow: hidden;\n\tpointer-events: none;\n\tvisibility: hidden;\n\tz-index: -1;\n}\n\n.chartjs-size-monitor-expand > div {\n\tposition: absolute;\n\twidth: 1000000px;\n\theight: 1000000px;\n\tleft: 0;\n\ttop: 0;\n}\n\n.chartjs-size-monitor-shrink > div {\n\tposition: absolute;\n\twidth: 200%;\n\theight: 200%;\n\tleft: 0;\n\ttop: 0;\n}\n";
  5640. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  5641. default: platform_dom
  5642. });
  5643. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  5644. function commonjsRequire () {
  5645. throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
  5646. }
  5647. function createCommonjsModule(fn, module) {
  5648. return module = { exports: {} }, fn(module, module.exports), module.exports;
  5649. }
  5650. function getCjsExportFromNamespace (n) {
  5651. return n && n.default || n;
  5652. }
  5653. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  5654. var EXPANDO_KEY = '$chartjs';
  5655. var CSS_PREFIX = 'chartjs-';
  5656. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  5657. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  5658. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  5659. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  5660. /**
  5661. * DOM event types -> Chart.js event types.
  5662. * Note: only events with different types are mapped.
  5663. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  5664. */
  5665. var EVENT_TYPES = {
  5666. touchstart: 'mousedown',
  5667. touchmove: 'mousemove',
  5668. touchend: 'mouseup',
  5669. pointerenter: 'mouseenter',
  5670. pointerdown: 'mousedown',
  5671. pointermove: 'mousemove',
  5672. pointerup: 'mouseup',
  5673. pointerleave: 'mouseout',
  5674. pointerout: 'mouseout'
  5675. };
  5676. /**
  5677. * The "used" size is the final value of a dimension property after all calculations have
  5678. * been performed. This method uses the computed style of `element` but returns undefined
  5679. * if the computed style is not expressed in pixels. That can happen in some cases where
  5680. * `element` has a size relative to its parent and this last one is not yet displayed,
  5681. * for example because of `display: none` on a parent node.
  5682. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  5683. * @returns {number} Size in pixels or undefined if unknown.
  5684. */
  5685. function readUsedSize(element, property) {
  5686. var value = helpers$1.getStyle(element, property);
  5687. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  5688. return matches ? Number(matches[1]) : undefined;
  5689. }
  5690. /**
  5691. * Initializes the canvas style and render size without modifying the canvas display size,
  5692. * since responsiveness is handled by the controller.resize() method. The config is used
  5693. * to determine the aspect ratio to apply in case no explicit height has been specified.
  5694. */
  5695. function initCanvas(canvas, config) {
  5696. var style = canvas.style;
  5697. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  5698. // returns null or '' if no explicit value has been set to the canvas attribute.
  5699. var renderHeight = canvas.getAttribute('height');
  5700. var renderWidth = canvas.getAttribute('width');
  5701. // Chart.js modifies some canvas values that we want to restore on destroy
  5702. canvas[EXPANDO_KEY] = {
  5703. initial: {
  5704. height: renderHeight,
  5705. width: renderWidth,
  5706. style: {
  5707. display: style.display,
  5708. height: style.height,
  5709. width: style.width
  5710. }
  5711. }
  5712. };
  5713. // Force canvas to display as block to avoid extra space caused by inline
  5714. // elements, which would interfere with the responsive resize process.
  5715. // https://github.com/chartjs/Chart.js/issues/2538
  5716. style.display = style.display || 'block';
  5717. if (renderWidth === null || renderWidth === '') {
  5718. var displayWidth = readUsedSize(canvas, 'width');
  5719. if (displayWidth !== undefined) {
  5720. canvas.width = displayWidth;
  5721. }
  5722. }
  5723. if (renderHeight === null || renderHeight === '') {
  5724. if (canvas.style.height === '') {
  5725. // If no explicit render height and style height, let's apply the aspect ratio,
  5726. // which one can be specified by the user but also by charts as default option
  5727. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  5728. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  5729. } else {
  5730. var displayHeight = readUsedSize(canvas, 'height');
  5731. if (displayWidth !== undefined) {
  5732. canvas.height = displayHeight;
  5733. }
  5734. }
  5735. }
  5736. return canvas;
  5737. }
  5738. /**
  5739. * Detects support for options object argument in addEventListener.
  5740. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  5741. * @private
  5742. */
  5743. var supportsEventListenerOptions = (function() {
  5744. var supports = false;
  5745. try {
  5746. var options = Object.defineProperty({}, 'passive', {
  5747. // eslint-disable-next-line getter-return
  5748. get: function() {
  5749. supports = true;
  5750. }
  5751. });
  5752. window.addEventListener('e', null, options);
  5753. } catch (e) {
  5754. // continue regardless of error
  5755. }
  5756. return supports;
  5757. }());
  5758. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  5759. // https://github.com/chartjs/Chart.js/issues/4287
  5760. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  5761. function addListener(node, type, listener) {
  5762. node.addEventListener(type, listener, eventListenerOptions);
  5763. }
  5764. function removeListener(node, type, listener) {
  5765. node.removeEventListener(type, listener, eventListenerOptions);
  5766. }
  5767. function createEvent(type, chart, x, y, nativeEvent) {
  5768. return {
  5769. type: type,
  5770. chart: chart,
  5771. native: nativeEvent || null,
  5772. x: x !== undefined ? x : null,
  5773. y: y !== undefined ? y : null,
  5774. };
  5775. }
  5776. function fromNativeEvent(event, chart) {
  5777. var type = EVENT_TYPES[event.type] || event.type;
  5778. var pos = helpers$1.getRelativePosition(event, chart);
  5779. return createEvent(type, chart, pos.x, pos.y, event);
  5780. }
  5781. function throttled(fn, thisArg) {
  5782. var ticking = false;
  5783. var args = [];
  5784. return function() {
  5785. args = Array.prototype.slice.call(arguments);
  5786. thisArg = thisArg || this;
  5787. if (!ticking) {
  5788. ticking = true;
  5789. helpers$1.requestAnimFrame.call(window, function() {
  5790. ticking = false;
  5791. fn.apply(thisArg, args);
  5792. });
  5793. }
  5794. };
  5795. }
  5796. function createDiv(cls) {
  5797. var el = document.createElement('div');
  5798. el.className = cls || '';
  5799. return el;
  5800. }
  5801. // Implementation based on https://github.com/marcj/css-element-queries
  5802. function createResizer(handler) {
  5803. var maxSize = 1000000;
  5804. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  5805. // https://github.com/chartjs/Chart.js/issues/5902
  5806. var resizer = createDiv(CSS_SIZE_MONITOR);
  5807. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  5808. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  5809. expand.appendChild(createDiv());
  5810. shrink.appendChild(createDiv());
  5811. resizer.appendChild(expand);
  5812. resizer.appendChild(shrink);
  5813. resizer._reset = function() {
  5814. expand.scrollLeft = maxSize;
  5815. expand.scrollTop = maxSize;
  5816. shrink.scrollLeft = maxSize;
  5817. shrink.scrollTop = maxSize;
  5818. };
  5819. var onScroll = function() {
  5820. resizer._reset();
  5821. handler();
  5822. };
  5823. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  5824. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  5825. return resizer;
  5826. }
  5827. // https://davidwalsh.name/detect-node-insertion
  5828. function watchForRender(node, handler) {
  5829. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  5830. var proxy = expando.renderProxy = function(e) {
  5831. if (e.animationName === CSS_RENDER_ANIMATION) {
  5832. handler();
  5833. }
  5834. };
  5835. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  5836. addListener(node, type, proxy);
  5837. });
  5838. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  5839. // is removed then added back immediately (same animation frame?). Accessing the
  5840. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  5841. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  5842. // https://github.com/chartjs/Chart.js/issues/4737
  5843. expando.reflow = !!node.offsetParent;
  5844. node.classList.add(CSS_RENDER_MONITOR);
  5845. }
  5846. function unwatchForRender(node) {
  5847. var expando = node[EXPANDO_KEY] || {};
  5848. var proxy = expando.renderProxy;
  5849. if (proxy) {
  5850. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  5851. removeListener(node, type, proxy);
  5852. });
  5853. delete expando.renderProxy;
  5854. }
  5855. node.classList.remove(CSS_RENDER_MONITOR);
  5856. }
  5857. function addResizeListener(node, listener, chart) {
  5858. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  5859. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  5860. var resizer = expando.resizer = createResizer(throttled(function() {
  5861. if (expando.resizer) {
  5862. var container = chart.options.maintainAspectRatio && node.parentNode;
  5863. var w = container ? container.clientWidth : 0;
  5864. listener(createEvent('resize', chart));
  5865. if (container && container.clientWidth < w && chart.canvas) {
  5866. // If the container size shrank during chart resize, let's assume
  5867. // scrollbar appeared. So we resize again with the scrollbar visible -
  5868. // effectively making chart smaller and the scrollbar hidden again.
  5869. // Because we are inside `throttled`, and currently `ticking`, scroll
  5870. // events are ignored during this whole 2 resize process.
  5871. // If we assumed wrong and something else happened, we are resizing
  5872. // twice in a frame (potential performance issue)
  5873. listener(createEvent('resize', chart));
  5874. }
  5875. }
  5876. }));
  5877. // The resizer needs to be attached to the node parent, so we first need to be
  5878. // sure that `node` is attached to the DOM before injecting the resizer element.
  5879. watchForRender(node, function() {
  5880. if (expando.resizer) {
  5881. var container = node.parentNode;
  5882. if (container && container !== resizer.parentNode) {
  5883. container.insertBefore(resizer, container.firstChild);
  5884. }
  5885. // The container size might have changed, let's reset the resizer state.
  5886. resizer._reset();
  5887. }
  5888. });
  5889. }
  5890. function removeResizeListener(node) {
  5891. var expando = node[EXPANDO_KEY] || {};
  5892. var resizer = expando.resizer;
  5893. delete expando.resizer;
  5894. unwatchForRender(node);
  5895. if (resizer && resizer.parentNode) {
  5896. resizer.parentNode.removeChild(resizer);
  5897. }
  5898. }
  5899. function injectCSS(platform, css) {
  5900. // https://stackoverflow.com/q/3922139
  5901. var style = platform._style || document.createElement('style');
  5902. if (!platform._style) {
  5903. platform._style = style;
  5904. css = '/* Chart.js */\n' + css;
  5905. style.setAttribute('type', 'text/css');
  5906. document.getElementsByTagName('head')[0].appendChild(style);
  5907. }
  5908. style.appendChild(document.createTextNode(css));
  5909. }
  5910. var platform_dom$2 = {
  5911. /**
  5912. * When `true`, prevents the automatic injection of the stylesheet required to
  5913. * correctly detect when the chart is added to the DOM and then resized. This
  5914. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  5915. * to be manually imported to make this library compatible with any CSP.
  5916. * See https://github.com/chartjs/Chart.js/issues/5208
  5917. */
  5918. disableCSSInjection: false,
  5919. /**
  5920. * This property holds whether this platform is enabled for the current environment.
  5921. * Currently used by platform.js to select the proper implementation.
  5922. * @private
  5923. */
  5924. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  5925. /**
  5926. * @private
  5927. */
  5928. _ensureLoaded: function() {
  5929. if (this._loaded) {
  5930. return;
  5931. }
  5932. this._loaded = true;
  5933. // https://github.com/chartjs/Chart.js/issues/5208
  5934. if (!this.disableCSSInjection) {
  5935. injectCSS(this, stylesheet);
  5936. }
  5937. },
  5938. acquireContext: function(item, config) {
  5939. if (typeof item === 'string') {
  5940. item = document.getElementById(item);
  5941. } else if (item.length) {
  5942. // Support for array based queries (such as jQuery)
  5943. item = item[0];
  5944. }
  5945. if (item && item.canvas) {
  5946. // Support for any object associated to a canvas (including a context2d)
  5947. item = item.canvas;
  5948. }
  5949. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  5950. // method, for example: https://github.com/kkapsner/CanvasBlocker
  5951. // https://github.com/chartjs/Chart.js/issues/2807
  5952. var context = item && item.getContext && item.getContext('2d');
  5953. // Load platform resources on first chart creation, to make possible to change
  5954. // platform options after importing the library (e.g. `disableCSSInjection`).
  5955. this._ensureLoaded();
  5956. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  5957. // inside an iframe or when running in a protected environment. We could guess the
  5958. // types from their toString() value but let's keep things flexible and assume it's
  5959. // a sufficient condition if the item has a context2D which has item as `canvas`.
  5960. // https://github.com/chartjs/Chart.js/issues/3887
  5961. // https://github.com/chartjs/Chart.js/issues/4102
  5962. // https://github.com/chartjs/Chart.js/issues/4152
  5963. if (context && context.canvas === item) {
  5964. initCanvas(item, config);
  5965. return context;
  5966. }
  5967. return null;
  5968. },
  5969. releaseContext: function(context) {
  5970. var canvas = context.canvas;
  5971. if (!canvas[EXPANDO_KEY]) {
  5972. return;
  5973. }
  5974. var initial = canvas[EXPANDO_KEY].initial;
  5975. ['height', 'width'].forEach(function(prop) {
  5976. var value = initial[prop];
  5977. if (helpers$1.isNullOrUndef(value)) {
  5978. canvas.removeAttribute(prop);
  5979. } else {
  5980. canvas.setAttribute(prop, value);
  5981. }
  5982. });
  5983. helpers$1.each(initial.style || {}, function(value, key) {
  5984. canvas.style[key] = value;
  5985. });
  5986. // The canvas render size might have been changed (and thus the state stack discarded),
  5987. // we can't use save() and restore() to restore the initial state. So make sure that at
  5988. // least the canvas context is reset to the default state by setting the canvas width.
  5989. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  5990. // eslint-disable-next-line no-self-assign
  5991. canvas.width = canvas.width;
  5992. delete canvas[EXPANDO_KEY];
  5993. },
  5994. addEventListener: function(chart, type, listener) {
  5995. var canvas = chart.canvas;
  5996. if (type === 'resize') {
  5997. // Note: the resize event is not supported on all browsers.
  5998. addResizeListener(canvas, listener, chart);
  5999. return;
  6000. }
  6001. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  6002. var proxies = expando.proxies || (expando.proxies = {});
  6003. var proxy = proxies[chart.id + '_' + type] = function(event) {
  6004. listener(fromNativeEvent(event, chart));
  6005. };
  6006. addListener(canvas, type, proxy);
  6007. },
  6008. removeEventListener: function(chart, type, listener) {
  6009. var canvas = chart.canvas;
  6010. if (type === 'resize') {
  6011. // Note: the resize event is not supported on all browsers.
  6012. removeResizeListener(canvas);
  6013. return;
  6014. }
  6015. var expando = listener[EXPANDO_KEY] || {};
  6016. var proxies = expando.proxies || {};
  6017. var proxy = proxies[chart.id + '_' + type];
  6018. if (!proxy) {
  6019. return;
  6020. }
  6021. removeListener(canvas, type, proxy);
  6022. }
  6023. };
  6024. // DEPRECATIONS
  6025. /**
  6026. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6027. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6028. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6029. * @function Chart.helpers.addEvent
  6030. * @deprecated since version 2.7.0
  6031. * @todo remove at version 3
  6032. * @private
  6033. */
  6034. helpers$1.addEvent = addListener;
  6035. /**
  6036. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6037. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6038. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6039. * @function Chart.helpers.removeEvent
  6040. * @deprecated since version 2.7.0
  6041. * @todo remove at version 3
  6042. * @private
  6043. */
  6044. helpers$1.removeEvent = removeListener;
  6045. // @TODO Make possible to select another platform at build time.
  6046. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6047. /**
  6048. * @namespace Chart.platform
  6049. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6050. * @since 2.4.0
  6051. */
  6052. var platform = helpers$1.extend({
  6053. /**
  6054. * @since 2.7.0
  6055. */
  6056. initialize: function() {},
  6057. /**
  6058. * Called at chart construction time, returns a context2d instance implementing
  6059. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6060. * @param {*} item - The native item from which to acquire context (platform specific)
  6061. * @param {object} options - The chart options
  6062. * @returns {CanvasRenderingContext2D} context2d instance
  6063. */
  6064. acquireContext: function() {},
  6065. /**
  6066. * Called at chart destruction time, releases any resources associated to the context
  6067. * previously returned by the acquireContext() method.
  6068. * @param {CanvasRenderingContext2D} context - The context2d instance
  6069. * @returns {boolean} true if the method succeeded, else false
  6070. */
  6071. releaseContext: function() {},
  6072. /**
  6073. * Registers the specified listener on the given chart.
  6074. * @param {Chart} chart - Chart from which to listen for event
  6075. * @param {string} type - The ({@link IEvent}) type to listen for
  6076. * @param {function} listener - Receives a notification (an object that implements
  6077. * the {@link IEvent} interface) when an event of the specified type occurs.
  6078. */
  6079. addEventListener: function() {},
  6080. /**
  6081. * Removes the specified listener previously registered with addEventListener.
  6082. * @param {Chart} chart - Chart from which to remove the listener
  6083. * @param {string} type - The ({@link IEvent}) type to remove
  6084. * @param {function} listener - The listener function to remove from the event target.
  6085. */
  6086. removeEventListener: function() {}
  6087. }, implementation);
  6088. core_defaults._set('global', {
  6089. plugins: {}
  6090. });
  6091. /**
  6092. * The plugin service singleton
  6093. * @namespace Chart.plugins
  6094. * @since 2.1.0
  6095. */
  6096. var core_plugins = {
  6097. /**
  6098. * Globally registered plugins.
  6099. * @private
  6100. */
  6101. _plugins: [],
  6102. /**
  6103. * This identifier is used to invalidate the descriptors cache attached to each chart
  6104. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6105. * incremented and descriptors are regenerated during following API calls.
  6106. * @private
  6107. */
  6108. _cacheId: 0,
  6109. /**
  6110. * Registers the given plugin(s) if not already registered.
  6111. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6112. */
  6113. register: function(plugins) {
  6114. var p = this._plugins;
  6115. ([]).concat(plugins).forEach(function(plugin) {
  6116. if (p.indexOf(plugin) === -1) {
  6117. p.push(plugin);
  6118. }
  6119. });
  6120. this._cacheId++;
  6121. },
  6122. /**
  6123. * Unregisters the given plugin(s) only if registered.
  6124. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6125. */
  6126. unregister: function(plugins) {
  6127. var p = this._plugins;
  6128. ([]).concat(plugins).forEach(function(plugin) {
  6129. var idx = p.indexOf(plugin);
  6130. if (idx !== -1) {
  6131. p.splice(idx, 1);
  6132. }
  6133. });
  6134. this._cacheId++;
  6135. },
  6136. /**
  6137. * Remove all registered plugins.
  6138. * @since 2.1.5
  6139. */
  6140. clear: function() {
  6141. this._plugins = [];
  6142. this._cacheId++;
  6143. },
  6144. /**
  6145. * Returns the number of registered plugins?
  6146. * @returns {number}
  6147. * @since 2.1.5
  6148. */
  6149. count: function() {
  6150. return this._plugins.length;
  6151. },
  6152. /**
  6153. * Returns all registered plugin instances.
  6154. * @returns {IPlugin[]} array of plugin objects.
  6155. * @since 2.1.5
  6156. */
  6157. getAll: function() {
  6158. return this._plugins;
  6159. },
  6160. /**
  6161. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6162. * This method immediately returns as soon as a plugin explicitly returns false. The
  6163. * returned value can be used, for instance, to interrupt the current action.
  6164. * @param {Chart} chart - The chart instance for which plugins should be called.
  6165. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6166. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6167. * @returns {boolean} false if any of the plugins return false, else returns true.
  6168. */
  6169. notify: function(chart, hook, args) {
  6170. var descriptors = this.descriptors(chart);
  6171. var ilen = descriptors.length;
  6172. var i, descriptor, plugin, params, method;
  6173. for (i = 0; i < ilen; ++i) {
  6174. descriptor = descriptors[i];
  6175. plugin = descriptor.plugin;
  6176. method = plugin[hook];
  6177. if (typeof method === 'function') {
  6178. params = [chart].concat(args || []);
  6179. params.push(descriptor.options);
  6180. if (method.apply(plugin, params) === false) {
  6181. return false;
  6182. }
  6183. }
  6184. }
  6185. return true;
  6186. },
  6187. /**
  6188. * Returns descriptors of enabled plugins for the given chart.
  6189. * @returns {object[]} [{ plugin, options }]
  6190. * @private
  6191. */
  6192. descriptors: function(chart) {
  6193. var cache = chart.$plugins || (chart.$plugins = {});
  6194. if (cache.id === this._cacheId) {
  6195. return cache.descriptors;
  6196. }
  6197. var plugins = [];
  6198. var descriptors = [];
  6199. var config = (chart && chart.config) || {};
  6200. var options = (config.options && config.options.plugins) || {};
  6201. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  6202. var idx = plugins.indexOf(plugin);
  6203. if (idx !== -1) {
  6204. return;
  6205. }
  6206. var id = plugin.id;
  6207. var opts = options[id];
  6208. if (opts === false) {
  6209. return;
  6210. }
  6211. if (opts === true) {
  6212. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6213. }
  6214. plugins.push(plugin);
  6215. descriptors.push({
  6216. plugin: plugin,
  6217. options: opts || {}
  6218. });
  6219. });
  6220. cache.descriptors = descriptors;
  6221. cache.id = this._cacheId;
  6222. return descriptors;
  6223. },
  6224. /**
  6225. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  6226. * but in some cases, this reference can be changed by the user when updating options.
  6227. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  6228. * @private
  6229. */
  6230. _invalidate: function(chart) {
  6231. delete chart.$plugins;
  6232. }
  6233. };
  6234. var core_scaleService = {
  6235. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  6236. // use the new chart options to grab the correct scale
  6237. constructors: {},
  6238. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  6239. // old browsers
  6240. // Scale config defaults
  6241. defaults: {},
  6242. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  6243. this.constructors[type] = scaleConstructor;
  6244. this.defaults[type] = helpers$1.clone(scaleDefaults);
  6245. },
  6246. getScaleConstructor: function(type) {
  6247. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  6248. },
  6249. getScaleDefaults: function(type) {
  6250. // Return the scale defaults merged with the global settings so that we always use the latest ones
  6251. return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {};
  6252. },
  6253. updateScaleDefaults: function(type, additions) {
  6254. var me = this;
  6255. if (me.defaults.hasOwnProperty(type)) {
  6256. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  6257. }
  6258. },
  6259. addScalesToLayout: function(chart) {
  6260. // Adds each scale to the chart.boxes array to be sized accordingly
  6261. helpers$1.each(chart.scales, function(scale) {
  6262. // Set ILayoutItem parameters for backwards compatibility
  6263. scale.fullWidth = scale.options.fullWidth;
  6264. scale.position = scale.options.position;
  6265. scale.weight = scale.options.weight;
  6266. core_layouts.addBox(chart, scale);
  6267. });
  6268. }
  6269. };
  6270. var valueOrDefault$7 = helpers$1.valueOrDefault;
  6271. core_defaults._set('global', {
  6272. tooltips: {
  6273. enabled: true,
  6274. custom: null,
  6275. mode: 'nearest',
  6276. position: 'average',
  6277. intersect: true,
  6278. backgroundColor: 'rgba(0,0,0,0.8)',
  6279. titleFontStyle: 'bold',
  6280. titleSpacing: 2,
  6281. titleMarginBottom: 6,
  6282. titleFontColor: '#fff',
  6283. titleAlign: 'left',
  6284. bodySpacing: 2,
  6285. bodyFontColor: '#fff',
  6286. bodyAlign: 'left',
  6287. footerFontStyle: 'bold',
  6288. footerSpacing: 2,
  6289. footerMarginTop: 6,
  6290. footerFontColor: '#fff',
  6291. footerAlign: 'left',
  6292. yPadding: 6,
  6293. xPadding: 6,
  6294. caretPadding: 2,
  6295. caretSize: 5,
  6296. cornerRadius: 6,
  6297. multiKeyBackground: '#fff',
  6298. displayColors: true,
  6299. borderColor: 'rgba(0,0,0,0)',
  6300. borderWidth: 0,
  6301. callbacks: {
  6302. // Args are: (tooltipItems, data)
  6303. beforeTitle: helpers$1.noop,
  6304. title: function(tooltipItems, data) {
  6305. var title = '';
  6306. var labels = data.labels;
  6307. var labelCount = labels ? labels.length : 0;
  6308. if (tooltipItems.length > 0) {
  6309. var item = tooltipItems[0];
  6310. if (item.label) {
  6311. title = item.label;
  6312. } else if (item.xLabel) {
  6313. title = item.xLabel;
  6314. } else if (labelCount > 0 && item.index < labelCount) {
  6315. title = labels[item.index];
  6316. }
  6317. }
  6318. return title;
  6319. },
  6320. afterTitle: helpers$1.noop,
  6321. // Args are: (tooltipItems, data)
  6322. beforeBody: helpers$1.noop,
  6323. // Args are: (tooltipItem, data)
  6324. beforeLabel: helpers$1.noop,
  6325. label: function(tooltipItem, data) {
  6326. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  6327. if (label) {
  6328. label += ': ';
  6329. }
  6330. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  6331. label += tooltipItem.value;
  6332. } else {
  6333. label += tooltipItem.yLabel;
  6334. }
  6335. return label;
  6336. },
  6337. labelColor: function(tooltipItem, chart) {
  6338. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  6339. var activeElement = meta.data[tooltipItem.index];
  6340. var view = activeElement._view;
  6341. return {
  6342. borderColor: view.borderColor,
  6343. backgroundColor: view.backgroundColor
  6344. };
  6345. },
  6346. labelTextColor: function() {
  6347. return this._options.bodyFontColor;
  6348. },
  6349. afterLabel: helpers$1.noop,
  6350. // Args are: (tooltipItems, data)
  6351. afterBody: helpers$1.noop,
  6352. // Args are: (tooltipItems, data)
  6353. beforeFooter: helpers$1.noop,
  6354. footer: helpers$1.noop,
  6355. afterFooter: helpers$1.noop
  6356. }
  6357. }
  6358. });
  6359. var positioners = {
  6360. /**
  6361. * Average mode places the tooltip at the average position of the elements shown
  6362. * @function Chart.Tooltip.positioners.average
  6363. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  6364. * @returns {object} tooltip position
  6365. */
  6366. average: function(elements) {
  6367. if (!elements.length) {
  6368. return false;
  6369. }
  6370. var i, len;
  6371. var x = 0;
  6372. var y = 0;
  6373. var count = 0;
  6374. for (i = 0, len = elements.length; i < len; ++i) {
  6375. var el = elements[i];
  6376. if (el && el.hasValue()) {
  6377. var pos = el.tooltipPosition();
  6378. x += pos.x;
  6379. y += pos.y;
  6380. ++count;
  6381. }
  6382. }
  6383. return {
  6384. x: x / count,
  6385. y: y / count
  6386. };
  6387. },
  6388. /**
  6389. * Gets the tooltip position nearest of the item nearest to the event position
  6390. * @function Chart.Tooltip.positioners.nearest
  6391. * @param elements {Chart.Element[]} the tooltip elements
  6392. * @param eventPosition {object} the position of the event in canvas coordinates
  6393. * @returns {object} the tooltip position
  6394. */
  6395. nearest: function(elements, eventPosition) {
  6396. var x = eventPosition.x;
  6397. var y = eventPosition.y;
  6398. var minDistance = Number.POSITIVE_INFINITY;
  6399. var i, len, nearestElement;
  6400. for (i = 0, len = elements.length; i < len; ++i) {
  6401. var el = elements[i];
  6402. if (el && el.hasValue()) {
  6403. var center = el.getCenterPoint();
  6404. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  6405. if (d < minDistance) {
  6406. minDistance = d;
  6407. nearestElement = el;
  6408. }
  6409. }
  6410. }
  6411. if (nearestElement) {
  6412. var tp = nearestElement.tooltipPosition();
  6413. x = tp.x;
  6414. y = tp.y;
  6415. }
  6416. return {
  6417. x: x,
  6418. y: y
  6419. };
  6420. }
  6421. };
  6422. // Helper to push or concat based on if the 2nd parameter is an array or not
  6423. function pushOrConcat(base, toPush) {
  6424. if (toPush) {
  6425. if (helpers$1.isArray(toPush)) {
  6426. // base = base.concat(toPush);
  6427. Array.prototype.push.apply(base, toPush);
  6428. } else {
  6429. base.push(toPush);
  6430. }
  6431. }
  6432. return base;
  6433. }
  6434. /**
  6435. * Returns array of strings split by newline
  6436. * @param {string} value - The value to split by newline.
  6437. * @returns {string[]} value if newline present - Returned from String split() method
  6438. * @function
  6439. */
  6440. function splitNewlines(str) {
  6441. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  6442. return str.split('\n');
  6443. }
  6444. return str;
  6445. }
  6446. /**
  6447. * Private helper to create a tooltip item model
  6448. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  6449. * @return new tooltip item
  6450. */
  6451. function createTooltipItem(element) {
  6452. var xScale = element._xScale;
  6453. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  6454. var index = element._index;
  6455. var datasetIndex = element._datasetIndex;
  6456. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  6457. var indexScale = controller._getIndexScale();
  6458. var valueScale = controller._getValueScale();
  6459. return {
  6460. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  6461. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  6462. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  6463. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  6464. index: index,
  6465. datasetIndex: datasetIndex,
  6466. x: element._model.x,
  6467. y: element._model.y
  6468. };
  6469. }
  6470. /**
  6471. * Helper to get the reset model for the tooltip
  6472. * @param tooltipOpts {object} the tooltip options
  6473. */
  6474. function getBaseModel(tooltipOpts) {
  6475. var globalDefaults = core_defaults.global;
  6476. return {
  6477. // Positioning
  6478. xPadding: tooltipOpts.xPadding,
  6479. yPadding: tooltipOpts.yPadding,
  6480. xAlign: tooltipOpts.xAlign,
  6481. yAlign: tooltipOpts.yAlign,
  6482. // Body
  6483. bodyFontColor: tooltipOpts.bodyFontColor,
  6484. _bodyFontFamily: valueOrDefault$7(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  6485. _bodyFontStyle: valueOrDefault$7(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  6486. _bodyAlign: tooltipOpts.bodyAlign,
  6487. bodyFontSize: valueOrDefault$7(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  6488. bodySpacing: tooltipOpts.bodySpacing,
  6489. // Title
  6490. titleFontColor: tooltipOpts.titleFontColor,
  6491. _titleFontFamily: valueOrDefault$7(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  6492. _titleFontStyle: valueOrDefault$7(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  6493. titleFontSize: valueOrDefault$7(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  6494. _titleAlign: tooltipOpts.titleAlign,
  6495. titleSpacing: tooltipOpts.titleSpacing,
  6496. titleMarginBottom: tooltipOpts.titleMarginBottom,
  6497. // Footer
  6498. footerFontColor: tooltipOpts.footerFontColor,
  6499. _footerFontFamily: valueOrDefault$7(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  6500. _footerFontStyle: valueOrDefault$7(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  6501. footerFontSize: valueOrDefault$7(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  6502. _footerAlign: tooltipOpts.footerAlign,
  6503. footerSpacing: tooltipOpts.footerSpacing,
  6504. footerMarginTop: tooltipOpts.footerMarginTop,
  6505. // Appearance
  6506. caretSize: tooltipOpts.caretSize,
  6507. cornerRadius: tooltipOpts.cornerRadius,
  6508. backgroundColor: tooltipOpts.backgroundColor,
  6509. opacity: 0,
  6510. legendColorBackground: tooltipOpts.multiKeyBackground,
  6511. displayColors: tooltipOpts.displayColors,
  6512. borderColor: tooltipOpts.borderColor,
  6513. borderWidth: tooltipOpts.borderWidth
  6514. };
  6515. }
  6516. /**
  6517. * Get the size of the tooltip
  6518. */
  6519. function getTooltipSize(tooltip, model) {
  6520. var ctx = tooltip._chart.ctx;
  6521. var height = model.yPadding * 2; // Tooltip Padding
  6522. var width = 0;
  6523. // Count of all lines in the body
  6524. var body = model.body;
  6525. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  6526. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  6527. }, 0);
  6528. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  6529. var titleLineCount = model.title.length;
  6530. var footerLineCount = model.footer.length;
  6531. var titleFontSize = model.titleFontSize;
  6532. var bodyFontSize = model.bodyFontSize;
  6533. var footerFontSize = model.footerFontSize;
  6534. height += titleLineCount * titleFontSize; // Title Lines
  6535. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  6536. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  6537. height += combinedBodyLength * bodyFontSize; // Body Lines
  6538. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  6539. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  6540. height += footerLineCount * (footerFontSize); // Footer Lines
  6541. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  6542. // Title width
  6543. var widthPadding = 0;
  6544. var maxLineWidth = function(line) {
  6545. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  6546. };
  6547. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  6548. helpers$1.each(model.title, maxLineWidth);
  6549. // Body width
  6550. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  6551. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  6552. // Body lines may include some extra width due to the color box
  6553. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  6554. helpers$1.each(body, function(bodyItem) {
  6555. helpers$1.each(bodyItem.before, maxLineWidth);
  6556. helpers$1.each(bodyItem.lines, maxLineWidth);
  6557. helpers$1.each(bodyItem.after, maxLineWidth);
  6558. });
  6559. // Reset back to 0
  6560. widthPadding = 0;
  6561. // Footer width
  6562. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  6563. helpers$1.each(model.footer, maxLineWidth);
  6564. // Add padding
  6565. width += 2 * model.xPadding;
  6566. return {
  6567. width: width,
  6568. height: height
  6569. };
  6570. }
  6571. /**
  6572. * Helper to get the alignment of a tooltip given the size
  6573. */
  6574. function determineAlignment(tooltip, size) {
  6575. var model = tooltip._model;
  6576. var chart = tooltip._chart;
  6577. var chartArea = tooltip._chart.chartArea;
  6578. var xAlign = 'center';
  6579. var yAlign = 'center';
  6580. if (model.y < size.height) {
  6581. yAlign = 'top';
  6582. } else if (model.y > (chart.height - size.height)) {
  6583. yAlign = 'bottom';
  6584. }
  6585. var lf, rf; // functions to determine left, right alignment
  6586. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  6587. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  6588. var midX = (chartArea.left + chartArea.right) / 2;
  6589. var midY = (chartArea.top + chartArea.bottom) / 2;
  6590. if (yAlign === 'center') {
  6591. lf = function(x) {
  6592. return x <= midX;
  6593. };
  6594. rf = function(x) {
  6595. return x > midX;
  6596. };
  6597. } else {
  6598. lf = function(x) {
  6599. return x <= (size.width / 2);
  6600. };
  6601. rf = function(x) {
  6602. return x >= (chart.width - (size.width / 2));
  6603. };
  6604. }
  6605. olf = function(x) {
  6606. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  6607. };
  6608. orf = function(x) {
  6609. return x - size.width - model.caretSize - model.caretPadding < 0;
  6610. };
  6611. yf = function(y) {
  6612. return y <= midY ? 'top' : 'bottom';
  6613. };
  6614. if (lf(model.x)) {
  6615. xAlign = 'left';
  6616. // Is tooltip too wide and goes over the right side of the chart.?
  6617. if (olf(model.x)) {
  6618. xAlign = 'center';
  6619. yAlign = yf(model.y);
  6620. }
  6621. } else if (rf(model.x)) {
  6622. xAlign = 'right';
  6623. // Is tooltip too wide and goes outside left edge of canvas?
  6624. if (orf(model.x)) {
  6625. xAlign = 'center';
  6626. yAlign = yf(model.y);
  6627. }
  6628. }
  6629. var opts = tooltip._options;
  6630. return {
  6631. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  6632. yAlign: opts.yAlign ? opts.yAlign : yAlign
  6633. };
  6634. }
  6635. /**
  6636. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  6637. */
  6638. function getBackgroundPoint(vm, size, alignment, chart) {
  6639. // Background Position
  6640. var x = vm.x;
  6641. var y = vm.y;
  6642. var caretSize = vm.caretSize;
  6643. var caretPadding = vm.caretPadding;
  6644. var cornerRadius = vm.cornerRadius;
  6645. var xAlign = alignment.xAlign;
  6646. var yAlign = alignment.yAlign;
  6647. var paddingAndSize = caretSize + caretPadding;
  6648. var radiusAndPadding = cornerRadius + caretPadding;
  6649. if (xAlign === 'right') {
  6650. x -= size.width;
  6651. } else if (xAlign === 'center') {
  6652. x -= (size.width / 2);
  6653. if (x + size.width > chart.width) {
  6654. x = chart.width - size.width;
  6655. }
  6656. if (x < 0) {
  6657. x = 0;
  6658. }
  6659. }
  6660. if (yAlign === 'top') {
  6661. y += paddingAndSize;
  6662. } else if (yAlign === 'bottom') {
  6663. y -= size.height + paddingAndSize;
  6664. } else {
  6665. y -= (size.height / 2);
  6666. }
  6667. if (yAlign === 'center') {
  6668. if (xAlign === 'left') {
  6669. x += paddingAndSize;
  6670. } else if (xAlign === 'right') {
  6671. x -= paddingAndSize;
  6672. }
  6673. } else if (xAlign === 'left') {
  6674. x -= radiusAndPadding;
  6675. } else if (xAlign === 'right') {
  6676. x += radiusAndPadding;
  6677. }
  6678. return {
  6679. x: x,
  6680. y: y
  6681. };
  6682. }
  6683. function getAlignedX(vm, align) {
  6684. return align === 'center'
  6685. ? vm.x + vm.width / 2
  6686. : align === 'right'
  6687. ? vm.x + vm.width - vm.xPadding
  6688. : vm.x + vm.xPadding;
  6689. }
  6690. /**
  6691. * Helper to build before and after body lines
  6692. */
  6693. function getBeforeAfterBodyLines(callback) {
  6694. return pushOrConcat([], splitNewlines(callback));
  6695. }
  6696. var exports$3 = core_element.extend({
  6697. initialize: function() {
  6698. this._model = getBaseModel(this._options);
  6699. this._lastActive = [];
  6700. },
  6701. // Get the title
  6702. // Args are: (tooltipItem, data)
  6703. getTitle: function() {
  6704. var me = this;
  6705. var opts = me._options;
  6706. var callbacks = opts.callbacks;
  6707. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  6708. var title = callbacks.title.apply(me, arguments);
  6709. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  6710. var lines = [];
  6711. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  6712. lines = pushOrConcat(lines, splitNewlines(title));
  6713. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  6714. return lines;
  6715. },
  6716. // Args are: (tooltipItem, data)
  6717. getBeforeBody: function() {
  6718. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  6719. },
  6720. // Args are: (tooltipItem, data)
  6721. getBody: function(tooltipItems, data) {
  6722. var me = this;
  6723. var callbacks = me._options.callbacks;
  6724. var bodyItems = [];
  6725. helpers$1.each(tooltipItems, function(tooltipItem) {
  6726. var bodyItem = {
  6727. before: [],
  6728. lines: [],
  6729. after: []
  6730. };
  6731. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  6732. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  6733. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  6734. bodyItems.push(bodyItem);
  6735. });
  6736. return bodyItems;
  6737. },
  6738. // Args are: (tooltipItem, data)
  6739. getAfterBody: function() {
  6740. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  6741. },
  6742. // Get the footer and beforeFooter and afterFooter lines
  6743. // Args are: (tooltipItem, data)
  6744. getFooter: function() {
  6745. var me = this;
  6746. var callbacks = me._options.callbacks;
  6747. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  6748. var footer = callbacks.footer.apply(me, arguments);
  6749. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  6750. var lines = [];
  6751. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  6752. lines = pushOrConcat(lines, splitNewlines(footer));
  6753. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  6754. return lines;
  6755. },
  6756. update: function(changed) {
  6757. var me = this;
  6758. var opts = me._options;
  6759. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  6760. // 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
  6761. // which breaks any animations.
  6762. var existingModel = me._model;
  6763. var model = me._model = getBaseModel(opts);
  6764. var active = me._active;
  6765. var data = me._data;
  6766. // In the case where active.length === 0 we need to keep these at existing values for good animations
  6767. var alignment = {
  6768. xAlign: existingModel.xAlign,
  6769. yAlign: existingModel.yAlign
  6770. };
  6771. var backgroundPoint = {
  6772. x: existingModel.x,
  6773. y: existingModel.y
  6774. };
  6775. var tooltipSize = {
  6776. width: existingModel.width,
  6777. height: existingModel.height
  6778. };
  6779. var tooltipPosition = {
  6780. x: existingModel.caretX,
  6781. y: existingModel.caretY
  6782. };
  6783. var i, len;
  6784. if (active.length) {
  6785. model.opacity = 1;
  6786. var labelColors = [];
  6787. var labelTextColors = [];
  6788. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  6789. var tooltipItems = [];
  6790. for (i = 0, len = active.length; i < len; ++i) {
  6791. tooltipItems.push(createTooltipItem(active[i]));
  6792. }
  6793. // If the user provided a filter function, use it to modify the tooltip items
  6794. if (opts.filter) {
  6795. tooltipItems = tooltipItems.filter(function(a) {
  6796. return opts.filter(a, data);
  6797. });
  6798. }
  6799. // If the user provided a sorting function, use it to modify the tooltip items
  6800. if (opts.itemSort) {
  6801. tooltipItems = tooltipItems.sort(function(a, b) {
  6802. return opts.itemSort(a, b, data);
  6803. });
  6804. }
  6805. // Determine colors for boxes
  6806. helpers$1.each(tooltipItems, function(tooltipItem) {
  6807. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  6808. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  6809. });
  6810. // Build the Text Lines
  6811. model.title = me.getTitle(tooltipItems, data);
  6812. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  6813. model.body = me.getBody(tooltipItems, data);
  6814. model.afterBody = me.getAfterBody(tooltipItems, data);
  6815. model.footer = me.getFooter(tooltipItems, data);
  6816. // Initial positioning and colors
  6817. model.x = tooltipPosition.x;
  6818. model.y = tooltipPosition.y;
  6819. model.caretPadding = opts.caretPadding;
  6820. model.labelColors = labelColors;
  6821. model.labelTextColors = labelTextColors;
  6822. // data points
  6823. model.dataPoints = tooltipItems;
  6824. // We need to determine alignment of the tooltip
  6825. tooltipSize = getTooltipSize(this, model);
  6826. alignment = determineAlignment(this, tooltipSize);
  6827. // Final Size and Position
  6828. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  6829. } else {
  6830. model.opacity = 0;
  6831. }
  6832. model.xAlign = alignment.xAlign;
  6833. model.yAlign = alignment.yAlign;
  6834. model.x = backgroundPoint.x;
  6835. model.y = backgroundPoint.y;
  6836. model.width = tooltipSize.width;
  6837. model.height = tooltipSize.height;
  6838. // Point where the caret on the tooltip points to
  6839. model.caretX = tooltipPosition.x;
  6840. model.caretY = tooltipPosition.y;
  6841. me._model = model;
  6842. if (changed && opts.custom) {
  6843. opts.custom.call(me, model);
  6844. }
  6845. return me;
  6846. },
  6847. drawCaret: function(tooltipPoint, size) {
  6848. var ctx = this._chart.ctx;
  6849. var vm = this._view;
  6850. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  6851. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  6852. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  6853. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  6854. },
  6855. getCaretPosition: function(tooltipPoint, size, vm) {
  6856. var x1, x2, x3, y1, y2, y3;
  6857. var caretSize = vm.caretSize;
  6858. var cornerRadius = vm.cornerRadius;
  6859. var xAlign = vm.xAlign;
  6860. var yAlign = vm.yAlign;
  6861. var ptX = tooltipPoint.x;
  6862. var ptY = tooltipPoint.y;
  6863. var width = size.width;
  6864. var height = size.height;
  6865. if (yAlign === 'center') {
  6866. y2 = ptY + (height / 2);
  6867. if (xAlign === 'left') {
  6868. x1 = ptX;
  6869. x2 = x1 - caretSize;
  6870. x3 = x1;
  6871. y1 = y2 + caretSize;
  6872. y3 = y2 - caretSize;
  6873. } else {
  6874. x1 = ptX + width;
  6875. x2 = x1 + caretSize;
  6876. x3 = x1;
  6877. y1 = y2 - caretSize;
  6878. y3 = y2 + caretSize;
  6879. }
  6880. } else {
  6881. if (xAlign === 'left') {
  6882. x2 = ptX + cornerRadius + (caretSize);
  6883. x1 = x2 - caretSize;
  6884. x3 = x2 + caretSize;
  6885. } else if (xAlign === 'right') {
  6886. x2 = ptX + width - cornerRadius - caretSize;
  6887. x1 = x2 - caretSize;
  6888. x3 = x2 + caretSize;
  6889. } else {
  6890. x2 = vm.caretX;
  6891. x1 = x2 - caretSize;
  6892. x3 = x2 + caretSize;
  6893. }
  6894. if (yAlign === 'top') {
  6895. y1 = ptY;
  6896. y2 = y1 - caretSize;
  6897. y3 = y1;
  6898. } else {
  6899. y1 = ptY + height;
  6900. y2 = y1 + caretSize;
  6901. y3 = y1;
  6902. // invert drawing order
  6903. var tmp = x3;
  6904. x3 = x1;
  6905. x1 = tmp;
  6906. }
  6907. }
  6908. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  6909. },
  6910. drawTitle: function(pt, vm, ctx) {
  6911. var title = vm.title;
  6912. if (title.length) {
  6913. pt.x = getAlignedX(vm, vm._titleAlign);
  6914. ctx.textAlign = vm._titleAlign;
  6915. ctx.textBaseline = 'top';
  6916. var titleFontSize = vm.titleFontSize;
  6917. var titleSpacing = vm.titleSpacing;
  6918. ctx.fillStyle = vm.titleFontColor;
  6919. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  6920. var i, len;
  6921. for (i = 0, len = title.length; i < len; ++i) {
  6922. ctx.fillText(title[i], pt.x, pt.y);
  6923. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  6924. if (i + 1 === title.length) {
  6925. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  6926. }
  6927. }
  6928. }
  6929. },
  6930. drawBody: function(pt, vm, ctx) {
  6931. var bodyFontSize = vm.bodyFontSize;
  6932. var bodySpacing = vm.bodySpacing;
  6933. var bodyAlign = vm._bodyAlign;
  6934. var body = vm.body;
  6935. var drawColorBoxes = vm.displayColors;
  6936. var labelColors = vm.labelColors;
  6937. var xLinePadding = 0;
  6938. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  6939. var textColor;
  6940. ctx.textAlign = bodyAlign;
  6941. ctx.textBaseline = 'top';
  6942. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  6943. pt.x = getAlignedX(vm, bodyAlign);
  6944. // Before Body
  6945. var fillLineOfText = function(line) {
  6946. ctx.fillText(line, pt.x + xLinePadding, pt.y);
  6947. pt.y += bodyFontSize + bodySpacing;
  6948. };
  6949. // Before body lines
  6950. ctx.fillStyle = vm.bodyFontColor;
  6951. helpers$1.each(vm.beforeBody, fillLineOfText);
  6952. xLinePadding = drawColorBoxes && bodyAlign !== 'right'
  6953. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  6954. : 0;
  6955. // Draw body lines now
  6956. helpers$1.each(body, function(bodyItem, i) {
  6957. textColor = vm.labelTextColors[i];
  6958. ctx.fillStyle = textColor;
  6959. helpers$1.each(bodyItem.before, fillLineOfText);
  6960. helpers$1.each(bodyItem.lines, function(line) {
  6961. // Draw Legend-like boxes if needed
  6962. if (drawColorBoxes) {
  6963. // Fill a white rect so that colours merge nicely if the opacity is < 1
  6964. ctx.fillStyle = vm.legendColorBackground;
  6965. ctx.fillRect(colorX, pt.y, bodyFontSize, bodyFontSize);
  6966. // Border
  6967. ctx.lineWidth = 1;
  6968. ctx.strokeStyle = labelColors[i].borderColor;
  6969. ctx.strokeRect(colorX, pt.y, bodyFontSize, bodyFontSize);
  6970. // Inner square
  6971. ctx.fillStyle = labelColors[i].backgroundColor;
  6972. ctx.fillRect(colorX + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  6973. ctx.fillStyle = textColor;
  6974. }
  6975. fillLineOfText(line);
  6976. });
  6977. helpers$1.each(bodyItem.after, fillLineOfText);
  6978. });
  6979. // Reset back to 0 for after body
  6980. xLinePadding = 0;
  6981. // After body lines
  6982. helpers$1.each(vm.afterBody, fillLineOfText);
  6983. pt.y -= bodySpacing; // Remove last body spacing
  6984. },
  6985. drawFooter: function(pt, vm, ctx) {
  6986. var footer = vm.footer;
  6987. if (footer.length) {
  6988. pt.x = getAlignedX(vm, vm._footerAlign);
  6989. pt.y += vm.footerMarginTop;
  6990. ctx.textAlign = vm._footerAlign;
  6991. ctx.textBaseline = 'top';
  6992. ctx.fillStyle = vm.footerFontColor;
  6993. ctx.font = helpers$1.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  6994. helpers$1.each(footer, function(line) {
  6995. ctx.fillText(line, pt.x, pt.y);
  6996. pt.y += vm.footerFontSize + vm.footerSpacing;
  6997. });
  6998. }
  6999. },
  7000. drawBackground: function(pt, vm, ctx, tooltipSize) {
  7001. ctx.fillStyle = vm.backgroundColor;
  7002. ctx.strokeStyle = vm.borderColor;
  7003. ctx.lineWidth = vm.borderWidth;
  7004. var xAlign = vm.xAlign;
  7005. var yAlign = vm.yAlign;
  7006. var x = pt.x;
  7007. var y = pt.y;
  7008. var width = tooltipSize.width;
  7009. var height = tooltipSize.height;
  7010. var radius = vm.cornerRadius;
  7011. ctx.beginPath();
  7012. ctx.moveTo(x + radius, y);
  7013. if (yAlign === 'top') {
  7014. this.drawCaret(pt, tooltipSize);
  7015. }
  7016. ctx.lineTo(x + width - radius, y);
  7017. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7018. if (yAlign === 'center' && xAlign === 'right') {
  7019. this.drawCaret(pt, tooltipSize);
  7020. }
  7021. ctx.lineTo(x + width, y + height - radius);
  7022. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7023. if (yAlign === 'bottom') {
  7024. this.drawCaret(pt, tooltipSize);
  7025. }
  7026. ctx.lineTo(x + radius, y + height);
  7027. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7028. if (yAlign === 'center' && xAlign === 'left') {
  7029. this.drawCaret(pt, tooltipSize);
  7030. }
  7031. ctx.lineTo(x, y + radius);
  7032. ctx.quadraticCurveTo(x, y, x + radius, y);
  7033. ctx.closePath();
  7034. ctx.fill();
  7035. if (vm.borderWidth > 0) {
  7036. ctx.stroke();
  7037. }
  7038. },
  7039. draw: function() {
  7040. var ctx = this._chart.ctx;
  7041. var vm = this._view;
  7042. if (vm.opacity === 0) {
  7043. return;
  7044. }
  7045. var tooltipSize = {
  7046. width: vm.width,
  7047. height: vm.height
  7048. };
  7049. var pt = {
  7050. x: vm.x,
  7051. y: vm.y
  7052. };
  7053. // IE11/Edge does not like very small opacities, so snap to 0
  7054. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7055. // Truthy/falsey value for empty tooltip
  7056. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7057. if (this._options.enabled && hasTooltipContent) {
  7058. ctx.save();
  7059. ctx.globalAlpha = opacity;
  7060. // Draw Background
  7061. this.drawBackground(pt, vm, ctx, tooltipSize);
  7062. // Draw Title, Body, and Footer
  7063. pt.y += vm.yPadding;
  7064. // Titles
  7065. this.drawTitle(pt, vm, ctx);
  7066. // Body
  7067. this.drawBody(pt, vm, ctx);
  7068. // Footer
  7069. this.drawFooter(pt, vm, ctx);
  7070. ctx.restore();
  7071. }
  7072. },
  7073. /**
  7074. * Handle an event
  7075. * @private
  7076. * @param {IEvent} event - The event to handle
  7077. * @returns {boolean} true if the tooltip changed
  7078. */
  7079. handleEvent: function(e) {
  7080. var me = this;
  7081. var options = me._options;
  7082. var changed = false;
  7083. me._lastActive = me._lastActive || [];
  7084. // Find Active Elements for tooltips
  7085. if (e.type === 'mouseout') {
  7086. me._active = [];
  7087. } else {
  7088. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7089. }
  7090. // Remember Last Actives
  7091. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7092. // Only handle target event on tooltip change
  7093. if (changed) {
  7094. me._lastActive = me._active;
  7095. if (options.enabled || options.custom) {
  7096. me._eventPosition = {
  7097. x: e.x,
  7098. y: e.y
  7099. };
  7100. me.update(true);
  7101. me.pivot();
  7102. }
  7103. }
  7104. return changed;
  7105. }
  7106. });
  7107. /**
  7108. * @namespace Chart.Tooltip.positioners
  7109. */
  7110. var positioners_1 = positioners;
  7111. var core_tooltip = exports$3;
  7112. core_tooltip.positioners = positioners_1;
  7113. var valueOrDefault$8 = helpers$1.valueOrDefault;
  7114. core_defaults._set('global', {
  7115. elements: {},
  7116. events: [
  7117. 'mousemove',
  7118. 'mouseout',
  7119. 'click',
  7120. 'touchstart',
  7121. 'touchmove'
  7122. ],
  7123. hover: {
  7124. onHover: null,
  7125. mode: 'nearest',
  7126. intersect: true,
  7127. animationDuration: 400
  7128. },
  7129. onClick: null,
  7130. maintainAspectRatio: true,
  7131. responsive: true,
  7132. responsiveAnimationDuration: 0
  7133. });
  7134. /**
  7135. * Recursively merge the given config objects representing the `scales` option
  7136. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7137. * returns a deep copy of the result, thus doesn't alter inputs.
  7138. */
  7139. function mergeScaleConfig(/* config objects ... */) {
  7140. return helpers$1.merge({}, [].slice.call(arguments), {
  7141. merger: function(key, target, source, options) {
  7142. if (key === 'xAxes' || key === 'yAxes') {
  7143. var slen = source[key].length;
  7144. var i, type, scale;
  7145. if (!target[key]) {
  7146. target[key] = [];
  7147. }
  7148. for (i = 0; i < slen; ++i) {
  7149. scale = source[key][i];
  7150. type = valueOrDefault$8(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7151. if (i >= target[key].length) {
  7152. target[key].push({});
  7153. }
  7154. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7155. // new/untyped scale or type changed: let's apply the new defaults
  7156. // then merge source scale to correctly overwrite the defaults.
  7157. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7158. } else {
  7159. // scales type are the same
  7160. helpers$1.merge(target[key][i], scale);
  7161. }
  7162. }
  7163. } else {
  7164. helpers$1._merger(key, target, source, options);
  7165. }
  7166. }
  7167. });
  7168. }
  7169. /**
  7170. * Recursively merge the given config objects as the root options by handling
  7171. * default scale options for the `scales` and `scale` properties, then returns
  7172. * a deep copy of the result, thus doesn't alter inputs.
  7173. */
  7174. function mergeConfig(/* config objects ... */) {
  7175. return helpers$1.merge({}, [].slice.call(arguments), {
  7176. merger: function(key, target, source, options) {
  7177. var tval = target[key] || {};
  7178. var sval = source[key];
  7179. if (key === 'scales') {
  7180. // scale config merging is complex. Add our own function here for that
  7181. target[key] = mergeScaleConfig(tval, sval);
  7182. } else if (key === 'scale') {
  7183. // used in polar area & radar charts since there is only one scale
  7184. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7185. } else {
  7186. helpers$1._merger(key, target, source, options);
  7187. }
  7188. }
  7189. });
  7190. }
  7191. function initConfig(config) {
  7192. config = config || {};
  7193. // Do NOT use mergeConfig for the data object because this method merges arrays
  7194. // and so would change references to labels and datasets, preventing data updates.
  7195. var data = config.data = config.data || {};
  7196. data.datasets = data.datasets || [];
  7197. data.labels = data.labels || [];
  7198. config.options = mergeConfig(
  7199. core_defaults.global,
  7200. core_defaults[config.type],
  7201. config.options || {});
  7202. return config;
  7203. }
  7204. function updateConfig(chart) {
  7205. var newOptions = chart.options;
  7206. helpers$1.each(chart.scales, function(scale) {
  7207. core_layouts.removeBox(chart, scale);
  7208. });
  7209. newOptions = mergeConfig(
  7210. core_defaults.global,
  7211. core_defaults[chart.config.type],
  7212. newOptions);
  7213. chart.options = chart.config.options = newOptions;
  7214. chart.ensureScalesHaveIDs();
  7215. chart.buildOrUpdateScales();
  7216. // Tooltip
  7217. chart.tooltip._options = newOptions.tooltips;
  7218. chart.tooltip.initialize();
  7219. }
  7220. function positionIsHorizontal(position) {
  7221. return position === 'top' || position === 'bottom';
  7222. }
  7223. var Chart = function(item, config) {
  7224. this.construct(item, config);
  7225. return this;
  7226. };
  7227. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  7228. /**
  7229. * @private
  7230. */
  7231. construct: function(item, config) {
  7232. var me = this;
  7233. config = initConfig(config);
  7234. var context = platform.acquireContext(item, config);
  7235. var canvas = context && context.canvas;
  7236. var height = canvas && canvas.height;
  7237. var width = canvas && canvas.width;
  7238. me.id = helpers$1.uid();
  7239. me.ctx = context;
  7240. me.canvas = canvas;
  7241. me.config = config;
  7242. me.width = width;
  7243. me.height = height;
  7244. me.aspectRatio = height ? width / height : null;
  7245. me.options = config.options;
  7246. me._bufferedRender = false;
  7247. /**
  7248. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  7249. * the "instance" still need to be defined since it might be called from plugins.
  7250. * @prop Chart#chart
  7251. * @deprecated since version 2.6.0
  7252. * @todo remove at version 3
  7253. * @private
  7254. */
  7255. me.chart = me;
  7256. me.controller = me; // chart.chart.controller #inception
  7257. // Add the chart instance to the global namespace
  7258. Chart.instances[me.id] = me;
  7259. // Define alias to the config data: `chart.data === chart.config.data`
  7260. Object.defineProperty(me, 'data', {
  7261. get: function() {
  7262. return me.config.data;
  7263. },
  7264. set: function(value) {
  7265. me.config.data = value;
  7266. }
  7267. });
  7268. if (!context || !canvas) {
  7269. // The given item is not a compatible context2d element, let's return before finalizing
  7270. // the chart initialization but after setting basic chart / controller properties that
  7271. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  7272. // https://github.com/chartjs/Chart.js/issues/2807
  7273. console.error("Failed to create chart: can't acquire context from the given item");
  7274. return;
  7275. }
  7276. me.initialize();
  7277. me.update();
  7278. },
  7279. /**
  7280. * @private
  7281. */
  7282. initialize: function() {
  7283. var me = this;
  7284. // Before init plugin notification
  7285. core_plugins.notify(me, 'beforeInit');
  7286. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  7287. me.bindEvents();
  7288. if (me.options.responsive) {
  7289. // Initial resize before chart draws (must be silent to preserve initial animations).
  7290. me.resize(true);
  7291. }
  7292. // Make sure scales have IDs and are built before we build any controllers.
  7293. me.ensureScalesHaveIDs();
  7294. me.buildOrUpdateScales();
  7295. me.initToolTip();
  7296. // After init plugin notification
  7297. core_plugins.notify(me, 'afterInit');
  7298. return me;
  7299. },
  7300. clear: function() {
  7301. helpers$1.canvas.clear(this);
  7302. return this;
  7303. },
  7304. stop: function() {
  7305. // Stops any current animation loop occurring
  7306. core_animations.cancelAnimation(this);
  7307. return this;
  7308. },
  7309. resize: function(silent) {
  7310. var me = this;
  7311. var options = me.options;
  7312. var canvas = me.canvas;
  7313. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  7314. // the canvas render width and height will be casted to integers so make sure that
  7315. // the canvas display style uses the same integer values to avoid blurring effect.
  7316. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  7317. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  7318. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  7319. if (me.width === newWidth && me.height === newHeight) {
  7320. return;
  7321. }
  7322. canvas.width = me.width = newWidth;
  7323. canvas.height = me.height = newHeight;
  7324. canvas.style.width = newWidth + 'px';
  7325. canvas.style.height = newHeight + 'px';
  7326. helpers$1.retinaScale(me, options.devicePixelRatio);
  7327. if (!silent) {
  7328. // Notify any plugins about the resize
  7329. var newSize = {width: newWidth, height: newHeight};
  7330. core_plugins.notify(me, 'resize', [newSize]);
  7331. // Notify of resize
  7332. if (options.onResize) {
  7333. options.onResize(me, newSize);
  7334. }
  7335. me.stop();
  7336. me.update({
  7337. duration: options.responsiveAnimationDuration
  7338. });
  7339. }
  7340. },
  7341. ensureScalesHaveIDs: function() {
  7342. var options = this.options;
  7343. var scalesOptions = options.scales || {};
  7344. var scaleOptions = options.scale;
  7345. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  7346. xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
  7347. });
  7348. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  7349. yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
  7350. });
  7351. if (scaleOptions) {
  7352. scaleOptions.id = scaleOptions.id || 'scale';
  7353. }
  7354. },
  7355. /**
  7356. * Builds a map of scale ID to scale object for future lookup.
  7357. */
  7358. buildOrUpdateScales: function() {
  7359. var me = this;
  7360. var options = me.options;
  7361. var scales = me.scales || {};
  7362. var items = [];
  7363. var updated = Object.keys(scales).reduce(function(obj, id) {
  7364. obj[id] = false;
  7365. return obj;
  7366. }, {});
  7367. if (options.scales) {
  7368. items = items.concat(
  7369. (options.scales.xAxes || []).map(function(xAxisOptions) {
  7370. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  7371. }),
  7372. (options.scales.yAxes || []).map(function(yAxisOptions) {
  7373. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  7374. })
  7375. );
  7376. }
  7377. if (options.scale) {
  7378. items.push({
  7379. options: options.scale,
  7380. dtype: 'radialLinear',
  7381. isDefault: true,
  7382. dposition: 'chartArea'
  7383. });
  7384. }
  7385. helpers$1.each(items, function(item) {
  7386. var scaleOptions = item.options;
  7387. var id = scaleOptions.id;
  7388. var scaleType = valueOrDefault$8(scaleOptions.type, item.dtype);
  7389. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  7390. scaleOptions.position = item.dposition;
  7391. }
  7392. updated[id] = true;
  7393. var scale = null;
  7394. if (id in scales && scales[id].type === scaleType) {
  7395. scale = scales[id];
  7396. scale.options = scaleOptions;
  7397. scale.ctx = me.ctx;
  7398. scale.chart = me;
  7399. } else {
  7400. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  7401. if (!scaleClass) {
  7402. return;
  7403. }
  7404. scale = new scaleClass({
  7405. id: id,
  7406. type: scaleType,
  7407. options: scaleOptions,
  7408. ctx: me.ctx,
  7409. chart: me
  7410. });
  7411. scales[scale.id] = scale;
  7412. }
  7413. scale.mergeTicksOptions();
  7414. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  7415. // and consider it as a regular scale part of the "scales"" map only! This would
  7416. // make the logic easier and remove some useless? custom code.
  7417. if (item.isDefault) {
  7418. me.scale = scale;
  7419. }
  7420. });
  7421. // clear up discarded scales
  7422. helpers$1.each(updated, function(hasUpdated, id) {
  7423. if (!hasUpdated) {
  7424. delete scales[id];
  7425. }
  7426. });
  7427. me.scales = scales;
  7428. core_scaleService.addScalesToLayout(this);
  7429. },
  7430. buildOrUpdateControllers: function() {
  7431. var me = this;
  7432. var newControllers = [];
  7433. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  7434. var meta = me.getDatasetMeta(datasetIndex);
  7435. var type = dataset.type || me.config.type;
  7436. if (meta.type && meta.type !== type) {
  7437. me.destroyDatasetMeta(datasetIndex);
  7438. meta = me.getDatasetMeta(datasetIndex);
  7439. }
  7440. meta.type = type;
  7441. if (meta.controller) {
  7442. meta.controller.updateIndex(datasetIndex);
  7443. meta.controller.linkScales();
  7444. } else {
  7445. var ControllerClass = controllers[meta.type];
  7446. if (ControllerClass === undefined) {
  7447. throw new Error('"' + meta.type + '" is not a chart type.');
  7448. }
  7449. meta.controller = new ControllerClass(me, datasetIndex);
  7450. newControllers.push(meta.controller);
  7451. }
  7452. }, me);
  7453. return newControllers;
  7454. },
  7455. /**
  7456. * Reset the elements of all datasets
  7457. * @private
  7458. */
  7459. resetElements: function() {
  7460. var me = this;
  7461. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  7462. me.getDatasetMeta(datasetIndex).controller.reset();
  7463. }, me);
  7464. },
  7465. /**
  7466. * Resets the chart back to it's state before the initial animation
  7467. */
  7468. reset: function() {
  7469. this.resetElements();
  7470. this.tooltip.initialize();
  7471. },
  7472. update: function(config) {
  7473. var me = this;
  7474. if (!config || typeof config !== 'object') {
  7475. // backwards compatibility
  7476. config = {
  7477. duration: config,
  7478. lazy: arguments[1]
  7479. };
  7480. }
  7481. updateConfig(me);
  7482. // plugins options references might have change, let's invalidate the cache
  7483. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  7484. core_plugins._invalidate(me);
  7485. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  7486. return;
  7487. }
  7488. // In case the entire data object changed
  7489. me.tooltip._data = me.data;
  7490. // Make sure dataset controllers are updated and new controllers are reset
  7491. var newControllers = me.buildOrUpdateControllers();
  7492. // Make sure all dataset controllers have correct meta data counts
  7493. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  7494. me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
  7495. }, me);
  7496. me.updateLayout();
  7497. // Can only reset the new controllers after the scales have been updated
  7498. if (me.options.animation && me.options.animation.duration) {
  7499. helpers$1.each(newControllers, function(controller) {
  7500. controller.reset();
  7501. });
  7502. }
  7503. me.updateDatasets();
  7504. // Need to reset tooltip in case it is displayed with elements that are removed
  7505. // after update.
  7506. me.tooltip.initialize();
  7507. // Last active contains items that were previously in the tooltip.
  7508. // When we reset the tooltip, we need to clear it
  7509. me.lastActive = [];
  7510. // Do this before render so that any plugins that need final scale updates can use it
  7511. core_plugins.notify(me, 'afterUpdate');
  7512. if (me._bufferedRender) {
  7513. me._bufferedRequest = {
  7514. duration: config.duration,
  7515. easing: config.easing,
  7516. lazy: config.lazy
  7517. };
  7518. } else {
  7519. me.render(config);
  7520. }
  7521. },
  7522. /**
  7523. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  7524. * hook, in which case, plugins will not be called on `afterLayout`.
  7525. * @private
  7526. */
  7527. updateLayout: function() {
  7528. var me = this;
  7529. if (core_plugins.notify(me, 'beforeLayout') === false) {
  7530. return;
  7531. }
  7532. core_layouts.update(this, this.width, this.height);
  7533. /**
  7534. * Provided for backward compatibility, use `afterLayout` instead.
  7535. * @method IPlugin#afterScaleUpdate
  7536. * @deprecated since version 2.5.0
  7537. * @todo remove at version 3
  7538. * @private
  7539. */
  7540. core_plugins.notify(me, 'afterScaleUpdate');
  7541. core_plugins.notify(me, 'afterLayout');
  7542. },
  7543. /**
  7544. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  7545. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  7546. * @private
  7547. */
  7548. updateDatasets: function() {
  7549. var me = this;
  7550. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  7551. return;
  7552. }
  7553. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  7554. me.updateDataset(i);
  7555. }
  7556. core_plugins.notify(me, 'afterDatasetsUpdate');
  7557. },
  7558. /**
  7559. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  7560. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  7561. * @private
  7562. */
  7563. updateDataset: function(index) {
  7564. var me = this;
  7565. var meta = me.getDatasetMeta(index);
  7566. var args = {
  7567. meta: meta,
  7568. index: index
  7569. };
  7570. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  7571. return;
  7572. }
  7573. meta.controller.update();
  7574. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  7575. },
  7576. render: function(config) {
  7577. var me = this;
  7578. if (!config || typeof config !== 'object') {
  7579. // backwards compatibility
  7580. config = {
  7581. duration: config,
  7582. lazy: arguments[1]
  7583. };
  7584. }
  7585. var animationOptions = me.options.animation;
  7586. var duration = valueOrDefault$8(config.duration, animationOptions && animationOptions.duration);
  7587. var lazy = config.lazy;
  7588. if (core_plugins.notify(me, 'beforeRender') === false) {
  7589. return;
  7590. }
  7591. var onComplete = function(animation) {
  7592. core_plugins.notify(me, 'afterRender');
  7593. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  7594. };
  7595. if (animationOptions && duration) {
  7596. var animation = new core_animation({
  7597. numSteps: duration / 16.66, // 60 fps
  7598. easing: config.easing || animationOptions.easing,
  7599. render: function(chart, animationObject) {
  7600. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  7601. var currentStep = animationObject.currentStep;
  7602. var stepDecimal = currentStep / animationObject.numSteps;
  7603. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  7604. },
  7605. onAnimationProgress: animationOptions.onProgress,
  7606. onAnimationComplete: onComplete
  7607. });
  7608. core_animations.addAnimation(me, animation, duration, lazy);
  7609. } else {
  7610. me.draw();
  7611. // See https://github.com/chartjs/Chart.js/issues/3781
  7612. onComplete(new core_animation({numSteps: 0, chart: me}));
  7613. }
  7614. return me;
  7615. },
  7616. draw: function(easingValue) {
  7617. var me = this;
  7618. me.clear();
  7619. if (helpers$1.isNullOrUndef(easingValue)) {
  7620. easingValue = 1;
  7621. }
  7622. me.transition(easingValue);
  7623. if (me.width <= 0 || me.height <= 0) {
  7624. return;
  7625. }
  7626. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  7627. return;
  7628. }
  7629. // Draw all the scales
  7630. helpers$1.each(me.boxes, function(box) {
  7631. box.draw(me.chartArea);
  7632. }, me);
  7633. me.drawDatasets(easingValue);
  7634. me._drawTooltip(easingValue);
  7635. core_plugins.notify(me, 'afterDraw', [easingValue]);
  7636. },
  7637. /**
  7638. * @private
  7639. */
  7640. transition: function(easingValue) {
  7641. var me = this;
  7642. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  7643. if (me.isDatasetVisible(i)) {
  7644. me.getDatasetMeta(i).controller.transition(easingValue);
  7645. }
  7646. }
  7647. me.tooltip.transition(easingValue);
  7648. },
  7649. /**
  7650. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  7651. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  7652. * @private
  7653. */
  7654. drawDatasets: function(easingValue) {
  7655. var me = this;
  7656. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  7657. return;
  7658. }
  7659. // Draw datasets reversed to support proper line stacking
  7660. for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {
  7661. if (me.isDatasetVisible(i)) {
  7662. me.drawDataset(i, easingValue);
  7663. }
  7664. }
  7665. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  7666. },
  7667. /**
  7668. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  7669. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  7670. * @private
  7671. */
  7672. drawDataset: function(index, easingValue) {
  7673. var me = this;
  7674. var meta = me.getDatasetMeta(index);
  7675. var args = {
  7676. meta: meta,
  7677. index: index,
  7678. easingValue: easingValue
  7679. };
  7680. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  7681. return;
  7682. }
  7683. meta.controller.draw(easingValue);
  7684. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  7685. },
  7686. /**
  7687. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  7688. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  7689. * @private
  7690. */
  7691. _drawTooltip: function(easingValue) {
  7692. var me = this;
  7693. var tooltip = me.tooltip;
  7694. var args = {
  7695. tooltip: tooltip,
  7696. easingValue: easingValue
  7697. };
  7698. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  7699. return;
  7700. }
  7701. tooltip.draw();
  7702. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  7703. },
  7704. /**
  7705. * Get the single element that was clicked on
  7706. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  7707. */
  7708. getElementAtEvent: function(e) {
  7709. return core_interaction.modes.single(this, e);
  7710. },
  7711. getElementsAtEvent: function(e) {
  7712. return core_interaction.modes.label(this, e, {intersect: true});
  7713. },
  7714. getElementsAtXAxis: function(e) {
  7715. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  7716. },
  7717. getElementsAtEventForMode: function(e, mode, options) {
  7718. var method = core_interaction.modes[mode];
  7719. if (typeof method === 'function') {
  7720. return method(this, e, options);
  7721. }
  7722. return [];
  7723. },
  7724. getDatasetAtEvent: function(e) {
  7725. return core_interaction.modes.dataset(this, e, {intersect: true});
  7726. },
  7727. getDatasetMeta: function(datasetIndex) {
  7728. var me = this;
  7729. var dataset = me.data.datasets[datasetIndex];
  7730. if (!dataset._meta) {
  7731. dataset._meta = {};
  7732. }
  7733. var meta = dataset._meta[me.id];
  7734. if (!meta) {
  7735. meta = dataset._meta[me.id] = {
  7736. type: null,
  7737. data: [],
  7738. dataset: null,
  7739. controller: null,
  7740. hidden: null, // See isDatasetVisible() comment
  7741. xAxisID: null,
  7742. yAxisID: null
  7743. };
  7744. }
  7745. return meta;
  7746. },
  7747. getVisibleDatasetCount: function() {
  7748. var count = 0;
  7749. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  7750. if (this.isDatasetVisible(i)) {
  7751. count++;
  7752. }
  7753. }
  7754. return count;
  7755. },
  7756. isDatasetVisible: function(datasetIndex) {
  7757. var meta = this.getDatasetMeta(datasetIndex);
  7758. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  7759. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  7760. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  7761. },
  7762. generateLegend: function() {
  7763. return this.options.legendCallback(this);
  7764. },
  7765. /**
  7766. * @private
  7767. */
  7768. destroyDatasetMeta: function(datasetIndex) {
  7769. var id = this.id;
  7770. var dataset = this.data.datasets[datasetIndex];
  7771. var meta = dataset._meta && dataset._meta[id];
  7772. if (meta) {
  7773. meta.controller.destroy();
  7774. delete dataset._meta[id];
  7775. }
  7776. },
  7777. destroy: function() {
  7778. var me = this;
  7779. var canvas = me.canvas;
  7780. var i, ilen;
  7781. me.stop();
  7782. // dataset controllers need to cleanup associated data
  7783. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  7784. me.destroyDatasetMeta(i);
  7785. }
  7786. if (canvas) {
  7787. me.unbindEvents();
  7788. helpers$1.canvas.clear(me);
  7789. platform.releaseContext(me.ctx);
  7790. me.canvas = null;
  7791. me.ctx = null;
  7792. }
  7793. core_plugins.notify(me, 'destroy');
  7794. delete Chart.instances[me.id];
  7795. },
  7796. toBase64Image: function() {
  7797. return this.canvas.toDataURL.apply(this.canvas, arguments);
  7798. },
  7799. initToolTip: function() {
  7800. var me = this;
  7801. me.tooltip = new core_tooltip({
  7802. _chart: me,
  7803. _chartInstance: me, // deprecated, backward compatibility
  7804. _data: me.data,
  7805. _options: me.options.tooltips
  7806. }, me);
  7807. },
  7808. /**
  7809. * @private
  7810. */
  7811. bindEvents: function() {
  7812. var me = this;
  7813. var listeners = me._listeners = {};
  7814. var listener = function() {
  7815. me.eventHandler.apply(me, arguments);
  7816. };
  7817. helpers$1.each(me.options.events, function(type) {
  7818. platform.addEventListener(me, type, listener);
  7819. listeners[type] = listener;
  7820. });
  7821. // Elements used to detect size change should not be injected for non responsive charts.
  7822. // See https://github.com/chartjs/Chart.js/issues/2210
  7823. if (me.options.responsive) {
  7824. listener = function() {
  7825. me.resize();
  7826. };
  7827. platform.addEventListener(me, 'resize', listener);
  7828. listeners.resize = listener;
  7829. }
  7830. },
  7831. /**
  7832. * @private
  7833. */
  7834. unbindEvents: function() {
  7835. var me = this;
  7836. var listeners = me._listeners;
  7837. if (!listeners) {
  7838. return;
  7839. }
  7840. delete me._listeners;
  7841. helpers$1.each(listeners, function(listener, type) {
  7842. platform.removeEventListener(me, type, listener);
  7843. });
  7844. },
  7845. updateHoverStyle: function(elements, mode, enabled) {
  7846. var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';
  7847. var element, i, ilen;
  7848. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  7849. element = elements[i];
  7850. if (element) {
  7851. this.getDatasetMeta(element._datasetIndex).controller[method](element);
  7852. }
  7853. }
  7854. },
  7855. /**
  7856. * @private
  7857. */
  7858. eventHandler: function(e) {
  7859. var me = this;
  7860. var tooltip = me.tooltip;
  7861. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  7862. return;
  7863. }
  7864. // Buffer any update calls so that renders do not occur
  7865. me._bufferedRender = true;
  7866. me._bufferedRequest = null;
  7867. var changed = me.handleEvent(e);
  7868. // for smooth tooltip animations issue #4989
  7869. // the tooltip should be the source of change
  7870. // Animation check workaround:
  7871. // tooltip._start will be null when tooltip isn't animating
  7872. if (tooltip) {
  7873. changed = tooltip._start
  7874. ? tooltip.handleEvent(e)
  7875. : changed | tooltip.handleEvent(e);
  7876. }
  7877. core_plugins.notify(me, 'afterEvent', [e]);
  7878. var bufferedRequest = me._bufferedRequest;
  7879. if (bufferedRequest) {
  7880. // If we have an update that was triggered, we need to do a normal render
  7881. me.render(bufferedRequest);
  7882. } else if (changed && !me.animating) {
  7883. // If entering, leaving, or changing elements, animate the change via pivot
  7884. me.stop();
  7885. // We only need to render at this point. Updating will cause scales to be
  7886. // recomputed generating flicker & using more memory than necessary.
  7887. me.render({
  7888. duration: me.options.hover.animationDuration,
  7889. lazy: true
  7890. });
  7891. }
  7892. me._bufferedRender = false;
  7893. me._bufferedRequest = null;
  7894. return me;
  7895. },
  7896. /**
  7897. * Handle an event
  7898. * @private
  7899. * @param {IEvent} event the event to handle
  7900. * @return {boolean} true if the chart needs to re-render
  7901. */
  7902. handleEvent: function(e) {
  7903. var me = this;
  7904. var options = me.options || {};
  7905. var hoverOptions = options.hover;
  7906. var changed = false;
  7907. me.lastActive = me.lastActive || [];
  7908. // Find Active Elements for hover and tooltips
  7909. if (e.type === 'mouseout') {
  7910. me.active = [];
  7911. } else {
  7912. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  7913. }
  7914. // Invoke onHover hook
  7915. // Need to call with native event here to not break backwards compatibility
  7916. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  7917. if (e.type === 'mouseup' || e.type === 'click') {
  7918. if (options.onClick) {
  7919. // Use e.native here for backwards compatibility
  7920. options.onClick.call(me, e.native, me.active);
  7921. }
  7922. }
  7923. // Remove styling for last active (even if it may still be active)
  7924. if (me.lastActive.length) {
  7925. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  7926. }
  7927. // Built in hover styling
  7928. if (me.active.length && hoverOptions.mode) {
  7929. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  7930. }
  7931. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  7932. // Remember Last Actives
  7933. me.lastActive = me.active;
  7934. return changed;
  7935. }
  7936. });
  7937. /**
  7938. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  7939. * for backward compatibility. Though, it can still be useful for plugins that
  7940. * would need to work on multiple charts?!
  7941. */
  7942. Chart.instances = {};
  7943. var core_controller = Chart;
  7944. // DEPRECATIONS
  7945. /**
  7946. * Provided for backward compatibility, use Chart instead.
  7947. * @class Chart.Controller
  7948. * @deprecated since version 2.6
  7949. * @todo remove at version 3
  7950. * @private
  7951. */
  7952. Chart.Controller = Chart;
  7953. /**
  7954. * Provided for backward compatibility, not available anymore.
  7955. * @namespace Chart
  7956. * @deprecated since version 2.8
  7957. * @todo remove at version 3
  7958. * @private
  7959. */
  7960. Chart.types = {};
  7961. /**
  7962. * Provided for backward compatibility, not available anymore.
  7963. * @namespace Chart.helpers.configMerge
  7964. * @deprecated since version 2.8.0
  7965. * @todo remove at version 3
  7966. * @private
  7967. */
  7968. helpers$1.configMerge = mergeConfig;
  7969. /**
  7970. * Provided for backward compatibility, not available anymore.
  7971. * @namespace Chart.helpers.scaleMerge
  7972. * @deprecated since version 2.8.0
  7973. * @todo remove at version 3
  7974. * @private
  7975. */
  7976. helpers$1.scaleMerge = mergeScaleConfig;
  7977. var core_helpers = function() {
  7978. // -- Basic js utility methods
  7979. helpers$1.where = function(collection, filterCallback) {
  7980. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  7981. return collection.filter(filterCallback);
  7982. }
  7983. var filtered = [];
  7984. helpers$1.each(collection, function(item) {
  7985. if (filterCallback(item)) {
  7986. filtered.push(item);
  7987. }
  7988. });
  7989. return filtered;
  7990. };
  7991. helpers$1.findIndex = Array.prototype.findIndex ?
  7992. function(array, callback, scope) {
  7993. return array.findIndex(callback, scope);
  7994. } :
  7995. function(array, callback, scope) {
  7996. scope = scope === undefined ? array : scope;
  7997. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  7998. if (callback.call(scope, array[i], i, array)) {
  7999. return i;
  8000. }
  8001. }
  8002. return -1;
  8003. };
  8004. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  8005. // Default to start of the array
  8006. if (helpers$1.isNullOrUndef(startIndex)) {
  8007. startIndex = -1;
  8008. }
  8009. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8010. var currentItem = arrayToSearch[i];
  8011. if (filterCallback(currentItem)) {
  8012. return currentItem;
  8013. }
  8014. }
  8015. };
  8016. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8017. // Default to end of the array
  8018. if (helpers$1.isNullOrUndef(startIndex)) {
  8019. startIndex = arrayToSearch.length;
  8020. }
  8021. for (var i = startIndex - 1; i >= 0; i--) {
  8022. var currentItem = arrayToSearch[i];
  8023. if (filterCallback(currentItem)) {
  8024. return currentItem;
  8025. }
  8026. }
  8027. };
  8028. // -- Math methods
  8029. helpers$1.isNumber = function(n) {
  8030. return !isNaN(parseFloat(n)) && isFinite(n);
  8031. };
  8032. helpers$1.almostEquals = function(x, y, epsilon) {
  8033. return Math.abs(x - y) < epsilon;
  8034. };
  8035. helpers$1.almostWhole = function(x, epsilon) {
  8036. var rounded = Math.round(x);
  8037. return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
  8038. };
  8039. helpers$1.max = function(array) {
  8040. return array.reduce(function(max, value) {
  8041. if (!isNaN(value)) {
  8042. return Math.max(max, value);
  8043. }
  8044. return max;
  8045. }, Number.NEGATIVE_INFINITY);
  8046. };
  8047. helpers$1.min = function(array) {
  8048. return array.reduce(function(min, value) {
  8049. if (!isNaN(value)) {
  8050. return Math.min(min, value);
  8051. }
  8052. return min;
  8053. }, Number.POSITIVE_INFINITY);
  8054. };
  8055. helpers$1.sign = Math.sign ?
  8056. function(x) {
  8057. return Math.sign(x);
  8058. } :
  8059. function(x) {
  8060. x = +x; // convert to a number
  8061. if (x === 0 || isNaN(x)) {
  8062. return x;
  8063. }
  8064. return x > 0 ? 1 : -1;
  8065. };
  8066. helpers$1.log10 = Math.log10 ?
  8067. function(x) {
  8068. return Math.log10(x);
  8069. } :
  8070. function(x) {
  8071. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  8072. // Check for whole powers of 10,
  8073. // which due to floating point rounding error should be corrected.
  8074. var powerOf10 = Math.round(exponent);
  8075. var isPowerOf10 = x === Math.pow(10, powerOf10);
  8076. return isPowerOf10 ? powerOf10 : exponent;
  8077. };
  8078. helpers$1.toRadians = function(degrees) {
  8079. return degrees * (Math.PI / 180);
  8080. };
  8081. helpers$1.toDegrees = function(radians) {
  8082. return radians * (180 / Math.PI);
  8083. };
  8084. /**
  8085. * Returns the number of decimal places
  8086. * i.e. the number of digits after the decimal point, of the value of this Number.
  8087. * @param {number} x - A number.
  8088. * @returns {number} The number of decimal places.
  8089. * @private
  8090. */
  8091. helpers$1._decimalPlaces = function(x) {
  8092. if (!helpers$1.isFinite(x)) {
  8093. return;
  8094. }
  8095. var e = 1;
  8096. var p = 0;
  8097. while (Math.round(x * e) / e !== x) {
  8098. e *= 10;
  8099. p++;
  8100. }
  8101. return p;
  8102. };
  8103. // Gets the angle from vertical upright to the point about a centre.
  8104. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  8105. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8106. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8107. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8108. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8109. if (angle < (-0.5 * Math.PI)) {
  8110. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8111. }
  8112. return {
  8113. angle: angle,
  8114. distance: radialDistanceFromCenter
  8115. };
  8116. };
  8117. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  8118. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8119. };
  8120. /**
  8121. * Provided for backward compatibility, not available anymore
  8122. * @function Chart.helpers.aliasPixel
  8123. * @deprecated since version 2.8.0
  8124. * @todo remove at version 3
  8125. */
  8126. helpers$1.aliasPixel = function(pixelWidth) {
  8127. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8128. };
  8129. /**
  8130. * Returns the aligned pixel value to avoid anti-aliasing blur
  8131. * @param {Chart} chart - The chart instance.
  8132. * @param {number} pixel - A pixel value.
  8133. * @param {number} width - The width of the element.
  8134. * @returns {number} The aligned pixel value.
  8135. * @private
  8136. */
  8137. helpers$1._alignPixel = function(chart, pixel, width) {
  8138. var devicePixelRatio = chart.currentDevicePixelRatio;
  8139. var halfWidth = width / 2;
  8140. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8141. };
  8142. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8143. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8144. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8145. // This function must also respect "skipped" points
  8146. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8147. var current = middlePoint;
  8148. var next = afterPoint.skip ? middlePoint : afterPoint;
  8149. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8150. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8151. var s01 = d01 / (d01 + d12);
  8152. var s12 = d12 / (d01 + d12);
  8153. // If all points are the same, s01 & s02 will be inf
  8154. s01 = isNaN(s01) ? 0 : s01;
  8155. s12 = isNaN(s12) ? 0 : s12;
  8156. var fa = t * s01; // scaling factor for triangle Ta
  8157. var fb = t * s12;
  8158. return {
  8159. previous: {
  8160. x: current.x - fa * (next.x - previous.x),
  8161. y: current.y - fa * (next.y - previous.y)
  8162. },
  8163. next: {
  8164. x: current.x + fb * (next.x - previous.x),
  8165. y: current.y + fb * (next.y - previous.y)
  8166. }
  8167. };
  8168. };
  8169. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  8170. helpers$1.splineCurveMonotone = function(points) {
  8171. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8172. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8173. // between the dataset discrete points due to the interpolation.
  8174. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8175. var pointsWithTangents = (points || []).map(function(point) {
  8176. return {
  8177. model: point._model,
  8178. deltaK: 0,
  8179. mK: 0
  8180. };
  8181. });
  8182. // Calculate slopes (deltaK) and initialize tangents (mK)
  8183. var pointsLen = pointsWithTangents.length;
  8184. var i, pointBefore, pointCurrent, pointAfter;
  8185. for (i = 0; i < pointsLen; ++i) {
  8186. pointCurrent = pointsWithTangents[i];
  8187. if (pointCurrent.model.skip) {
  8188. continue;
  8189. }
  8190. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8191. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8192. if (pointAfter && !pointAfter.model.skip) {
  8193. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8194. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  8195. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  8196. }
  8197. if (!pointBefore || pointBefore.model.skip) {
  8198. pointCurrent.mK = pointCurrent.deltaK;
  8199. } else if (!pointAfter || pointAfter.model.skip) {
  8200. pointCurrent.mK = pointBefore.deltaK;
  8201. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  8202. pointCurrent.mK = 0;
  8203. } else {
  8204. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  8205. }
  8206. }
  8207. // Adjust tangents to ensure monotonic properties
  8208. var alphaK, betaK, tauK, squaredMagnitude;
  8209. for (i = 0; i < pointsLen - 1; ++i) {
  8210. pointCurrent = pointsWithTangents[i];
  8211. pointAfter = pointsWithTangents[i + 1];
  8212. if (pointCurrent.model.skip || pointAfter.model.skip) {
  8213. continue;
  8214. }
  8215. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  8216. pointCurrent.mK = pointAfter.mK = 0;
  8217. continue;
  8218. }
  8219. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  8220. betaK = pointAfter.mK / pointCurrent.deltaK;
  8221. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  8222. if (squaredMagnitude <= 9) {
  8223. continue;
  8224. }
  8225. tauK = 3 / Math.sqrt(squaredMagnitude);
  8226. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  8227. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  8228. }
  8229. // Compute control points
  8230. var deltaX;
  8231. for (i = 0; i < pointsLen; ++i) {
  8232. pointCurrent = pointsWithTangents[i];
  8233. if (pointCurrent.model.skip) {
  8234. continue;
  8235. }
  8236. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8237. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8238. if (pointBefore && !pointBefore.model.skip) {
  8239. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  8240. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  8241. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  8242. }
  8243. if (pointAfter && !pointAfter.model.skip) {
  8244. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  8245. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  8246. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  8247. }
  8248. }
  8249. };
  8250. helpers$1.nextItem = function(collection, index, loop) {
  8251. if (loop) {
  8252. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  8253. }
  8254. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  8255. };
  8256. helpers$1.previousItem = function(collection, index, loop) {
  8257. if (loop) {
  8258. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  8259. }
  8260. return index <= 0 ? collection[0] : collection[index - 1];
  8261. };
  8262. // Implementation of the nice number algorithm used in determining where axis labels will go
  8263. helpers$1.niceNum = function(range, round) {
  8264. var exponent = Math.floor(helpers$1.log10(range));
  8265. var fraction = range / Math.pow(10, exponent);
  8266. var niceFraction;
  8267. if (round) {
  8268. if (fraction < 1.5) {
  8269. niceFraction = 1;
  8270. } else if (fraction < 3) {
  8271. niceFraction = 2;
  8272. } else if (fraction < 7) {
  8273. niceFraction = 5;
  8274. } else {
  8275. niceFraction = 10;
  8276. }
  8277. } else if (fraction <= 1.0) {
  8278. niceFraction = 1;
  8279. } else if (fraction <= 2) {
  8280. niceFraction = 2;
  8281. } else if (fraction <= 5) {
  8282. niceFraction = 5;
  8283. } else {
  8284. niceFraction = 10;
  8285. }
  8286. return niceFraction * Math.pow(10, exponent);
  8287. };
  8288. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  8289. helpers$1.requestAnimFrame = (function() {
  8290. if (typeof window === 'undefined') {
  8291. return function(callback) {
  8292. callback();
  8293. };
  8294. }
  8295. return window.requestAnimationFrame ||
  8296. window.webkitRequestAnimationFrame ||
  8297. window.mozRequestAnimationFrame ||
  8298. window.oRequestAnimationFrame ||
  8299. window.msRequestAnimationFrame ||
  8300. function(callback) {
  8301. return window.setTimeout(callback, 1000 / 60);
  8302. };
  8303. }());
  8304. // -- DOM methods
  8305. helpers$1.getRelativePosition = function(evt, chart) {
  8306. var mouseX, mouseY;
  8307. var e = evt.originalEvent || evt;
  8308. var canvas = evt.target || evt.srcElement;
  8309. var boundingRect = canvas.getBoundingClientRect();
  8310. var touches = e.touches;
  8311. if (touches && touches.length > 0) {
  8312. mouseX = touches[0].clientX;
  8313. mouseY = touches[0].clientY;
  8314. } else {
  8315. mouseX = e.clientX;
  8316. mouseY = e.clientY;
  8317. }
  8318. // Scale mouse coordinates into canvas coordinates
  8319. // by following the pattern laid out by 'jerryj' in the comments of
  8320. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  8321. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  8322. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  8323. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  8324. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  8325. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  8326. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  8327. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  8328. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  8329. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  8330. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  8331. return {
  8332. x: mouseX,
  8333. y: mouseY
  8334. };
  8335. };
  8336. // Private helper function to convert max-width/max-height values that may be percentages into a number
  8337. function parseMaxStyle(styleValue, node, parentProperty) {
  8338. var valueInPixels;
  8339. if (typeof styleValue === 'string') {
  8340. valueInPixels = parseInt(styleValue, 10);
  8341. if (styleValue.indexOf('%') !== -1) {
  8342. // percentage * size in dimension
  8343. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  8344. }
  8345. } else {
  8346. valueInPixels = styleValue;
  8347. }
  8348. return valueInPixels;
  8349. }
  8350. /**
  8351. * Returns if the given value contains an effective constraint.
  8352. * @private
  8353. */
  8354. function isConstrainedValue(value) {
  8355. return value !== undefined && value !== null && value !== 'none';
  8356. }
  8357. /**
  8358. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  8359. * @param {HTMLElement} domNode - the node to check the constraint on
  8360. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  8361. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  8362. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  8363. */
  8364. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  8365. var view = document.defaultView;
  8366. var parentNode = helpers$1._getParentNode(domNode);
  8367. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  8368. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  8369. var hasCNode = isConstrainedValue(constrainedNode);
  8370. var hasCContainer = isConstrainedValue(constrainedContainer);
  8371. var infinity = Number.POSITIVE_INFINITY;
  8372. if (hasCNode || hasCContainer) {
  8373. return Math.min(
  8374. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  8375. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  8376. }
  8377. return 'none';
  8378. }
  8379. // returns Number or undefined if no constraint
  8380. helpers$1.getConstraintWidth = function(domNode) {
  8381. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  8382. };
  8383. // returns Number or undefined if no constraint
  8384. helpers$1.getConstraintHeight = function(domNode) {
  8385. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  8386. };
  8387. /**
  8388. * @private
  8389. */
  8390. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  8391. padding = helpers$1.getStyle(container, padding);
  8392. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  8393. };
  8394. /**
  8395. * @private
  8396. */
  8397. helpers$1._getParentNode = function(domNode) {
  8398. var parent = domNode.parentNode;
  8399. if (parent && parent.toString() === '[object ShadowRoot]') {
  8400. parent = parent.host;
  8401. }
  8402. return parent;
  8403. };
  8404. helpers$1.getMaximumWidth = function(domNode) {
  8405. var container = helpers$1._getParentNode(domNode);
  8406. if (!container) {
  8407. return domNode.clientWidth;
  8408. }
  8409. var clientWidth = container.clientWidth;
  8410. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  8411. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  8412. var w = clientWidth - paddingLeft - paddingRight;
  8413. var cw = helpers$1.getConstraintWidth(domNode);
  8414. return isNaN(cw) ? w : Math.min(w, cw);
  8415. };
  8416. helpers$1.getMaximumHeight = function(domNode) {
  8417. var container = helpers$1._getParentNode(domNode);
  8418. if (!container) {
  8419. return domNode.clientHeight;
  8420. }
  8421. var clientHeight = container.clientHeight;
  8422. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  8423. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  8424. var h = clientHeight - paddingTop - paddingBottom;
  8425. var ch = helpers$1.getConstraintHeight(domNode);
  8426. return isNaN(ch) ? h : Math.min(h, ch);
  8427. };
  8428. helpers$1.getStyle = function(el, property) {
  8429. return el.currentStyle ?
  8430. el.currentStyle[property] :
  8431. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  8432. };
  8433. helpers$1.retinaScale = function(chart, forceRatio) {
  8434. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  8435. if (pixelRatio === 1) {
  8436. return;
  8437. }
  8438. var canvas = chart.canvas;
  8439. var height = chart.height;
  8440. var width = chart.width;
  8441. canvas.height = height * pixelRatio;
  8442. canvas.width = width * pixelRatio;
  8443. chart.ctx.scale(pixelRatio, pixelRatio);
  8444. // If no style has been set on the canvas, the render size is used as display size,
  8445. // making the chart visually bigger, so let's enforce it to the "correct" values.
  8446. // See https://github.com/chartjs/Chart.js/issues/3575
  8447. if (!canvas.style.height && !canvas.style.width) {
  8448. canvas.style.height = height + 'px';
  8449. canvas.style.width = width + 'px';
  8450. }
  8451. };
  8452. // -- Canvas methods
  8453. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  8454. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  8455. };
  8456. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  8457. cache = cache || {};
  8458. var data = cache.data = cache.data || {};
  8459. var gc = cache.garbageCollect = cache.garbageCollect || [];
  8460. if (cache.font !== font) {
  8461. data = cache.data = {};
  8462. gc = cache.garbageCollect = [];
  8463. cache.font = font;
  8464. }
  8465. ctx.font = font;
  8466. var longest = 0;
  8467. helpers$1.each(arrayOfThings, function(thing) {
  8468. // Undefined strings and arrays should not be measured
  8469. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  8470. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  8471. } else if (helpers$1.isArray(thing)) {
  8472. // if it is an array lets measure each element
  8473. // to do maybe simplify this function a bit so we can do this more recursively?
  8474. helpers$1.each(thing, function(nestedThing) {
  8475. // Undefined strings and arrays should not be measured
  8476. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  8477. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  8478. }
  8479. });
  8480. }
  8481. });
  8482. var gcLen = gc.length / 2;
  8483. if (gcLen > arrayOfThings.length) {
  8484. for (var i = 0; i < gcLen; i++) {
  8485. delete data[gc[i]];
  8486. }
  8487. gc.splice(0, gcLen);
  8488. }
  8489. return longest;
  8490. };
  8491. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  8492. var textWidth = data[string];
  8493. if (!textWidth) {
  8494. textWidth = data[string] = ctx.measureText(string).width;
  8495. gc.push(string);
  8496. }
  8497. if (textWidth > longest) {
  8498. longest = textWidth;
  8499. }
  8500. return longest;
  8501. };
  8502. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  8503. var numberOfLines = 1;
  8504. helpers$1.each(arrayOfThings, function(thing) {
  8505. if (helpers$1.isArray(thing)) {
  8506. if (thing.length > numberOfLines) {
  8507. numberOfLines = thing.length;
  8508. }
  8509. }
  8510. });
  8511. return numberOfLines;
  8512. };
  8513. helpers$1.color = !chartjsColor ?
  8514. function(value) {
  8515. console.error('Color.js not found!');
  8516. return value;
  8517. } :
  8518. function(value) {
  8519. /* global CanvasGradient */
  8520. if (value instanceof CanvasGradient) {
  8521. value = core_defaults.global.defaultColor;
  8522. }
  8523. return chartjsColor(value);
  8524. };
  8525. helpers$1.getHoverColor = function(colorValue) {
  8526. /* global CanvasPattern */
  8527. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  8528. colorValue :
  8529. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  8530. };
  8531. };
  8532. function abstract() {
  8533. throw new Error(
  8534. 'This method is not implemented: either no adapter can ' +
  8535. 'be found or an incomplete integration was provided.'
  8536. );
  8537. }
  8538. /**
  8539. * Date adapter (current used by the time scale)
  8540. * @namespace Chart._adapters._date
  8541. * @memberof Chart._adapters
  8542. * @private
  8543. */
  8544. /**
  8545. * Currently supported unit string values.
  8546. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  8547. * @memberof Chart._adapters._date
  8548. * @name Unit
  8549. */
  8550. /**
  8551. * @class
  8552. */
  8553. function DateAdapter(options) {
  8554. this.options = options || {};
  8555. }
  8556. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  8557. /**
  8558. * Returns a map of time formats for the supported formatting units defined
  8559. * in Unit as well as 'datetime' representing a detailed date/time string.
  8560. * @returns {{string: string}}
  8561. */
  8562. formats: abstract,
  8563. /**
  8564. * Parses the given `value` and return the associated timestamp.
  8565. * @param {any} value - the value to parse (usually comes from the data)
  8566. * @param {string} [format] - the expected data format
  8567. * @returns {(number|null)}
  8568. * @function
  8569. */
  8570. parse: abstract,
  8571. /**
  8572. * Returns the formatted date in the specified `format` for a given `timestamp`.
  8573. * @param {number} timestamp - the timestamp to format
  8574. * @param {string} format - the date/time token
  8575. * @return {string}
  8576. * @function
  8577. */
  8578. format: abstract,
  8579. /**
  8580. * Adds the specified `amount` of `unit` to the given `timestamp`.
  8581. * @param {number} timestamp - the input timestamp
  8582. * @param {number} amount - the amount to add
  8583. * @param {Unit} unit - the unit as string
  8584. * @return {number}
  8585. * @function
  8586. */
  8587. add: abstract,
  8588. /**
  8589. * Returns the number of `unit` between the given timestamps.
  8590. * @param {number} max - the input timestamp (reference)
  8591. * @param {number} min - the timestamp to substract
  8592. * @param {Unit} unit - the unit as string
  8593. * @return {number}
  8594. * @function
  8595. */
  8596. diff: abstract,
  8597. /**
  8598. * Returns start of `unit` for the given `timestamp`.
  8599. * @param {number} timestamp - the input timestamp
  8600. * @param {Unit} unit - the unit as string
  8601. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  8602. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  8603. * @function
  8604. */
  8605. startOf: abstract,
  8606. /**
  8607. * Returns end of `unit` for the given `timestamp`.
  8608. * @param {number} timestamp - the input timestamp
  8609. * @param {Unit} unit - the unit as string
  8610. * @function
  8611. */
  8612. endOf: abstract,
  8613. // DEPRECATIONS
  8614. /**
  8615. * Provided for backward compatibility for scale.getValueForPixel(),
  8616. * this method should be overridden only by the moment adapter.
  8617. * @deprecated since version 2.8.0
  8618. * @todo remove at version 3
  8619. * @private
  8620. */
  8621. _create: function(value) {
  8622. return value;
  8623. }
  8624. });
  8625. DateAdapter.override = function(members) {
  8626. helpers$1.extend(DateAdapter.prototype, members);
  8627. };
  8628. var _date = DateAdapter;
  8629. var core_adapters = {
  8630. _date: _date
  8631. };
  8632. /**
  8633. * Namespace to hold static tick generation functions
  8634. * @namespace Chart.Ticks
  8635. */
  8636. var core_ticks = {
  8637. /**
  8638. * Namespace to hold formatters for different types of ticks
  8639. * @namespace Chart.Ticks.formatters
  8640. */
  8641. formatters: {
  8642. /**
  8643. * Formatter for value labels
  8644. * @method Chart.Ticks.formatters.values
  8645. * @param value the value to display
  8646. * @return {string|string[]} the label to display
  8647. */
  8648. values: function(value) {
  8649. return helpers$1.isArray(value) ? value : '' + value;
  8650. },
  8651. /**
  8652. * Formatter for linear numeric ticks
  8653. * @method Chart.Ticks.formatters.linear
  8654. * @param tickValue {number} the value to be formatted
  8655. * @param index {number} the position of the tickValue parameter in the ticks array
  8656. * @param ticks {number[]} the list of ticks being converted
  8657. * @return {string} string representation of the tickValue parameter
  8658. */
  8659. linear: function(tickValue, index, ticks) {
  8660. // If we have lots of ticks, don't use the ones
  8661. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  8662. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  8663. if (Math.abs(delta) > 1) {
  8664. if (tickValue !== Math.floor(tickValue)) {
  8665. // not an integer
  8666. delta = tickValue - Math.floor(tickValue);
  8667. }
  8668. }
  8669. var logDelta = helpers$1.log10(Math.abs(delta));
  8670. var tickString = '';
  8671. if (tickValue !== 0) {
  8672. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  8673. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  8674. var logTick = helpers$1.log10(Math.abs(tickValue));
  8675. tickString = tickValue.toExponential(Math.floor(logTick) - Math.floor(logDelta));
  8676. } else {
  8677. var numDecimal = -1 * Math.floor(logDelta);
  8678. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  8679. tickString = tickValue.toFixed(numDecimal);
  8680. }
  8681. } else {
  8682. tickString = '0'; // never show decimal places for 0
  8683. }
  8684. return tickString;
  8685. },
  8686. logarithmic: function(tickValue, index, ticks) {
  8687. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  8688. if (tickValue === 0) {
  8689. return '0';
  8690. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  8691. return tickValue.toExponential();
  8692. }
  8693. return '';
  8694. }
  8695. }
  8696. };
  8697. var valueOrDefault$9 = helpers$1.valueOrDefault;
  8698. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  8699. core_defaults._set('scale', {
  8700. display: true,
  8701. position: 'left',
  8702. offset: false,
  8703. // grid line settings
  8704. gridLines: {
  8705. display: true,
  8706. color: 'rgba(0, 0, 0, 0.1)',
  8707. lineWidth: 1,
  8708. drawBorder: true,
  8709. drawOnChartArea: true,
  8710. drawTicks: true,
  8711. tickMarkLength: 10,
  8712. zeroLineWidth: 1,
  8713. zeroLineColor: 'rgba(0,0,0,0.25)',
  8714. zeroLineBorderDash: [],
  8715. zeroLineBorderDashOffset: 0.0,
  8716. offsetGridLines: false,
  8717. borderDash: [],
  8718. borderDashOffset: 0.0
  8719. },
  8720. // scale label
  8721. scaleLabel: {
  8722. // display property
  8723. display: false,
  8724. // actual label
  8725. labelString: '',
  8726. // top/bottom padding
  8727. padding: {
  8728. top: 4,
  8729. bottom: 4
  8730. }
  8731. },
  8732. // label settings
  8733. ticks: {
  8734. beginAtZero: false,
  8735. minRotation: 0,
  8736. maxRotation: 50,
  8737. mirror: false,
  8738. padding: 0,
  8739. reverse: false,
  8740. display: true,
  8741. autoSkip: true,
  8742. autoSkipPadding: 0,
  8743. labelOffset: 0,
  8744. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  8745. callback: core_ticks.formatters.values,
  8746. minor: {},
  8747. major: {}
  8748. }
  8749. });
  8750. function labelsFromTicks(ticks) {
  8751. var labels = [];
  8752. var i, ilen;
  8753. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  8754. labels.push(ticks[i].label);
  8755. }
  8756. return labels;
  8757. }
  8758. function getPixelForGridLine(scale, index, offsetGridLines) {
  8759. var lineValue = scale.getPixelForTick(index);
  8760. if (offsetGridLines) {
  8761. if (scale.getTicks().length === 1) {
  8762. lineValue -= scale.isHorizontal() ?
  8763. Math.max(lineValue - scale.left, scale.right - lineValue) :
  8764. Math.max(lineValue - scale.top, scale.bottom - lineValue);
  8765. } else if (index === 0) {
  8766. lineValue -= (scale.getPixelForTick(1) - lineValue) / 2;
  8767. } else {
  8768. lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2;
  8769. }
  8770. }
  8771. return lineValue;
  8772. }
  8773. function computeTextSize(context, tick, font) {
  8774. return helpers$1.isArray(tick) ?
  8775. helpers$1.longestText(context, font, tick) :
  8776. context.measureText(tick).width;
  8777. }
  8778. var core_scale = core_element.extend({
  8779. /**
  8780. * Get the padding needed for the scale
  8781. * @method getPadding
  8782. * @private
  8783. * @returns {Padding} the necessary padding
  8784. */
  8785. getPadding: function() {
  8786. var me = this;
  8787. return {
  8788. left: me.paddingLeft || 0,
  8789. top: me.paddingTop || 0,
  8790. right: me.paddingRight || 0,
  8791. bottom: me.paddingBottom || 0
  8792. };
  8793. },
  8794. /**
  8795. * Returns the scale tick objects ({label, major})
  8796. * @since 2.7
  8797. */
  8798. getTicks: function() {
  8799. return this._ticks;
  8800. },
  8801. // These methods are ordered by lifecyle. Utilities then follow.
  8802. // Any function defined here is inherited by all scale types.
  8803. // Any function can be extended by the scale type
  8804. mergeTicksOptions: function() {
  8805. var ticks = this.options.ticks;
  8806. if (ticks.minor === false) {
  8807. ticks.minor = {
  8808. display: false
  8809. };
  8810. }
  8811. if (ticks.major === false) {
  8812. ticks.major = {
  8813. display: false
  8814. };
  8815. }
  8816. for (var key in ticks) {
  8817. if (key !== 'major' && key !== 'minor') {
  8818. if (typeof ticks.minor[key] === 'undefined') {
  8819. ticks.minor[key] = ticks[key];
  8820. }
  8821. if (typeof ticks.major[key] === 'undefined') {
  8822. ticks.major[key] = ticks[key];
  8823. }
  8824. }
  8825. }
  8826. },
  8827. beforeUpdate: function() {
  8828. helpers$1.callback(this.options.beforeUpdate, [this]);
  8829. },
  8830. update: function(maxWidth, maxHeight, margins) {
  8831. var me = this;
  8832. var i, ilen, labels, label, ticks, tick;
  8833. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  8834. me.beforeUpdate();
  8835. // Absorb the master measurements
  8836. me.maxWidth = maxWidth;
  8837. me.maxHeight = maxHeight;
  8838. me.margins = helpers$1.extend({
  8839. left: 0,
  8840. right: 0,
  8841. top: 0,
  8842. bottom: 0
  8843. }, margins);
  8844. me._maxLabelLines = 0;
  8845. me.longestLabelWidth = 0;
  8846. me.longestTextCache = me.longestTextCache || {};
  8847. // Dimensions
  8848. me.beforeSetDimensions();
  8849. me.setDimensions();
  8850. me.afterSetDimensions();
  8851. // Data min/max
  8852. me.beforeDataLimits();
  8853. me.determineDataLimits();
  8854. me.afterDataLimits();
  8855. // Ticks - `this.ticks` is now DEPRECATED!
  8856. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  8857. // and must not be accessed directly from outside this class. `this.ticks` being
  8858. // around for long time and not marked as private, we can't change its structure
  8859. // without unexpected breaking changes. If you need to access the scale ticks,
  8860. // use scale.getTicks() instead.
  8861. me.beforeBuildTicks();
  8862. // New implementations should return an array of objects but for BACKWARD COMPAT,
  8863. // we still support no return (`this.ticks` internally set by calling this method).
  8864. ticks = me.buildTicks() || [];
  8865. // Allow modification of ticks in callback.
  8866. ticks = me.afterBuildTicks(ticks) || ticks;
  8867. me.beforeTickToLabelConversion();
  8868. // New implementations should return the formatted tick labels but for BACKWARD
  8869. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  8870. // this method and supposed to contain only string values).
  8871. labels = me.convertTicksToLabels(ticks) || me.ticks;
  8872. me.afterTickToLabelConversion();
  8873. me.ticks = labels; // BACKWARD COMPATIBILITY
  8874. // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change!
  8875. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  8876. for (i = 0, ilen = labels.length; i < ilen; ++i) {
  8877. label = labels[i];
  8878. tick = ticks[i];
  8879. if (!tick) {
  8880. ticks.push(tick = {
  8881. label: label,
  8882. major: false
  8883. });
  8884. } else {
  8885. tick.label = label;
  8886. }
  8887. }
  8888. me._ticks = ticks;
  8889. // Tick Rotation
  8890. me.beforeCalculateTickRotation();
  8891. me.calculateTickRotation();
  8892. me.afterCalculateTickRotation();
  8893. // Fit
  8894. me.beforeFit();
  8895. me.fit();
  8896. me.afterFit();
  8897. //
  8898. me.afterUpdate();
  8899. return me.minSize;
  8900. },
  8901. afterUpdate: function() {
  8902. helpers$1.callback(this.options.afterUpdate, [this]);
  8903. },
  8904. //
  8905. beforeSetDimensions: function() {
  8906. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  8907. },
  8908. setDimensions: function() {
  8909. var me = this;
  8910. // Set the unconstrained dimension before label rotation
  8911. if (me.isHorizontal()) {
  8912. // Reset position before calculating rotation
  8913. me.width = me.maxWidth;
  8914. me.left = 0;
  8915. me.right = me.width;
  8916. } else {
  8917. me.height = me.maxHeight;
  8918. // Reset position before calculating rotation
  8919. me.top = 0;
  8920. me.bottom = me.height;
  8921. }
  8922. // Reset padding
  8923. me.paddingLeft = 0;
  8924. me.paddingTop = 0;
  8925. me.paddingRight = 0;
  8926. me.paddingBottom = 0;
  8927. },
  8928. afterSetDimensions: function() {
  8929. helpers$1.callback(this.options.afterSetDimensions, [this]);
  8930. },
  8931. // Data limits
  8932. beforeDataLimits: function() {
  8933. helpers$1.callback(this.options.beforeDataLimits, [this]);
  8934. },
  8935. determineDataLimits: helpers$1.noop,
  8936. afterDataLimits: function() {
  8937. helpers$1.callback(this.options.afterDataLimits, [this]);
  8938. },
  8939. //
  8940. beforeBuildTicks: function() {
  8941. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  8942. },
  8943. buildTicks: helpers$1.noop,
  8944. afterBuildTicks: function(ticks) {
  8945. var me = this;
  8946. // ticks is empty for old axis implementations here
  8947. if (helpers$1.isArray(ticks) && ticks.length) {
  8948. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  8949. }
  8950. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  8951. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  8952. return ticks;
  8953. },
  8954. beforeTickToLabelConversion: function() {
  8955. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  8956. },
  8957. convertTicksToLabels: function() {
  8958. var me = this;
  8959. // Convert ticks to strings
  8960. var tickOpts = me.options.ticks;
  8961. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  8962. },
  8963. afterTickToLabelConversion: function() {
  8964. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  8965. },
  8966. //
  8967. beforeCalculateTickRotation: function() {
  8968. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  8969. },
  8970. calculateTickRotation: function() {
  8971. var me = this;
  8972. var context = me.ctx;
  8973. var tickOpts = me.options.ticks;
  8974. var labels = labelsFromTicks(me._ticks);
  8975. // Get the width of each grid by calculating the difference
  8976. // between x offsets between 0 and 1.
  8977. var tickFont = helpers$1.options._parseFont(tickOpts);
  8978. context.font = tickFont.string;
  8979. var labelRotation = tickOpts.minRotation || 0;
  8980. if (labels.length && me.options.display && me.isHorizontal()) {
  8981. var originalLabelWidth = helpers$1.longestText(context, tickFont.string, labels, me.longestTextCache);
  8982. var labelWidth = originalLabelWidth;
  8983. var cosRotation, sinRotation;
  8984. // Allow 3 pixels x2 padding either side for label readability
  8985. var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
  8986. // Max label rotation can be set or default to 90 - also act as a loop counter
  8987. while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {
  8988. var angleRadians = helpers$1.toRadians(labelRotation);
  8989. cosRotation = Math.cos(angleRadians);
  8990. sinRotation = Math.sin(angleRadians);
  8991. if (sinRotation * originalLabelWidth > me.maxHeight) {
  8992. // go back one step
  8993. labelRotation--;
  8994. break;
  8995. }
  8996. labelRotation++;
  8997. labelWidth = cosRotation * originalLabelWidth;
  8998. }
  8999. }
  9000. me.labelRotation = labelRotation;
  9001. },
  9002. afterCalculateTickRotation: function() {
  9003. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  9004. },
  9005. //
  9006. beforeFit: function() {
  9007. helpers$1.callback(this.options.beforeFit, [this]);
  9008. },
  9009. fit: function() {
  9010. var me = this;
  9011. // Reset
  9012. var minSize = me.minSize = {
  9013. width: 0,
  9014. height: 0
  9015. };
  9016. var labels = labelsFromTicks(me._ticks);
  9017. var opts = me.options;
  9018. var tickOpts = opts.ticks;
  9019. var scaleLabelOpts = opts.scaleLabel;
  9020. var gridLineOpts = opts.gridLines;
  9021. var display = me._isVisible();
  9022. var position = opts.position;
  9023. var isHorizontal = me.isHorizontal();
  9024. var parseFont = helpers$1.options._parseFont;
  9025. var tickFont = parseFont(tickOpts);
  9026. var tickMarkLength = opts.gridLines.tickMarkLength;
  9027. // Width
  9028. if (isHorizontal) {
  9029. // subtract the margins to line up with the chartArea if we are a full width scale
  9030. minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
  9031. } else {
  9032. minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
  9033. }
  9034. // height
  9035. if (isHorizontal) {
  9036. minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
  9037. } else {
  9038. minSize.height = me.maxHeight; // fill all the height
  9039. }
  9040. // Are we showing a title for the scale?
  9041. if (scaleLabelOpts.display && display) {
  9042. var scaleLabelFont = parseFont(scaleLabelOpts);
  9043. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabelOpts.padding);
  9044. var deltaHeight = scaleLabelFont.lineHeight + scaleLabelPadding.height;
  9045. if (isHorizontal) {
  9046. minSize.height += deltaHeight;
  9047. } else {
  9048. minSize.width += deltaHeight;
  9049. }
  9050. }
  9051. // Don't bother fitting the ticks if we are not showing the labels
  9052. if (tickOpts.display && display) {
  9053. var largestTextWidth = helpers$1.longestText(me.ctx, tickFont.string, labels, me.longestTextCache);
  9054. var tallestLabelHeightInLines = helpers$1.numberOfLabelLines(labels);
  9055. var lineSpace = tickFont.size * 0.5;
  9056. var tickPadding = me.options.ticks.padding;
  9057. // Store max number of lines and widest label for _autoSkip
  9058. me._maxLabelLines = tallestLabelHeightInLines;
  9059. me.longestLabelWidth = largestTextWidth;
  9060. if (isHorizontal) {
  9061. var angleRadians = helpers$1.toRadians(me.labelRotation);
  9062. var cosRotation = Math.cos(angleRadians);
  9063. var sinRotation = Math.sin(angleRadians);
  9064. // TODO - improve this calculation
  9065. var labelHeight = (sinRotation * largestTextWidth)
  9066. + (tickFont.lineHeight * tallestLabelHeightInLines)
  9067. + lineSpace; // padding
  9068. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  9069. me.ctx.font = tickFont.string;
  9070. var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.string);
  9071. var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.string);
  9072. var offsetLeft = me.getPixelForTick(0) - me.left;
  9073. var offsetRight = me.right - me.getPixelForTick(labels.length - 1);
  9074. var paddingLeft, paddingRight;
  9075. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  9076. // which means that the right padding is dominated by the font height
  9077. if (me.labelRotation !== 0) {
  9078. paddingLeft = position === 'bottom' ? (cosRotation * firstLabelWidth) : (cosRotation * lineSpace);
  9079. paddingRight = position === 'bottom' ? (cosRotation * lineSpace) : (cosRotation * lastLabelWidth);
  9080. } else {
  9081. paddingLeft = firstLabelWidth / 2;
  9082. paddingRight = lastLabelWidth / 2;
  9083. }
  9084. me.paddingLeft = Math.max(paddingLeft - offsetLeft, 0) + 3; // add 3 px to move away from canvas edges
  9085. me.paddingRight = Math.max(paddingRight - offsetRight, 0) + 3;
  9086. } else {
  9087. // A vertical axis is more constrained by the width. Labels are the
  9088. // dominant factor here, so get that length first and account for padding
  9089. if (tickOpts.mirror) {
  9090. largestTextWidth = 0;
  9091. } else {
  9092. // use lineSpace for consistency with horizontal axis
  9093. // tickPadding is not implemented for horizontal
  9094. largestTextWidth += tickPadding + lineSpace;
  9095. }
  9096. minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth);
  9097. me.paddingTop = tickFont.size / 2;
  9098. me.paddingBottom = tickFont.size / 2;
  9099. }
  9100. }
  9101. me.handleMargins();
  9102. me.width = minSize.width;
  9103. me.height = minSize.height;
  9104. },
  9105. /**
  9106. * Handle margins and padding interactions
  9107. * @private
  9108. */
  9109. handleMargins: function() {
  9110. var me = this;
  9111. if (me.margins) {
  9112. me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
  9113. me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
  9114. me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
  9115. me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
  9116. }
  9117. },
  9118. afterFit: function() {
  9119. helpers$1.callback(this.options.afterFit, [this]);
  9120. },
  9121. // Shared Methods
  9122. isHorizontal: function() {
  9123. return this.options.position === 'top' || this.options.position === 'bottom';
  9124. },
  9125. isFullWidth: function() {
  9126. return (this.options.fullWidth);
  9127. },
  9128. // 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
  9129. getRightValue: function(rawValue) {
  9130. // Null and undefined values first
  9131. if (helpers$1.isNullOrUndef(rawValue)) {
  9132. return NaN;
  9133. }
  9134. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  9135. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  9136. return NaN;
  9137. }
  9138. // If it is in fact an object, dive in one more level
  9139. if (rawValue) {
  9140. if (this.isHorizontal()) {
  9141. if (rawValue.x !== undefined) {
  9142. return this.getRightValue(rawValue.x);
  9143. }
  9144. } else if (rawValue.y !== undefined) {
  9145. return this.getRightValue(rawValue.y);
  9146. }
  9147. }
  9148. // Value is good, return it
  9149. return rawValue;
  9150. },
  9151. /**
  9152. * Used to get the value to display in the tooltip for the data at the given index
  9153. * @param index
  9154. * @param datasetIndex
  9155. */
  9156. getLabelForIndex: helpers$1.noop,
  9157. /**
  9158. * Returns the location of the given data point. Value can either be an index or a numerical value
  9159. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9160. * @param value
  9161. * @param index
  9162. * @param datasetIndex
  9163. */
  9164. getPixelForValue: helpers$1.noop,
  9165. /**
  9166. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  9167. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9168. * @param pixel
  9169. */
  9170. getValueForPixel: helpers$1.noop,
  9171. /**
  9172. * Returns the location of the tick at the given index
  9173. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9174. */
  9175. getPixelForTick: function(index) {
  9176. var me = this;
  9177. var offset = me.options.offset;
  9178. if (me.isHorizontal()) {
  9179. var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
  9180. var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
  9181. var pixel = (tickWidth * index) + me.paddingLeft;
  9182. if (offset) {
  9183. pixel += tickWidth / 2;
  9184. }
  9185. var finalVal = me.left + pixel;
  9186. finalVal += me.isFullWidth() ? me.margins.left : 0;
  9187. return finalVal;
  9188. }
  9189. var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
  9190. return me.top + (index * (innerHeight / (me._ticks.length - 1)));
  9191. },
  9192. /**
  9193. * Utility for getting the pixel location of a percentage of scale
  9194. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9195. */
  9196. getPixelForDecimal: function(decimal) {
  9197. var me = this;
  9198. if (me.isHorizontal()) {
  9199. var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
  9200. var valueOffset = (innerWidth * decimal) + me.paddingLeft;
  9201. var finalVal = me.left + valueOffset;
  9202. finalVal += me.isFullWidth() ? me.margins.left : 0;
  9203. return finalVal;
  9204. }
  9205. return me.top + (decimal * me.height);
  9206. },
  9207. /**
  9208. * Returns the pixel for the minimum chart value
  9209. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9210. */
  9211. getBasePixel: function() {
  9212. return this.getPixelForValue(this.getBaseValue());
  9213. },
  9214. getBaseValue: function() {
  9215. var me = this;
  9216. var min = me.min;
  9217. var max = me.max;
  9218. return me.beginAtZero ? 0 :
  9219. min < 0 && max < 0 ? max :
  9220. min > 0 && max > 0 ? min :
  9221. 0;
  9222. },
  9223. /**
  9224. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  9225. * @private
  9226. */
  9227. _autoSkip: function(ticks) {
  9228. var me = this;
  9229. var isHorizontal = me.isHorizontal();
  9230. var optionTicks = me.options.ticks.minor;
  9231. var tickCount = ticks.length;
  9232. var skipRatio = false;
  9233. var maxTicks = optionTicks.maxTicksLimit;
  9234. // Total space needed to display all ticks. First and last ticks are
  9235. // drawn as their center at end of axis, so tickCount-1
  9236. var ticksLength = me._tickSize() * (tickCount - 1);
  9237. // Axis length
  9238. var axisLength = isHorizontal
  9239. ? me.width - (me.paddingLeft + me.paddingRight)
  9240. : me.height - (me.paddingTop + me.PaddingBottom);
  9241. var result = [];
  9242. var i, tick;
  9243. if (ticksLength > axisLength) {
  9244. skipRatio = 1 + Math.floor(ticksLength / axisLength);
  9245. }
  9246. // if they defined a max number of optionTicks,
  9247. // increase skipRatio until that number is met
  9248. if (tickCount > maxTicks) {
  9249. skipRatio = Math.max(skipRatio, 1 + Math.floor(tickCount / maxTicks));
  9250. }
  9251. for (i = 0; i < tickCount; i++) {
  9252. tick = ticks[i];
  9253. if (skipRatio > 1 && i % skipRatio > 0) {
  9254. // leave tick in place but make sure it's not displayed (#4635)
  9255. delete tick.label;
  9256. }
  9257. result.push(tick);
  9258. }
  9259. return result;
  9260. },
  9261. /**
  9262. * @private
  9263. */
  9264. _tickSize: function() {
  9265. var me = this;
  9266. var isHorizontal = me.isHorizontal();
  9267. var optionTicks = me.options.ticks.minor;
  9268. // Calculate space needed by label in axis direction.
  9269. var rot = helpers$1.toRadians(me.labelRotation);
  9270. var cos = Math.abs(Math.cos(rot));
  9271. var sin = Math.abs(Math.sin(rot));
  9272. var padding = optionTicks.autoSkipPadding || 0;
  9273. var w = (me.longestLabelWidth + padding) || 0;
  9274. var tickFont = helpers$1.options._parseFont(optionTicks);
  9275. var h = (me._maxLabelLines * tickFont.lineHeight + padding) || 0;
  9276. // Calculate space needed for 1 tick in axis direction.
  9277. return isHorizontal
  9278. ? h * cos > w * sin ? w / cos : h / sin
  9279. : h * sin < w * cos ? h / cos : w / sin;
  9280. },
  9281. /**
  9282. * @private
  9283. */
  9284. _isVisible: function() {
  9285. var me = this;
  9286. var chart = me.chart;
  9287. var display = me.options.display;
  9288. var i, ilen, meta;
  9289. if (display !== 'auto') {
  9290. return !!display;
  9291. }
  9292. // When 'auto', the scale is visible if at least one associated dataset is visible.
  9293. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  9294. if (chart.isDatasetVisible(i)) {
  9295. meta = chart.getDatasetMeta(i);
  9296. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  9297. return true;
  9298. }
  9299. }
  9300. }
  9301. return false;
  9302. },
  9303. /**
  9304. * Actually draw the scale on the canvas
  9305. * @param {object} chartArea - the area of the chart to draw full grid lines on
  9306. */
  9307. draw: function(chartArea) {
  9308. var me = this;
  9309. var options = me.options;
  9310. if (!me._isVisible()) {
  9311. return;
  9312. }
  9313. var chart = me.chart;
  9314. var context = me.ctx;
  9315. var globalDefaults = core_defaults.global;
  9316. var defaultFontColor = globalDefaults.defaultFontColor;
  9317. var optionTicks = options.ticks.minor;
  9318. var optionMajorTicks = options.ticks.major || optionTicks;
  9319. var gridLines = options.gridLines;
  9320. var scaleLabel = options.scaleLabel;
  9321. var position = options.position;
  9322. var isRotated = me.labelRotation !== 0;
  9323. var isMirrored = optionTicks.mirror;
  9324. var isHorizontal = me.isHorizontal();
  9325. var parseFont = helpers$1.options._parseFont;
  9326. var ticks = optionTicks.display && optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks();
  9327. var tickFontColor = valueOrDefault$9(optionTicks.fontColor, defaultFontColor);
  9328. var tickFont = parseFont(optionTicks);
  9329. var lineHeight = tickFont.lineHeight;
  9330. var majorTickFontColor = valueOrDefault$9(optionMajorTicks.fontColor, defaultFontColor);
  9331. var majorTickFont = parseFont(optionMajorTicks);
  9332. var tickPadding = optionTicks.padding;
  9333. var labelOffset = optionTicks.labelOffset;
  9334. var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;
  9335. var scaleLabelFontColor = valueOrDefault$9(scaleLabel.fontColor, defaultFontColor);
  9336. var scaleLabelFont = parseFont(scaleLabel);
  9337. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  9338. var labelRotationRadians = helpers$1.toRadians(me.labelRotation);
  9339. var itemsToDraw = [];
  9340. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  9341. var alignPixel = helpers$1._alignPixel;
  9342. var borderValue, tickStart, tickEnd;
  9343. if (position === 'top') {
  9344. borderValue = alignPixel(chart, me.bottom, axisWidth);
  9345. tickStart = me.bottom - tl;
  9346. tickEnd = borderValue - axisWidth / 2;
  9347. } else if (position === 'bottom') {
  9348. borderValue = alignPixel(chart, me.top, axisWidth);
  9349. tickStart = borderValue + axisWidth / 2;
  9350. tickEnd = me.top + tl;
  9351. } else if (position === 'left') {
  9352. borderValue = alignPixel(chart, me.right, axisWidth);
  9353. tickStart = me.right - tl;
  9354. tickEnd = borderValue - axisWidth / 2;
  9355. } else {
  9356. borderValue = alignPixel(chart, me.left, axisWidth);
  9357. tickStart = borderValue + axisWidth / 2;
  9358. tickEnd = me.left + tl;
  9359. }
  9360. var epsilon = 0.0000001; // 0.0000001 is margin in pixels for Accumulated error.
  9361. helpers$1.each(ticks, function(tick, index) {
  9362. // autoskipper skipped this tick (#4635)
  9363. if (helpers$1.isNullOrUndef(tick.label)) {
  9364. return;
  9365. }
  9366. var label = tick.label;
  9367. var lineWidth, lineColor, borderDash, borderDashOffset;
  9368. if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) {
  9369. // Draw the first index specially
  9370. lineWidth = gridLines.zeroLineWidth;
  9371. lineColor = gridLines.zeroLineColor;
  9372. borderDash = gridLines.zeroLineBorderDash || [];
  9373. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  9374. } else {
  9375. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, index);
  9376. lineColor = valueAtIndexOrDefault(gridLines.color, index);
  9377. borderDash = gridLines.borderDash || [];
  9378. borderDashOffset = gridLines.borderDashOffset || 0.0;
  9379. }
  9380. // Common properties
  9381. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY, textOffset, textAlign;
  9382. var labelCount = helpers$1.isArray(label) ? label.length : 1;
  9383. var lineValue = getPixelForGridLine(me, index, gridLines.offsetGridLines);
  9384. if (isHorizontal) {
  9385. var labelYOffset = tl + tickPadding;
  9386. if (lineValue < me.left - epsilon) {
  9387. lineColor = 'rgba(0,0,0,0)';
  9388. }
  9389. tx1 = tx2 = x1 = x2 = alignPixel(chart, lineValue, lineWidth);
  9390. ty1 = tickStart;
  9391. ty2 = tickEnd;
  9392. labelX = me.getPixelForTick(index) + labelOffset; // x values for optionTicks (need to consider offsetLabel option)
  9393. if (position === 'top') {
  9394. y1 = alignPixel(chart, chartArea.top, axisWidth) + axisWidth / 2;
  9395. y2 = chartArea.bottom;
  9396. textOffset = ((!isRotated ? 0.5 : 1) - labelCount) * lineHeight;
  9397. textAlign = !isRotated ? 'center' : 'left';
  9398. labelY = me.bottom - labelYOffset;
  9399. } else {
  9400. y1 = chartArea.top;
  9401. y2 = alignPixel(chart, chartArea.bottom, axisWidth) - axisWidth / 2;
  9402. textOffset = (!isRotated ? 0.5 : 0) * lineHeight;
  9403. textAlign = !isRotated ? 'center' : 'right';
  9404. labelY = me.top + labelYOffset;
  9405. }
  9406. } else {
  9407. var labelXOffset = (isMirrored ? 0 : tl) + tickPadding;
  9408. if (lineValue < me.top - epsilon) {
  9409. lineColor = 'rgba(0,0,0,0)';
  9410. }
  9411. tx1 = tickStart;
  9412. tx2 = tickEnd;
  9413. ty1 = ty2 = y1 = y2 = alignPixel(chart, lineValue, lineWidth);
  9414. labelY = me.getPixelForTick(index) + labelOffset;
  9415. textOffset = (1 - labelCount) * lineHeight / 2;
  9416. if (position === 'left') {
  9417. x1 = alignPixel(chart, chartArea.left, axisWidth) + axisWidth / 2;
  9418. x2 = chartArea.right;
  9419. textAlign = isMirrored ? 'left' : 'right';
  9420. labelX = me.right - labelXOffset;
  9421. } else {
  9422. x1 = chartArea.left;
  9423. x2 = alignPixel(chart, chartArea.right, axisWidth) - axisWidth / 2;
  9424. textAlign = isMirrored ? 'right' : 'left';
  9425. labelX = me.left + labelXOffset;
  9426. }
  9427. }
  9428. itemsToDraw.push({
  9429. tx1: tx1,
  9430. ty1: ty1,
  9431. tx2: tx2,
  9432. ty2: ty2,
  9433. x1: x1,
  9434. y1: y1,
  9435. x2: x2,
  9436. y2: y2,
  9437. labelX: labelX,
  9438. labelY: labelY,
  9439. glWidth: lineWidth,
  9440. glColor: lineColor,
  9441. glBorderDash: borderDash,
  9442. glBorderDashOffset: borderDashOffset,
  9443. rotation: -1 * labelRotationRadians,
  9444. label: label,
  9445. major: tick.major,
  9446. textOffset: textOffset,
  9447. textAlign: textAlign
  9448. });
  9449. });
  9450. // Draw all of the tick labels, tick marks, and grid lines at the correct places
  9451. helpers$1.each(itemsToDraw, function(itemToDraw) {
  9452. var glWidth = itemToDraw.glWidth;
  9453. var glColor = itemToDraw.glColor;
  9454. if (gridLines.display && glWidth && glColor) {
  9455. context.save();
  9456. context.lineWidth = glWidth;
  9457. context.strokeStyle = glColor;
  9458. if (context.setLineDash) {
  9459. context.setLineDash(itemToDraw.glBorderDash);
  9460. context.lineDashOffset = itemToDraw.glBorderDashOffset;
  9461. }
  9462. context.beginPath();
  9463. if (gridLines.drawTicks) {
  9464. context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
  9465. context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
  9466. }
  9467. if (gridLines.drawOnChartArea) {
  9468. context.moveTo(itemToDraw.x1, itemToDraw.y1);
  9469. context.lineTo(itemToDraw.x2, itemToDraw.y2);
  9470. }
  9471. context.stroke();
  9472. context.restore();
  9473. }
  9474. if (optionTicks.display) {
  9475. // Make sure we draw text in the correct color and font
  9476. context.save();
  9477. context.translate(itemToDraw.labelX, itemToDraw.labelY);
  9478. context.rotate(itemToDraw.rotation);
  9479. context.font = itemToDraw.major ? majorTickFont.string : tickFont.string;
  9480. context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;
  9481. context.textBaseline = 'middle';
  9482. context.textAlign = itemToDraw.textAlign;
  9483. var label = itemToDraw.label;
  9484. var y = itemToDraw.textOffset;
  9485. if (helpers$1.isArray(label)) {
  9486. for (var i = 0; i < label.length; ++i) {
  9487. // We just make sure the multiline element is a string here..
  9488. context.fillText('' + label[i], 0, y);
  9489. y += lineHeight;
  9490. }
  9491. } else {
  9492. context.fillText(label, 0, y);
  9493. }
  9494. context.restore();
  9495. }
  9496. });
  9497. if (scaleLabel.display) {
  9498. // Draw the scale label
  9499. var scaleLabelX;
  9500. var scaleLabelY;
  9501. var rotation = 0;
  9502. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  9503. if (isHorizontal) {
  9504. scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
  9505. scaleLabelY = position === 'bottom'
  9506. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  9507. : me.top + halfLineHeight + scaleLabelPadding.top;
  9508. } else {
  9509. var isLeft = position === 'left';
  9510. scaleLabelX = isLeft
  9511. ? me.left + halfLineHeight + scaleLabelPadding.top
  9512. : me.right - halfLineHeight - scaleLabelPadding.top;
  9513. scaleLabelY = me.top + ((me.bottom - me.top) / 2);
  9514. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  9515. }
  9516. context.save();
  9517. context.translate(scaleLabelX, scaleLabelY);
  9518. context.rotate(rotation);
  9519. context.textAlign = 'center';
  9520. context.textBaseline = 'middle';
  9521. context.fillStyle = scaleLabelFontColor; // render in correct colour
  9522. context.font = scaleLabelFont.string;
  9523. context.fillText(scaleLabel.labelString, 0, 0);
  9524. context.restore();
  9525. }
  9526. if (axisWidth) {
  9527. // Draw the line at the edge of the axis
  9528. var firstLineWidth = axisWidth;
  9529. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, ticks.length - 1, 0);
  9530. var x1, x2, y1, y2;
  9531. if (isHorizontal) {
  9532. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  9533. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  9534. y1 = y2 = borderValue;
  9535. } else {
  9536. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  9537. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  9538. x1 = x2 = borderValue;
  9539. }
  9540. context.lineWidth = axisWidth;
  9541. context.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  9542. context.beginPath();
  9543. context.moveTo(x1, y1);
  9544. context.lineTo(x2, y2);
  9545. context.stroke();
  9546. }
  9547. }
  9548. });
  9549. var defaultConfig = {
  9550. position: 'bottom'
  9551. };
  9552. var scale_category = core_scale.extend({
  9553. /**
  9554. * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those
  9555. * else fall back to data.labels
  9556. * @private
  9557. */
  9558. getLabels: function() {
  9559. var data = this.chart.data;
  9560. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;
  9561. },
  9562. determineDataLimits: function() {
  9563. var me = this;
  9564. var labels = me.getLabels();
  9565. me.minIndex = 0;
  9566. me.maxIndex = labels.length - 1;
  9567. var findIndex;
  9568. if (me.options.ticks.min !== undefined) {
  9569. // user specified min value
  9570. findIndex = labels.indexOf(me.options.ticks.min);
  9571. me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
  9572. }
  9573. if (me.options.ticks.max !== undefined) {
  9574. // user specified max value
  9575. findIndex = labels.indexOf(me.options.ticks.max);
  9576. me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
  9577. }
  9578. me.min = labels[me.minIndex];
  9579. me.max = labels[me.maxIndex];
  9580. },
  9581. buildTicks: function() {
  9582. var me = this;
  9583. var labels = me.getLabels();
  9584. // If we are viewing some subset of labels, slice the original array
  9585. me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);
  9586. },
  9587. getLabelForIndex: function(index, datasetIndex) {
  9588. var me = this;
  9589. var chart = me.chart;
  9590. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  9591. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  9592. }
  9593. return me.ticks[index - me.minIndex];
  9594. },
  9595. // Used to get data value locations. Value can either be an index or a numerical value
  9596. getPixelForValue: function(value, index) {
  9597. var me = this;
  9598. var offset = me.options.offset;
  9599. // 1 is added because we need the length but we have the indexes
  9600. var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1);
  9601. // If value is a data object, then index is the index in the data array,
  9602. // not the index of the scale. We need to change that.
  9603. var valueCategory;
  9604. if (value !== undefined && value !== null) {
  9605. valueCategory = me.isHorizontal() ? value.x : value.y;
  9606. }
  9607. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  9608. var labels = me.getLabels();
  9609. value = valueCategory || value;
  9610. var idx = labels.indexOf(value);
  9611. index = idx !== -1 ? idx : index;
  9612. }
  9613. if (me.isHorizontal()) {
  9614. var valueWidth = me.width / offsetAmt;
  9615. var widthOffset = (valueWidth * (index - me.minIndex));
  9616. if (offset) {
  9617. widthOffset += (valueWidth / 2);
  9618. }
  9619. return me.left + widthOffset;
  9620. }
  9621. var valueHeight = me.height / offsetAmt;
  9622. var heightOffset = (valueHeight * (index - me.minIndex));
  9623. if (offset) {
  9624. heightOffset += (valueHeight / 2);
  9625. }
  9626. return me.top + heightOffset;
  9627. },
  9628. getPixelForTick: function(index) {
  9629. return this.getPixelForValue(this.ticks[index], index + this.minIndex, null);
  9630. },
  9631. getValueForPixel: function(pixel) {
  9632. var me = this;
  9633. var offset = me.options.offset;
  9634. var value;
  9635. var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
  9636. var horz = me.isHorizontal();
  9637. var valueDimension = (horz ? me.width : me.height) / offsetAmt;
  9638. pixel -= horz ? me.left : me.top;
  9639. if (offset) {
  9640. pixel -= (valueDimension / 2);
  9641. }
  9642. if (pixel <= 0) {
  9643. value = 0;
  9644. } else {
  9645. value = Math.round(pixel / valueDimension);
  9646. }
  9647. return value + me.minIndex;
  9648. },
  9649. getBasePixel: function() {
  9650. return this.bottom;
  9651. }
  9652. });
  9653. // INTERNAL: static default options, registered in src/index.js
  9654. var _defaults = defaultConfig;
  9655. scale_category._defaults = _defaults;
  9656. var noop = helpers$1.noop;
  9657. var isNullOrUndef = helpers$1.isNullOrUndef;
  9658. /**
  9659. * Generate a set of linear ticks
  9660. * @param generationOptions the options used to generate the ticks
  9661. * @param dataRange the range of the data
  9662. * @returns {number[]} array of tick values
  9663. */
  9664. function generateTicks(generationOptions, dataRange) {
  9665. var ticks = [];
  9666. // To get a "nice" value for the tick spacing, we will use the appropriately named
  9667. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  9668. // for details.
  9669. var MIN_SPACING = 1e-14;
  9670. var stepSize = generationOptions.stepSize;
  9671. var unit = stepSize || 1;
  9672. var maxNumSpaces = generationOptions.maxTicks - 1;
  9673. var min = generationOptions.min;
  9674. var max = generationOptions.max;
  9675. var precision = generationOptions.precision;
  9676. var rmin = dataRange.min;
  9677. var rmax = dataRange.max;
  9678. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  9679. var factor, niceMin, niceMax, numSpaces;
  9680. // Beyond MIN_SPACING floating point numbers being to lose precision
  9681. // such that we can't do the math necessary to generate ticks
  9682. if (spacing < MIN_SPACING && isNullOrUndef(min) && isNullOrUndef(max)) {
  9683. return [rmin, rmax];
  9684. }
  9685. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  9686. if (numSpaces > maxNumSpaces) {
  9687. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  9688. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  9689. }
  9690. if (stepSize || isNullOrUndef(precision)) {
  9691. // If a precision is not specified, calculate factor based on spacing
  9692. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  9693. } else {
  9694. // If the user specified a precision, round to that number of decimal places
  9695. factor = Math.pow(10, precision);
  9696. spacing = Math.ceil(spacing * factor) / factor;
  9697. }
  9698. niceMin = Math.floor(rmin / spacing) * spacing;
  9699. niceMax = Math.ceil(rmax / spacing) * spacing;
  9700. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  9701. if (stepSize) {
  9702. // If very close to our whole number, use it.
  9703. if (!isNullOrUndef(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  9704. niceMin = min;
  9705. }
  9706. if (!isNullOrUndef(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  9707. niceMax = max;
  9708. }
  9709. }
  9710. numSpaces = (niceMax - niceMin) / spacing;
  9711. // If very close to our rounded value, use it.
  9712. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  9713. numSpaces = Math.round(numSpaces);
  9714. } else {
  9715. numSpaces = Math.ceil(numSpaces);
  9716. }
  9717. niceMin = Math.round(niceMin * factor) / factor;
  9718. niceMax = Math.round(niceMax * factor) / factor;
  9719. ticks.push(isNullOrUndef(min) ? niceMin : min);
  9720. for (var j = 1; j < numSpaces; ++j) {
  9721. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  9722. }
  9723. ticks.push(isNullOrUndef(max) ? niceMax : max);
  9724. return ticks;
  9725. }
  9726. var scale_linearbase = core_scale.extend({
  9727. getRightValue: function(value) {
  9728. if (typeof value === 'string') {
  9729. return +value;
  9730. }
  9731. return core_scale.prototype.getRightValue.call(this, value);
  9732. },
  9733. handleTickRangeOptions: function() {
  9734. var me = this;
  9735. var opts = me.options;
  9736. var tickOpts = opts.ticks;
  9737. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  9738. // do nothing since that would make the chart weird. If the user really wants a weird chart
  9739. // axis, they can manually override it
  9740. if (tickOpts.beginAtZero) {
  9741. var minSign = helpers$1.sign(me.min);
  9742. var maxSign = helpers$1.sign(me.max);
  9743. if (minSign < 0 && maxSign < 0) {
  9744. // move the top up to 0
  9745. me.max = 0;
  9746. } else if (minSign > 0 && maxSign > 0) {
  9747. // move the bottom down to 0
  9748. me.min = 0;
  9749. }
  9750. }
  9751. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  9752. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  9753. if (tickOpts.min !== undefined) {
  9754. me.min = tickOpts.min;
  9755. } else if (tickOpts.suggestedMin !== undefined) {
  9756. if (me.min === null) {
  9757. me.min = tickOpts.suggestedMin;
  9758. } else {
  9759. me.min = Math.min(me.min, tickOpts.suggestedMin);
  9760. }
  9761. }
  9762. if (tickOpts.max !== undefined) {
  9763. me.max = tickOpts.max;
  9764. } else if (tickOpts.suggestedMax !== undefined) {
  9765. if (me.max === null) {
  9766. me.max = tickOpts.suggestedMax;
  9767. } else {
  9768. me.max = Math.max(me.max, tickOpts.suggestedMax);
  9769. }
  9770. }
  9771. if (setMin !== setMax) {
  9772. // We set the min or the max but not both.
  9773. // So ensure that our range is good
  9774. // Inverted or 0 length range can happen when
  9775. // ticks.min is set, and no datasets are visible
  9776. if (me.min >= me.max) {
  9777. if (setMin) {
  9778. me.max = me.min + 1;
  9779. } else {
  9780. me.min = me.max - 1;
  9781. }
  9782. }
  9783. }
  9784. if (me.min === me.max) {
  9785. me.max++;
  9786. if (!tickOpts.beginAtZero) {
  9787. me.min--;
  9788. }
  9789. }
  9790. },
  9791. getTickLimit: function() {
  9792. var me = this;
  9793. var tickOpts = me.options.ticks;
  9794. var stepSize = tickOpts.stepSize;
  9795. var maxTicksLimit = tickOpts.maxTicksLimit;
  9796. var maxTicks;
  9797. if (stepSize) {
  9798. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  9799. } else {
  9800. maxTicks = me._computeTickLimit();
  9801. maxTicksLimit = maxTicksLimit || 11;
  9802. }
  9803. if (maxTicksLimit) {
  9804. maxTicks = Math.min(maxTicksLimit, maxTicks);
  9805. }
  9806. return maxTicks;
  9807. },
  9808. _computeTickLimit: function() {
  9809. return Number.POSITIVE_INFINITY;
  9810. },
  9811. handleDirectionalChanges: noop,
  9812. buildTicks: function() {
  9813. var me = this;
  9814. var opts = me.options;
  9815. var tickOpts = opts.ticks;
  9816. // Figure out what the max number of ticks we can support it is based on the size of
  9817. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  9818. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  9819. // the graph. Make sure we always have at least 2 ticks
  9820. var maxTicks = me.getTickLimit();
  9821. maxTicks = Math.max(2, maxTicks);
  9822. var numericGeneratorOptions = {
  9823. maxTicks: maxTicks,
  9824. min: tickOpts.min,
  9825. max: tickOpts.max,
  9826. precision: tickOpts.precision,
  9827. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  9828. };
  9829. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  9830. me.handleDirectionalChanges();
  9831. // At this point, we need to update our max and min given the tick values since we have expanded the
  9832. // range of the scale
  9833. me.max = helpers$1.max(ticks);
  9834. me.min = helpers$1.min(ticks);
  9835. if (tickOpts.reverse) {
  9836. ticks.reverse();
  9837. me.start = me.max;
  9838. me.end = me.min;
  9839. } else {
  9840. me.start = me.min;
  9841. me.end = me.max;
  9842. }
  9843. },
  9844. convertTicksToLabels: function() {
  9845. var me = this;
  9846. me.ticksAsNumbers = me.ticks.slice();
  9847. me.zeroLineIndex = me.ticks.indexOf(0);
  9848. core_scale.prototype.convertTicksToLabels.call(me);
  9849. }
  9850. });
  9851. var defaultConfig$1 = {
  9852. position: 'left',
  9853. ticks: {
  9854. callback: core_ticks.formatters.linear
  9855. }
  9856. };
  9857. var scale_linear = scale_linearbase.extend({
  9858. determineDataLimits: function() {
  9859. var me = this;
  9860. var opts = me.options;
  9861. var chart = me.chart;
  9862. var data = chart.data;
  9863. var datasets = data.datasets;
  9864. var isHorizontal = me.isHorizontal();
  9865. var DEFAULT_MIN = 0;
  9866. var DEFAULT_MAX = 1;
  9867. function IDMatches(meta) {
  9868. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  9869. }
  9870. // First Calculate the range
  9871. me.min = null;
  9872. me.max = null;
  9873. var hasStacks = opts.stacked;
  9874. if (hasStacks === undefined) {
  9875. helpers$1.each(datasets, function(dataset, datasetIndex) {
  9876. if (hasStacks) {
  9877. return;
  9878. }
  9879. var meta = chart.getDatasetMeta(datasetIndex);
  9880. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  9881. meta.stack !== undefined) {
  9882. hasStacks = true;
  9883. }
  9884. });
  9885. }
  9886. if (opts.stacked || hasStacks) {
  9887. var valuesPerStack = {};
  9888. helpers$1.each(datasets, function(dataset, datasetIndex) {
  9889. var meta = chart.getDatasetMeta(datasetIndex);
  9890. var key = [
  9891. meta.type,
  9892. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  9893. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  9894. meta.stack
  9895. ].join('.');
  9896. if (valuesPerStack[key] === undefined) {
  9897. valuesPerStack[key] = {
  9898. positiveValues: [],
  9899. negativeValues: []
  9900. };
  9901. }
  9902. // Store these per type
  9903. var positiveValues = valuesPerStack[key].positiveValues;
  9904. var negativeValues = valuesPerStack[key].negativeValues;
  9905. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  9906. helpers$1.each(dataset.data, function(rawValue, index) {
  9907. var value = +me.getRightValue(rawValue);
  9908. if (isNaN(value) || meta.data[index].hidden) {
  9909. return;
  9910. }
  9911. positiveValues[index] = positiveValues[index] || 0;
  9912. negativeValues[index] = negativeValues[index] || 0;
  9913. if (opts.relativePoints) {
  9914. positiveValues[index] = 100;
  9915. } else if (value < 0) {
  9916. negativeValues[index] += value;
  9917. } else {
  9918. positiveValues[index] += value;
  9919. }
  9920. });
  9921. }
  9922. });
  9923. helpers$1.each(valuesPerStack, function(valuesForType) {
  9924. var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
  9925. var minVal = helpers$1.min(values);
  9926. var maxVal = helpers$1.max(values);
  9927. me.min = me.min === null ? minVal : Math.min(me.min, minVal);
  9928. me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
  9929. });
  9930. } else {
  9931. helpers$1.each(datasets, function(dataset, datasetIndex) {
  9932. var meta = chart.getDatasetMeta(datasetIndex);
  9933. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  9934. helpers$1.each(dataset.data, function(rawValue, index) {
  9935. var value = +me.getRightValue(rawValue);
  9936. if (isNaN(value) || meta.data[index].hidden) {
  9937. return;
  9938. }
  9939. if (me.min === null) {
  9940. me.min = value;
  9941. } else if (value < me.min) {
  9942. me.min = value;
  9943. }
  9944. if (me.max === null) {
  9945. me.max = value;
  9946. } else if (value > me.max) {
  9947. me.max = value;
  9948. }
  9949. });
  9950. }
  9951. });
  9952. }
  9953. me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  9954. me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  9955. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  9956. this.handleTickRangeOptions();
  9957. },
  9958. // Returns the maximum number of ticks based on the scale dimension
  9959. _computeTickLimit: function() {
  9960. var me = this;
  9961. var tickFont;
  9962. if (me.isHorizontal()) {
  9963. return Math.ceil(me.width / 40);
  9964. }
  9965. tickFont = helpers$1.options._parseFont(me.options.ticks);
  9966. return Math.ceil(me.height / tickFont.lineHeight);
  9967. },
  9968. // Called after the ticks are built. We need
  9969. handleDirectionalChanges: function() {
  9970. if (!this.isHorizontal()) {
  9971. // We are in a vertical orientation. The top value is the highest. So reverse the array
  9972. this.ticks.reverse();
  9973. }
  9974. },
  9975. getLabelForIndex: function(index, datasetIndex) {
  9976. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  9977. },
  9978. // Utils
  9979. getPixelForValue: function(value) {
  9980. // This must be called after fit has been run so that
  9981. // this.left, this.top, this.right, and this.bottom have been defined
  9982. var me = this;
  9983. var start = me.start;
  9984. var rightValue = +me.getRightValue(value);
  9985. var pixel;
  9986. var range = me.end - start;
  9987. if (me.isHorizontal()) {
  9988. pixel = me.left + (me.width / range * (rightValue - start));
  9989. } else {
  9990. pixel = me.bottom - (me.height / range * (rightValue - start));
  9991. }
  9992. return pixel;
  9993. },
  9994. getValueForPixel: function(pixel) {
  9995. var me = this;
  9996. var isHorizontal = me.isHorizontal();
  9997. var innerDimension = isHorizontal ? me.width : me.height;
  9998. var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;
  9999. return me.start + ((me.end - me.start) * offset);
  10000. },
  10001. getPixelForTick: function(index) {
  10002. return this.getPixelForValue(this.ticksAsNumbers[index]);
  10003. }
  10004. });
  10005. // INTERNAL: static default options, registered in src/index.js
  10006. var _defaults$1 = defaultConfig$1;
  10007. scale_linear._defaults = _defaults$1;
  10008. var valueOrDefault$a = helpers$1.valueOrDefault;
  10009. /**
  10010. * Generate a set of logarithmic ticks
  10011. * @param generationOptions the options used to generate the ticks
  10012. * @param dataRange the range of the data
  10013. * @returns {number[]} array of tick values
  10014. */
  10015. function generateTicks$1(generationOptions, dataRange) {
  10016. var ticks = [];
  10017. var tickVal = valueOrDefault$a(generationOptions.min, Math.pow(10, Math.floor(helpers$1.log10(dataRange.min))));
  10018. var endExp = Math.floor(helpers$1.log10(dataRange.max));
  10019. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  10020. var exp, significand;
  10021. if (tickVal === 0) {
  10022. exp = Math.floor(helpers$1.log10(dataRange.minNotZero));
  10023. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  10024. ticks.push(tickVal);
  10025. tickVal = significand * Math.pow(10, exp);
  10026. } else {
  10027. exp = Math.floor(helpers$1.log10(tickVal));
  10028. significand = Math.floor(tickVal / Math.pow(10, exp));
  10029. }
  10030. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  10031. do {
  10032. ticks.push(tickVal);
  10033. ++significand;
  10034. if (significand === 10) {
  10035. significand = 1;
  10036. ++exp;
  10037. precision = exp >= 0 ? 1 : precision;
  10038. }
  10039. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  10040. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  10041. var lastTick = valueOrDefault$a(generationOptions.max, tickVal);
  10042. ticks.push(lastTick);
  10043. return ticks;
  10044. }
  10045. var defaultConfig$2 = {
  10046. position: 'left',
  10047. // label settings
  10048. ticks: {
  10049. callback: core_ticks.formatters.logarithmic
  10050. }
  10051. };
  10052. // TODO(v3): change this to positiveOrDefault
  10053. function nonNegativeOrDefault(value, defaultValue) {
  10054. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  10055. }
  10056. var scale_logarithmic = core_scale.extend({
  10057. determineDataLimits: function() {
  10058. var me = this;
  10059. var opts = me.options;
  10060. var chart = me.chart;
  10061. var data = chart.data;
  10062. var datasets = data.datasets;
  10063. var isHorizontal = me.isHorizontal();
  10064. function IDMatches(meta) {
  10065. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  10066. }
  10067. // Calculate Range
  10068. me.min = null;
  10069. me.max = null;
  10070. me.minNotZero = null;
  10071. var hasStacks = opts.stacked;
  10072. if (hasStacks === undefined) {
  10073. helpers$1.each(datasets, function(dataset, datasetIndex) {
  10074. if (hasStacks) {
  10075. return;
  10076. }
  10077. var meta = chart.getDatasetMeta(datasetIndex);
  10078. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  10079. meta.stack !== undefined) {
  10080. hasStacks = true;
  10081. }
  10082. });
  10083. }
  10084. if (opts.stacked || hasStacks) {
  10085. var valuesPerStack = {};
  10086. helpers$1.each(datasets, function(dataset, datasetIndex) {
  10087. var meta = chart.getDatasetMeta(datasetIndex);
  10088. var key = [
  10089. meta.type,
  10090. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  10091. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  10092. meta.stack
  10093. ].join('.');
  10094. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  10095. if (valuesPerStack[key] === undefined) {
  10096. valuesPerStack[key] = [];
  10097. }
  10098. helpers$1.each(dataset.data, function(rawValue, index) {
  10099. var values = valuesPerStack[key];
  10100. var value = +me.getRightValue(rawValue);
  10101. // invalid, hidden and negative values are ignored
  10102. if (isNaN(value) || meta.data[index].hidden || value < 0) {
  10103. return;
  10104. }
  10105. values[index] = values[index] || 0;
  10106. values[index] += value;
  10107. });
  10108. }
  10109. });
  10110. helpers$1.each(valuesPerStack, function(valuesForType) {
  10111. if (valuesForType.length > 0) {
  10112. var minVal = helpers$1.min(valuesForType);
  10113. var maxVal = helpers$1.max(valuesForType);
  10114. me.min = me.min === null ? minVal : Math.min(me.min, minVal);
  10115. me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
  10116. }
  10117. });
  10118. } else {
  10119. helpers$1.each(datasets, function(dataset, datasetIndex) {
  10120. var meta = chart.getDatasetMeta(datasetIndex);
  10121. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  10122. helpers$1.each(dataset.data, function(rawValue, index) {
  10123. var value = +me.getRightValue(rawValue);
  10124. // invalid, hidden and negative values are ignored
  10125. if (isNaN(value) || meta.data[index].hidden || value < 0) {
  10126. return;
  10127. }
  10128. if (me.min === null) {
  10129. me.min = value;
  10130. } else if (value < me.min) {
  10131. me.min = value;
  10132. }
  10133. if (me.max === null) {
  10134. me.max = value;
  10135. } else if (value > me.max) {
  10136. me.max = value;
  10137. }
  10138. if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {
  10139. me.minNotZero = value;
  10140. }
  10141. });
  10142. }
  10143. });
  10144. }
  10145. // Common base implementation to handle ticks.min, ticks.max
  10146. this.handleTickRangeOptions();
  10147. },
  10148. handleTickRangeOptions: function() {
  10149. var me = this;
  10150. var tickOpts = me.options.ticks;
  10151. var DEFAULT_MIN = 1;
  10152. var DEFAULT_MAX = 10;
  10153. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  10154. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  10155. if (me.min === me.max) {
  10156. if (me.min !== 0 && me.min !== null) {
  10157. me.min = Math.pow(10, Math.floor(helpers$1.log10(me.min)) - 1);
  10158. me.max = Math.pow(10, Math.floor(helpers$1.log10(me.max)) + 1);
  10159. } else {
  10160. me.min = DEFAULT_MIN;
  10161. me.max = DEFAULT_MAX;
  10162. }
  10163. }
  10164. if (me.min === null) {
  10165. me.min = Math.pow(10, Math.floor(helpers$1.log10(me.max)) - 1);
  10166. }
  10167. if (me.max === null) {
  10168. me.max = me.min !== 0
  10169. ? Math.pow(10, Math.floor(helpers$1.log10(me.min)) + 1)
  10170. : DEFAULT_MAX;
  10171. }
  10172. if (me.minNotZero === null) {
  10173. if (me.min > 0) {
  10174. me.minNotZero = me.min;
  10175. } else if (me.max < 1) {
  10176. me.minNotZero = Math.pow(10, Math.floor(helpers$1.log10(me.max)));
  10177. } else {
  10178. me.minNotZero = DEFAULT_MIN;
  10179. }
  10180. }
  10181. },
  10182. buildTicks: function() {
  10183. var me = this;
  10184. var tickOpts = me.options.ticks;
  10185. var reverse = !me.isHorizontal();
  10186. var generationOptions = {
  10187. min: nonNegativeOrDefault(tickOpts.min),
  10188. max: nonNegativeOrDefault(tickOpts.max)
  10189. };
  10190. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  10191. // At this point, we need to update our max and min given the tick values since we have expanded the
  10192. // range of the scale
  10193. me.max = helpers$1.max(ticks);
  10194. me.min = helpers$1.min(ticks);
  10195. if (tickOpts.reverse) {
  10196. reverse = !reverse;
  10197. me.start = me.max;
  10198. me.end = me.min;
  10199. } else {
  10200. me.start = me.min;
  10201. me.end = me.max;
  10202. }
  10203. if (reverse) {
  10204. ticks.reverse();
  10205. }
  10206. },
  10207. convertTicksToLabels: function() {
  10208. this.tickValues = this.ticks.slice();
  10209. core_scale.prototype.convertTicksToLabels.call(this);
  10210. },
  10211. // Get the correct tooltip label
  10212. getLabelForIndex: function(index, datasetIndex) {
  10213. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  10214. },
  10215. getPixelForTick: function(index) {
  10216. return this.getPixelForValue(this.tickValues[index]);
  10217. },
  10218. /**
  10219. * Returns the value of the first tick.
  10220. * @param {number} value - The minimum not zero value.
  10221. * @return {number} The first tick value.
  10222. * @private
  10223. */
  10224. _getFirstTickValue: function(value) {
  10225. var exp = Math.floor(helpers$1.log10(value));
  10226. var significand = Math.floor(value / Math.pow(10, exp));
  10227. return significand * Math.pow(10, exp);
  10228. },
  10229. getPixelForValue: function(value) {
  10230. var me = this;
  10231. var tickOpts = me.options.ticks;
  10232. var reverse = tickOpts.reverse;
  10233. var log10 = helpers$1.log10;
  10234. var firstTickValue = me._getFirstTickValue(me.minNotZero);
  10235. var offset = 0;
  10236. var innerDimension, pixel, start, end, sign;
  10237. value = +me.getRightValue(value);
  10238. if (reverse) {
  10239. start = me.end;
  10240. end = me.start;
  10241. sign = -1;
  10242. } else {
  10243. start = me.start;
  10244. end = me.end;
  10245. sign = 1;
  10246. }
  10247. if (me.isHorizontal()) {
  10248. innerDimension = me.width;
  10249. pixel = reverse ? me.right : me.left;
  10250. } else {
  10251. innerDimension = me.height;
  10252. sign *= -1; // invert, since the upper-left corner of the canvas is at pixel (0, 0)
  10253. pixel = reverse ? me.top : me.bottom;
  10254. }
  10255. if (value !== start) {
  10256. if (start === 0) { // include zero tick
  10257. offset = valueOrDefault$a(tickOpts.fontSize, core_defaults.global.defaultFontSize);
  10258. innerDimension -= offset;
  10259. start = firstTickValue;
  10260. }
  10261. if (value !== 0) {
  10262. offset += innerDimension / (log10(end) - log10(start)) * (log10(value) - log10(start));
  10263. }
  10264. pixel += sign * offset;
  10265. }
  10266. return pixel;
  10267. },
  10268. getValueForPixel: function(pixel) {
  10269. var me = this;
  10270. var tickOpts = me.options.ticks;
  10271. var reverse = tickOpts.reverse;
  10272. var log10 = helpers$1.log10;
  10273. var firstTickValue = me._getFirstTickValue(me.minNotZero);
  10274. var innerDimension, start, end, value;
  10275. if (reverse) {
  10276. start = me.end;
  10277. end = me.start;
  10278. } else {
  10279. start = me.start;
  10280. end = me.end;
  10281. }
  10282. if (me.isHorizontal()) {
  10283. innerDimension = me.width;
  10284. value = reverse ? me.right - pixel : pixel - me.left;
  10285. } else {
  10286. innerDimension = me.height;
  10287. value = reverse ? pixel - me.top : me.bottom - pixel;
  10288. }
  10289. if (value !== start) {
  10290. if (start === 0) { // include zero tick
  10291. var offset = valueOrDefault$a(tickOpts.fontSize, core_defaults.global.defaultFontSize);
  10292. value -= offset;
  10293. innerDimension -= offset;
  10294. start = firstTickValue;
  10295. }
  10296. value *= log10(end) - log10(start);
  10297. value /= innerDimension;
  10298. value = Math.pow(10, log10(start) + value);
  10299. }
  10300. return value;
  10301. }
  10302. });
  10303. // INTERNAL: static default options, registered in src/index.js
  10304. var _defaults$2 = defaultConfig$2;
  10305. scale_logarithmic._defaults = _defaults$2;
  10306. var valueOrDefault$b = helpers$1.valueOrDefault;
  10307. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  10308. var resolve$7 = helpers$1.options.resolve;
  10309. var defaultConfig$3 = {
  10310. display: true,
  10311. // Boolean - Whether to animate scaling the chart from the centre
  10312. animate: true,
  10313. position: 'chartArea',
  10314. angleLines: {
  10315. display: true,
  10316. color: 'rgba(0, 0, 0, 0.1)',
  10317. lineWidth: 1,
  10318. borderDash: [],
  10319. borderDashOffset: 0.0
  10320. },
  10321. gridLines: {
  10322. circular: false
  10323. },
  10324. // label settings
  10325. ticks: {
  10326. // Boolean - Show a backdrop to the scale label
  10327. showLabelBackdrop: true,
  10328. // String - The colour of the label backdrop
  10329. backdropColor: 'rgba(255,255,255,0.75)',
  10330. // Number - The backdrop padding above & below the label in pixels
  10331. backdropPaddingY: 2,
  10332. // Number - The backdrop padding to the side of the label in pixels
  10333. backdropPaddingX: 2,
  10334. callback: core_ticks.formatters.linear
  10335. },
  10336. pointLabels: {
  10337. // Boolean - if true, show point labels
  10338. display: true,
  10339. // Number - Point label font size in pixels
  10340. fontSize: 10,
  10341. // Function - Used to convert point labels
  10342. callback: function(label) {
  10343. return label;
  10344. }
  10345. }
  10346. };
  10347. function getValueCount(scale) {
  10348. var opts = scale.options;
  10349. return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0;
  10350. }
  10351. function getTickBackdropHeight(opts) {
  10352. var tickOpts = opts.ticks;
  10353. if (tickOpts.display && opts.display) {
  10354. return valueOrDefault$b(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  10355. }
  10356. return 0;
  10357. }
  10358. function measureLabelSize(ctx, lineHeight, label) {
  10359. if (helpers$1.isArray(label)) {
  10360. return {
  10361. w: helpers$1.longestText(ctx, ctx.font, label),
  10362. h: label.length * lineHeight
  10363. };
  10364. }
  10365. return {
  10366. w: ctx.measureText(label).width,
  10367. h: lineHeight
  10368. };
  10369. }
  10370. function determineLimits(angle, pos, size, min, max) {
  10371. if (angle === min || angle === max) {
  10372. return {
  10373. start: pos - (size / 2),
  10374. end: pos + (size / 2)
  10375. };
  10376. } else if (angle < min || angle > max) {
  10377. return {
  10378. start: pos - size,
  10379. end: pos
  10380. };
  10381. }
  10382. return {
  10383. start: pos,
  10384. end: pos + size
  10385. };
  10386. }
  10387. /**
  10388. * Helper function to fit a radial linear scale with point labels
  10389. */
  10390. function fitWithPointLabels(scale) {
  10391. // Right, this is really confusing and there is a lot of maths going on here
  10392. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  10393. //
  10394. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  10395. //
  10396. // Solution:
  10397. //
  10398. // We assume the radius of the polygon is half the size of the canvas at first
  10399. // at each index we check if the text overlaps.
  10400. //
  10401. // Where it does, we store that angle and that index.
  10402. //
  10403. // After finding the largest index and angle we calculate how much we need to remove
  10404. // from the shape radius to move the point inwards by that x.
  10405. //
  10406. // We average the left and right distances to get the maximum shape radius that can fit in the box
  10407. // along with labels.
  10408. //
  10409. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  10410. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  10411. //
  10412. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  10413. // and position it in the most space efficient manner
  10414. //
  10415. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  10416. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  10417. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  10418. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  10419. var furthestLimits = {
  10420. l: 0,
  10421. r: scale.width,
  10422. t: 0,
  10423. b: scale.height - scale.paddingTop
  10424. };
  10425. var furthestAngles = {};
  10426. var i, textSize, pointPosition;
  10427. scale.ctx.font = plFont.string;
  10428. scale._pointLabelSizes = [];
  10429. var valueCount = getValueCount(scale);
  10430. for (i = 0; i < valueCount; i++) {
  10431. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  10432. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i] || '');
  10433. scale._pointLabelSizes[i] = textSize;
  10434. // Add quarter circle to make degree 0 mean top of circle
  10435. var angleRadians = scale.getIndexAngle(i);
  10436. var angle = helpers$1.toDegrees(angleRadians) % 360;
  10437. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  10438. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  10439. if (hLimits.start < furthestLimits.l) {
  10440. furthestLimits.l = hLimits.start;
  10441. furthestAngles.l = angleRadians;
  10442. }
  10443. if (hLimits.end > furthestLimits.r) {
  10444. furthestLimits.r = hLimits.end;
  10445. furthestAngles.r = angleRadians;
  10446. }
  10447. if (vLimits.start < furthestLimits.t) {
  10448. furthestLimits.t = vLimits.start;
  10449. furthestAngles.t = angleRadians;
  10450. }
  10451. if (vLimits.end > furthestLimits.b) {
  10452. furthestLimits.b = vLimits.end;
  10453. furthestAngles.b = angleRadians;
  10454. }
  10455. }
  10456. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  10457. }
  10458. function getTextAlignForAngle(angle) {
  10459. if (angle === 0 || angle === 180) {
  10460. return 'center';
  10461. } else if (angle < 180) {
  10462. return 'left';
  10463. }
  10464. return 'right';
  10465. }
  10466. function fillText(ctx, text, position, lineHeight) {
  10467. var y = position.y + lineHeight / 2;
  10468. var i, ilen;
  10469. if (helpers$1.isArray(text)) {
  10470. for (i = 0, ilen = text.length; i < ilen; ++i) {
  10471. ctx.fillText(text[i], position.x, y);
  10472. y += lineHeight;
  10473. }
  10474. } else {
  10475. ctx.fillText(text, position.x, y);
  10476. }
  10477. }
  10478. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  10479. if (angle === 90 || angle === 270) {
  10480. position.y -= (textSize.h / 2);
  10481. } else if (angle > 270 || angle < 90) {
  10482. position.y -= textSize.h;
  10483. }
  10484. }
  10485. function drawPointLabels(scale) {
  10486. var ctx = scale.ctx;
  10487. var opts = scale.options;
  10488. var angleLineOpts = opts.angleLines;
  10489. var gridLineOpts = opts.gridLines;
  10490. var pointLabelOpts = opts.pointLabels;
  10491. var lineWidth = valueOrDefault$b(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  10492. var lineColor = valueOrDefault$b(angleLineOpts.color, gridLineOpts.color);
  10493. var tickBackdropHeight = getTickBackdropHeight(opts);
  10494. ctx.save();
  10495. ctx.lineWidth = lineWidth;
  10496. ctx.strokeStyle = lineColor;
  10497. if (ctx.setLineDash) {
  10498. ctx.setLineDash(resolve$7([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  10499. ctx.lineDashOffset = resolve$7([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  10500. }
  10501. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  10502. // Point Label Font
  10503. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  10504. ctx.font = plFont.string;
  10505. ctx.textBaseline = 'middle';
  10506. for (var i = getValueCount(scale) - 1; i >= 0; i--) {
  10507. if (angleLineOpts.display && lineWidth && lineColor) {
  10508. var outerPosition = scale.getPointPosition(i, outerDistance);
  10509. ctx.beginPath();
  10510. ctx.moveTo(scale.xCenter, scale.yCenter);
  10511. ctx.lineTo(outerPosition.x, outerPosition.y);
  10512. ctx.stroke();
  10513. }
  10514. if (pointLabelOpts.display) {
  10515. // Extra pixels out for some label spacing
  10516. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  10517. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  10518. // Keep this in loop since we may support array properties here
  10519. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  10520. ctx.fillStyle = pointLabelFontColor;
  10521. var angleRadians = scale.getIndexAngle(i);
  10522. var angle = helpers$1.toDegrees(angleRadians);
  10523. ctx.textAlign = getTextAlignForAngle(angle);
  10524. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  10525. fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.lineHeight);
  10526. }
  10527. }
  10528. ctx.restore();
  10529. }
  10530. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  10531. var ctx = scale.ctx;
  10532. var circular = gridLineOpts.circular;
  10533. var valueCount = getValueCount(scale);
  10534. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  10535. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  10536. var pointPosition;
  10537. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  10538. return;
  10539. }
  10540. ctx.save();
  10541. ctx.strokeStyle = lineColor;
  10542. ctx.lineWidth = lineWidth;
  10543. if (ctx.setLineDash) {
  10544. ctx.setLineDash(gridLineOpts.borderDash || []);
  10545. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  10546. }
  10547. ctx.beginPath();
  10548. if (circular) {
  10549. // Draw circular arcs between the points
  10550. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  10551. } else {
  10552. // Draw straight lines connecting each index
  10553. pointPosition = scale.getPointPosition(0, radius);
  10554. ctx.moveTo(pointPosition.x, pointPosition.y);
  10555. for (var i = 1; i < valueCount; i++) {
  10556. pointPosition = scale.getPointPosition(i, radius);
  10557. ctx.lineTo(pointPosition.x, pointPosition.y);
  10558. }
  10559. }
  10560. ctx.closePath();
  10561. ctx.stroke();
  10562. ctx.restore();
  10563. }
  10564. function numberOrZero(param) {
  10565. return helpers$1.isNumber(param) ? param : 0;
  10566. }
  10567. var scale_radialLinear = scale_linearbase.extend({
  10568. setDimensions: function() {
  10569. var me = this;
  10570. // Set the unconstrained dimension before label rotation
  10571. me.width = me.maxWidth;
  10572. me.height = me.maxHeight;
  10573. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  10574. me.xCenter = Math.floor(me.width / 2);
  10575. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  10576. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  10577. },
  10578. determineDataLimits: function() {
  10579. var me = this;
  10580. var chart = me.chart;
  10581. var min = Number.POSITIVE_INFINITY;
  10582. var max = Number.NEGATIVE_INFINITY;
  10583. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  10584. if (chart.isDatasetVisible(datasetIndex)) {
  10585. var meta = chart.getDatasetMeta(datasetIndex);
  10586. helpers$1.each(dataset.data, function(rawValue, index) {
  10587. var value = +me.getRightValue(rawValue);
  10588. if (isNaN(value) || meta.data[index].hidden) {
  10589. return;
  10590. }
  10591. min = Math.min(value, min);
  10592. max = Math.max(value, max);
  10593. });
  10594. }
  10595. });
  10596. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  10597. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  10598. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  10599. me.handleTickRangeOptions();
  10600. },
  10601. // Returns the maximum number of ticks based on the scale dimension
  10602. _computeTickLimit: function() {
  10603. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  10604. },
  10605. convertTicksToLabels: function() {
  10606. var me = this;
  10607. scale_linearbase.prototype.convertTicksToLabels.call(me);
  10608. // Point labels
  10609. me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
  10610. },
  10611. getLabelForIndex: function(index, datasetIndex) {
  10612. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  10613. },
  10614. fit: function() {
  10615. var me = this;
  10616. var opts = me.options;
  10617. if (opts.display && opts.pointLabels.display) {
  10618. fitWithPointLabels(me);
  10619. } else {
  10620. me.setCenterPoint(0, 0, 0, 0);
  10621. }
  10622. },
  10623. /**
  10624. * Set radius reductions and determine new radius and center point
  10625. * @private
  10626. */
  10627. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  10628. var me = this;
  10629. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  10630. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  10631. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  10632. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  10633. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  10634. radiusReductionRight = numberOrZero(radiusReductionRight);
  10635. radiusReductionTop = numberOrZero(radiusReductionTop);
  10636. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  10637. me.drawingArea = Math.min(
  10638. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  10639. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  10640. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  10641. },
  10642. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  10643. var me = this;
  10644. var maxRight = me.width - rightMovement - me.drawingArea;
  10645. var maxLeft = leftMovement + me.drawingArea;
  10646. var maxTop = topMovement + me.drawingArea;
  10647. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  10648. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  10649. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  10650. },
  10651. getIndexAngle: function(index) {
  10652. var angleMultiplier = (Math.PI * 2) / getValueCount(this);
  10653. var startAngle = this.chart.options && this.chart.options.startAngle ?
  10654. this.chart.options.startAngle :
  10655. 0;
  10656. var startAngleRadians = startAngle * Math.PI * 2 / 360;
  10657. // Start from the top instead of right, so remove a quarter of the circle
  10658. return index * angleMultiplier + startAngleRadians;
  10659. },
  10660. getDistanceFromCenterForValue: function(value) {
  10661. var me = this;
  10662. if (value === null) {
  10663. return 0; // null always in center
  10664. }
  10665. // Take into account half font size + the yPadding of the top value
  10666. var scalingFactor = me.drawingArea / (me.max - me.min);
  10667. if (me.options.ticks.reverse) {
  10668. return (me.max - value) * scalingFactor;
  10669. }
  10670. return (value - me.min) * scalingFactor;
  10671. },
  10672. getPointPosition: function(index, distanceFromCenter) {
  10673. var me = this;
  10674. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  10675. return {
  10676. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  10677. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  10678. };
  10679. },
  10680. getPointPositionForValue: function(index, value) {
  10681. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  10682. },
  10683. getBasePosition: function() {
  10684. var me = this;
  10685. var min = me.min;
  10686. var max = me.max;
  10687. return me.getPointPositionForValue(0,
  10688. me.beginAtZero ? 0 :
  10689. min < 0 && max < 0 ? max :
  10690. min > 0 && max > 0 ? min :
  10691. 0);
  10692. },
  10693. draw: function() {
  10694. var me = this;
  10695. var opts = me.options;
  10696. var gridLineOpts = opts.gridLines;
  10697. var tickOpts = opts.ticks;
  10698. if (opts.display) {
  10699. var ctx = me.ctx;
  10700. var startAngle = this.getIndexAngle(0);
  10701. var tickFont = helpers$1.options._parseFont(tickOpts);
  10702. if (opts.angleLines.display || opts.pointLabels.display) {
  10703. drawPointLabels(me);
  10704. }
  10705. helpers$1.each(me.ticks, function(label, index) {
  10706. // Don't draw a centre value (if it is minimum)
  10707. if (index > 0 || tickOpts.reverse) {
  10708. var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  10709. // Draw circular lines around the scale
  10710. if (gridLineOpts.display && index !== 0) {
  10711. drawRadiusLine(me, gridLineOpts, yCenterOffset, index);
  10712. }
  10713. if (tickOpts.display) {
  10714. var tickFontColor = valueOrDefault$b(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  10715. ctx.font = tickFont.string;
  10716. ctx.save();
  10717. ctx.translate(me.xCenter, me.yCenter);
  10718. ctx.rotate(startAngle);
  10719. if (tickOpts.showLabelBackdrop) {
  10720. var labelWidth = ctx.measureText(label).width;
  10721. ctx.fillStyle = tickOpts.backdropColor;
  10722. ctx.fillRect(
  10723. -labelWidth / 2 - tickOpts.backdropPaddingX,
  10724. -yCenterOffset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  10725. labelWidth + tickOpts.backdropPaddingX * 2,
  10726. tickFont.size + tickOpts.backdropPaddingY * 2
  10727. );
  10728. }
  10729. ctx.textAlign = 'center';
  10730. ctx.textBaseline = 'middle';
  10731. ctx.fillStyle = tickFontColor;
  10732. ctx.fillText(label, 0, -yCenterOffset);
  10733. ctx.restore();
  10734. }
  10735. }
  10736. });
  10737. }
  10738. }
  10739. });
  10740. // INTERNAL: static default options, registered in src/index.js
  10741. var _defaults$3 = defaultConfig$3;
  10742. scale_radialLinear._defaults = _defaults$3;
  10743. var valueOrDefault$c = helpers$1.valueOrDefault;
  10744. // Integer constants are from the ES6 spec.
  10745. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  10746. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  10747. var INTERVALS = {
  10748. millisecond: {
  10749. common: true,
  10750. size: 1,
  10751. steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
  10752. },
  10753. second: {
  10754. common: true,
  10755. size: 1000,
  10756. steps: [1, 2, 5, 10, 15, 30]
  10757. },
  10758. minute: {
  10759. common: true,
  10760. size: 60000,
  10761. steps: [1, 2, 5, 10, 15, 30]
  10762. },
  10763. hour: {
  10764. common: true,
  10765. size: 3600000,
  10766. steps: [1, 2, 3, 6, 12]
  10767. },
  10768. day: {
  10769. common: true,
  10770. size: 86400000,
  10771. steps: [1, 2, 5]
  10772. },
  10773. week: {
  10774. common: false,
  10775. size: 604800000,
  10776. steps: [1, 2, 3, 4]
  10777. },
  10778. month: {
  10779. common: true,
  10780. size: 2.628e9,
  10781. steps: [1, 2, 3]
  10782. },
  10783. quarter: {
  10784. common: false,
  10785. size: 7.884e9,
  10786. steps: [1, 2, 3, 4]
  10787. },
  10788. year: {
  10789. common: true,
  10790. size: 3.154e10
  10791. }
  10792. };
  10793. var UNITS = Object.keys(INTERVALS);
  10794. function sorter(a, b) {
  10795. return a - b;
  10796. }
  10797. function arrayUnique(items) {
  10798. var hash = {};
  10799. var out = [];
  10800. var i, ilen, item;
  10801. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10802. item = items[i];
  10803. if (!hash[item]) {
  10804. hash[item] = true;
  10805. out.push(item);
  10806. }
  10807. }
  10808. return out;
  10809. }
  10810. /**
  10811. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  10812. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  10813. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  10814. * extremity (left + width or top + height). Note that it would be more optimized to directly
  10815. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  10816. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  10817. *
  10818. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  10819. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  10820. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  10821. * If 'series', timestamps will be positioned at the same distance from each other. In this
  10822. * case, only timestamps that break the time linearity are registered, meaning that in the
  10823. * best case, all timestamps are linear, the table contains only min and max.
  10824. */
  10825. function buildLookupTable(timestamps, min, max, distribution) {
  10826. if (distribution === 'linear' || !timestamps.length) {
  10827. return [
  10828. {time: min, pos: 0},
  10829. {time: max, pos: 1}
  10830. ];
  10831. }
  10832. var table = [];
  10833. var items = [min];
  10834. var i, ilen, prev, curr, next;
  10835. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  10836. curr = timestamps[i];
  10837. if (curr > min && curr < max) {
  10838. items.push(curr);
  10839. }
  10840. }
  10841. items.push(max);
  10842. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10843. next = items[i + 1];
  10844. prev = items[i - 1];
  10845. curr = items[i];
  10846. // only add points that breaks the scale linearity
  10847. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  10848. table.push({time: curr, pos: i / (ilen - 1)});
  10849. }
  10850. }
  10851. return table;
  10852. }
  10853. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  10854. function lookup(table, key, value) {
  10855. var lo = 0;
  10856. var hi = table.length - 1;
  10857. var mid, i0, i1;
  10858. while (lo >= 0 && lo <= hi) {
  10859. mid = (lo + hi) >> 1;
  10860. i0 = table[mid - 1] || null;
  10861. i1 = table[mid];
  10862. if (!i0) {
  10863. // given value is outside table (before first item)
  10864. return {lo: null, hi: i1};
  10865. } else if (i1[key] < value) {
  10866. lo = mid + 1;
  10867. } else if (i0[key] > value) {
  10868. hi = mid - 1;
  10869. } else {
  10870. return {lo: i0, hi: i1};
  10871. }
  10872. }
  10873. // given value is outside table (after last item)
  10874. return {lo: i1, hi: null};
  10875. }
  10876. /**
  10877. * Linearly interpolates the given source `value` using the table items `skey` values and
  10878. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  10879. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  10880. * index [0, 1] or [n - 1, n] are used for the interpolation.
  10881. */
  10882. function interpolate$1(table, skey, sval, tkey) {
  10883. var range = lookup(table, skey, sval);
  10884. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  10885. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  10886. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  10887. var span = next[skey] - prev[skey];
  10888. var ratio = span ? (sval - prev[skey]) / span : 0;
  10889. var offset = (next[tkey] - prev[tkey]) * ratio;
  10890. return prev[tkey] + offset;
  10891. }
  10892. function toTimestamp(scale, input) {
  10893. var adapter = scale._adapter;
  10894. var options = scale.options.time;
  10895. var parser = options.parser;
  10896. var format = parser || options.format;
  10897. var value = input;
  10898. if (typeof parser === 'function') {
  10899. value = parser(value);
  10900. }
  10901. // Only parse if its not a timestamp already
  10902. if (!helpers$1.isFinite(value)) {
  10903. value = typeof format === 'string'
  10904. ? adapter.parse(value, format)
  10905. : adapter.parse(value);
  10906. }
  10907. if (value !== null) {
  10908. return +value;
  10909. }
  10910. // Labels are in an incompatible format and no `parser` has been provided.
  10911. // The user might still use the deprecated `format` option for parsing.
  10912. if (!parser && typeof format === 'function') {
  10913. value = format(input);
  10914. // `format` could return something else than a timestamp, if so, parse it
  10915. if (!helpers$1.isFinite(value)) {
  10916. value = adapter.parse(value);
  10917. }
  10918. }
  10919. return value;
  10920. }
  10921. function parse(scale, input) {
  10922. if (helpers$1.isNullOrUndef(input)) {
  10923. return null;
  10924. }
  10925. var options = scale.options.time;
  10926. var value = toTimestamp(scale, scale.getRightValue(input));
  10927. if (value === null) {
  10928. return value;
  10929. }
  10930. if (options.round) {
  10931. value = +scale._adapter.startOf(value, options.round);
  10932. }
  10933. return value;
  10934. }
  10935. /**
  10936. * Returns the number of unit to skip to be able to display up to `capacity` number of ticks
  10937. * in `unit` for the given `min` / `max` range and respecting the interval steps constraints.
  10938. */
  10939. function determineStepSize(min, max, unit, capacity) {
  10940. var range = max - min;
  10941. var interval = INTERVALS[unit];
  10942. var milliseconds = interval.size;
  10943. var steps = interval.steps;
  10944. var i, ilen, factor;
  10945. if (!steps) {
  10946. return Math.ceil(range / (capacity * milliseconds));
  10947. }
  10948. for (i = 0, ilen = steps.length; i < ilen; ++i) {
  10949. factor = steps[i];
  10950. if (Math.ceil(range / (milliseconds * factor)) <= capacity) {
  10951. break;
  10952. }
  10953. }
  10954. return factor;
  10955. }
  10956. /**
  10957. * Figures out what unit results in an appropriate number of auto-generated ticks
  10958. */
  10959. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  10960. var ilen = UNITS.length;
  10961. var i, interval, factor;
  10962. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  10963. interval = INTERVALS[UNITS[i]];
  10964. factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;
  10965. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  10966. return UNITS[i];
  10967. }
  10968. }
  10969. return UNITS[ilen - 1];
  10970. }
  10971. /**
  10972. * Figures out what unit to format a set of ticks with
  10973. */
  10974. function determineUnitForFormatting(scale, ticks, minUnit, min, max) {
  10975. var ilen = UNITS.length;
  10976. var i, unit;
  10977. for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) {
  10978. unit = UNITS[i];
  10979. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= ticks.length) {
  10980. return unit;
  10981. }
  10982. }
  10983. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  10984. }
  10985. function determineMajorUnit(unit) {
  10986. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  10987. if (INTERVALS[UNITS[i]].common) {
  10988. return UNITS[i];
  10989. }
  10990. }
  10991. }
  10992. /**
  10993. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  10994. * `minor` unit, aligned on the `major` unit and using the given scale time `options`.
  10995. * Important: this method can return ticks outside the min and max range, it's the
  10996. * responsibility of the calling code to clamp values if needed.
  10997. */
  10998. function generate(scale, min, max, capacity) {
  10999. var adapter = scale._adapter;
  11000. var options = scale.options;
  11001. var timeOpts = options.time;
  11002. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  11003. var major = determineMajorUnit(minor);
  11004. var stepSize = valueOrDefault$c(timeOpts.stepSize, timeOpts.unitStepSize);
  11005. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  11006. var majorTicksEnabled = options.ticks.major.enabled;
  11007. var interval = INTERVALS[minor];
  11008. var first = min;
  11009. var last = max;
  11010. var ticks = [];
  11011. var time;
  11012. if (!stepSize) {
  11013. stepSize = determineStepSize(min, max, minor, capacity);
  11014. }
  11015. // For 'week' unit, handle the first day of week option
  11016. if (weekday) {
  11017. first = +adapter.startOf(first, 'isoWeek', weekday);
  11018. last = +adapter.startOf(last, 'isoWeek', weekday);
  11019. }
  11020. // Align first/last ticks on unit
  11021. first = +adapter.startOf(first, weekday ? 'day' : minor);
  11022. last = +adapter.startOf(last, weekday ? 'day' : minor);
  11023. // Make sure that the last tick include max
  11024. if (last < max) {
  11025. last = +adapter.add(last, 1, minor);
  11026. }
  11027. time = first;
  11028. if (majorTicksEnabled && major && !weekday && !timeOpts.round) {
  11029. // Align the first tick on the previous `minor` unit aligned on the `major` unit:
  11030. // we first aligned time on the previous `major` unit then add the number of full
  11031. // stepSize there is between first and the previous major time.
  11032. time = +adapter.startOf(time, major);
  11033. time = +adapter.add(time, ~~((first - time) / (interval.size * stepSize)) * stepSize, minor);
  11034. }
  11035. for (; time < last; time = +adapter.add(time, stepSize, minor)) {
  11036. ticks.push(+time);
  11037. }
  11038. ticks.push(+time);
  11039. return ticks;
  11040. }
  11041. /**
  11042. * Returns the start and end offsets from edges in the form of {start, end}
  11043. * where each value is a relative width to the scale and ranges between 0 and 1.
  11044. * They add extra margins on the both sides by scaling down the original scale.
  11045. * Offsets are added when the `offset` option is true.
  11046. */
  11047. function computeOffsets(table, ticks, min, max, options) {
  11048. var start = 0;
  11049. var end = 0;
  11050. var first, last;
  11051. if (options.offset && ticks.length) {
  11052. if (!options.time.min) {
  11053. first = interpolate$1(table, 'time', ticks[0], 'pos');
  11054. if (ticks.length === 1) {
  11055. start = 1 - first;
  11056. } else {
  11057. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  11058. }
  11059. }
  11060. if (!options.time.max) {
  11061. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  11062. if (ticks.length === 1) {
  11063. end = last;
  11064. } else {
  11065. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  11066. }
  11067. }
  11068. }
  11069. return {start: start, end: end};
  11070. }
  11071. function ticksFromTimestamps(scale, values, majorUnit) {
  11072. var ticks = [];
  11073. var i, ilen, value, major;
  11074. for (i = 0, ilen = values.length; i < ilen; ++i) {
  11075. value = values[i];
  11076. major = majorUnit ? value === +scale._adapter.startOf(value, majorUnit) : false;
  11077. ticks.push({
  11078. value: value,
  11079. major: major
  11080. });
  11081. }
  11082. return ticks;
  11083. }
  11084. var defaultConfig$4 = {
  11085. position: 'bottom',
  11086. /**
  11087. * Data distribution along the scale:
  11088. * - 'linear': data are spread according to their time (distances can vary),
  11089. * - 'series': data are spread at the same distance from each other.
  11090. * @see https://github.com/chartjs/Chart.js/pull/4507
  11091. * @since 2.7.0
  11092. */
  11093. distribution: 'linear',
  11094. /**
  11095. * Scale boundary strategy (bypassed by min/max time options)
  11096. * - `data`: make sure data are fully visible, ticks outside are removed
  11097. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  11098. * @see https://github.com/chartjs/Chart.js/pull/4556
  11099. * @since 2.7.0
  11100. */
  11101. bounds: 'data',
  11102. adapters: {},
  11103. time: {
  11104. 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
  11105. format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from https://momentjs.com/docs/#/parsing/string-format/
  11106. unit: false, // false == automatic or override with week, month, year, etc.
  11107. round: false, // none, or override with week, month, year, etc.
  11108. displayFormat: false, // DEPRECATED
  11109. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  11110. minUnit: 'millisecond',
  11111. displayFormats: {}
  11112. },
  11113. ticks: {
  11114. autoSkip: false,
  11115. /**
  11116. * Ticks generation input values:
  11117. * - 'auto': generates "optimal" ticks based on scale size and time options.
  11118. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  11119. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  11120. * @see https://github.com/chartjs/Chart.js/pull/4507
  11121. * @since 2.7.0
  11122. */
  11123. source: 'auto',
  11124. major: {
  11125. enabled: false
  11126. }
  11127. }
  11128. };
  11129. var scale_time = core_scale.extend({
  11130. initialize: function() {
  11131. this.mergeTicksOptions();
  11132. core_scale.prototype.initialize.call(this);
  11133. },
  11134. update: function() {
  11135. var me = this;
  11136. var options = me.options;
  11137. var time = options.time || (options.time = {});
  11138. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  11139. // DEPRECATIONS: output a message only one time per update
  11140. if (time.format) {
  11141. console.warn('options.time.format is deprecated and replaced by options.time.parser.');
  11142. }
  11143. // Backward compatibility: before introducing adapter, `displayFormats` was
  11144. // supposed to contain *all* unit/string pairs but this can't be resolved
  11145. // when loading the scale (adapters are loaded afterward), so let's populate
  11146. // missing formats on update
  11147. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  11148. return core_scale.prototype.update.apply(me, arguments);
  11149. },
  11150. /**
  11151. * Allows data to be referenced via 't' attribute
  11152. */
  11153. getRightValue: function(rawValue) {
  11154. if (rawValue && rawValue.t !== undefined) {
  11155. rawValue = rawValue.t;
  11156. }
  11157. return core_scale.prototype.getRightValue.call(this, rawValue);
  11158. },
  11159. determineDataLimits: function() {
  11160. var me = this;
  11161. var chart = me.chart;
  11162. var adapter = me._adapter;
  11163. var timeOpts = me.options.time;
  11164. var unit = timeOpts.unit || 'day';
  11165. var min = MAX_INTEGER;
  11166. var max = MIN_INTEGER;
  11167. var timestamps = [];
  11168. var datasets = [];
  11169. var labels = [];
  11170. var i, j, ilen, jlen, data, timestamp;
  11171. var dataLabels = chart.data.labels || [];
  11172. // Convert labels to timestamps
  11173. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  11174. labels.push(parse(me, dataLabels[i]));
  11175. }
  11176. // Convert data to timestamps
  11177. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  11178. if (chart.isDatasetVisible(i)) {
  11179. data = chart.data.datasets[i].data;
  11180. // Let's consider that all data have the same format.
  11181. if (helpers$1.isObject(data[0])) {
  11182. datasets[i] = [];
  11183. for (j = 0, jlen = data.length; j < jlen; ++j) {
  11184. timestamp = parse(me, data[j]);
  11185. timestamps.push(timestamp);
  11186. datasets[i][j] = timestamp;
  11187. }
  11188. } else {
  11189. for (j = 0, jlen = labels.length; j < jlen; ++j) {
  11190. timestamps.push(labels[j]);
  11191. }
  11192. datasets[i] = labels.slice(0);
  11193. }
  11194. } else {
  11195. datasets[i] = [];
  11196. }
  11197. }
  11198. if (labels.length) {
  11199. // Sort labels **after** data have been converted
  11200. labels = arrayUnique(labels).sort(sorter);
  11201. min = Math.min(min, labels[0]);
  11202. max = Math.max(max, labels[labels.length - 1]);
  11203. }
  11204. if (timestamps.length) {
  11205. timestamps = arrayUnique(timestamps).sort(sorter);
  11206. min = Math.min(min, timestamps[0]);
  11207. max = Math.max(max, timestamps[timestamps.length - 1]);
  11208. }
  11209. min = parse(me, timeOpts.min) || min;
  11210. max = parse(me, timeOpts.max) || max;
  11211. // In case there is no valid min/max, set limits based on unit time option
  11212. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  11213. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  11214. // Make sure that max is strictly higher than min (required by the lookup table)
  11215. me.min = Math.min(min, max);
  11216. me.max = Math.max(min + 1, max);
  11217. // PRIVATE
  11218. me._horizontal = me.isHorizontal();
  11219. me._table = [];
  11220. me._timestamps = {
  11221. data: timestamps,
  11222. datasets: datasets,
  11223. labels: labels
  11224. };
  11225. },
  11226. buildTicks: function() {
  11227. var me = this;
  11228. var min = me.min;
  11229. var max = me.max;
  11230. var options = me.options;
  11231. var timeOpts = options.time;
  11232. var timestamps = [];
  11233. var ticks = [];
  11234. var i, ilen, timestamp;
  11235. switch (options.ticks.source) {
  11236. case 'data':
  11237. timestamps = me._timestamps.data;
  11238. break;
  11239. case 'labels':
  11240. timestamps = me._timestamps.labels;
  11241. break;
  11242. case 'auto':
  11243. default:
  11244. timestamps = generate(me, min, max, me.getLabelCapacity(min), options);
  11245. }
  11246. if (options.bounds === 'ticks' && timestamps.length) {
  11247. min = timestamps[0];
  11248. max = timestamps[timestamps.length - 1];
  11249. }
  11250. // Enforce limits with user min/max options
  11251. min = parse(me, timeOpts.min) || min;
  11252. max = parse(me, timeOpts.max) || max;
  11253. // Remove ticks outside the min/max range
  11254. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  11255. timestamp = timestamps[i];
  11256. if (timestamp >= min && timestamp <= max) {
  11257. ticks.push(timestamp);
  11258. }
  11259. }
  11260. me.min = min;
  11261. me.max = max;
  11262. // PRIVATE
  11263. me._unit = timeOpts.unit || determineUnitForFormatting(me, ticks, timeOpts.minUnit, me.min, me.max);
  11264. me._majorUnit = determineMajorUnit(me._unit);
  11265. me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
  11266. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  11267. if (options.ticks.reverse) {
  11268. ticks.reverse();
  11269. }
  11270. return ticksFromTimestamps(me, ticks, me._majorUnit);
  11271. },
  11272. getLabelForIndex: function(index, datasetIndex) {
  11273. var me = this;
  11274. var adapter = me._adapter;
  11275. var data = me.chart.data;
  11276. var timeOpts = me.options.time;
  11277. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  11278. var value = data.datasets[datasetIndex].data[index];
  11279. if (helpers$1.isObject(value)) {
  11280. label = me.getRightValue(value);
  11281. }
  11282. if (timeOpts.tooltipFormat) {
  11283. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  11284. }
  11285. if (typeof label === 'string') {
  11286. return label;
  11287. }
  11288. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  11289. },
  11290. /**
  11291. * Function to format an individual tick mark
  11292. * @private
  11293. */
  11294. tickFormatFunction: function(time, index, ticks, format) {
  11295. var me = this;
  11296. var adapter = me._adapter;
  11297. var options = me.options;
  11298. var formats = options.time.displayFormats;
  11299. var minorFormat = formats[me._unit];
  11300. var majorUnit = me._majorUnit;
  11301. var majorFormat = formats[majorUnit];
  11302. var majorTime = +adapter.startOf(time, majorUnit);
  11303. var majorTickOpts = options.ticks.major;
  11304. var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime;
  11305. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  11306. var tickOpts = major ? majorTickOpts : options.ticks.minor;
  11307. var formatter = valueOrDefault$c(tickOpts.callback, tickOpts.userCallback);
  11308. return formatter ? formatter(label, index, ticks) : label;
  11309. },
  11310. convertTicksToLabels: function(ticks) {
  11311. var labels = [];
  11312. var i, ilen;
  11313. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  11314. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  11315. }
  11316. return labels;
  11317. },
  11318. /**
  11319. * @private
  11320. */
  11321. getPixelForOffset: function(time) {
  11322. var me = this;
  11323. var isReverse = me.options.ticks.reverse;
  11324. var size = me._horizontal ? me.width : me.height;
  11325. var start = me._horizontal ? isReverse ? me.right : me.left : isReverse ? me.bottom : me.top;
  11326. var pos = interpolate$1(me._table, 'time', time, 'pos');
  11327. var offset = size * (me._offsets.start + pos) / (me._offsets.start + 1 + me._offsets.end);
  11328. return isReverse ? start - offset : start + offset;
  11329. },
  11330. getPixelForValue: function(value, index, datasetIndex) {
  11331. var me = this;
  11332. var time = null;
  11333. if (index !== undefined && datasetIndex !== undefined) {
  11334. time = me._timestamps.datasets[datasetIndex][index];
  11335. }
  11336. if (time === null) {
  11337. time = parse(me, value);
  11338. }
  11339. if (time !== null) {
  11340. return me.getPixelForOffset(time);
  11341. }
  11342. },
  11343. getPixelForTick: function(index) {
  11344. var ticks = this.getTicks();
  11345. return index >= 0 && index < ticks.length ?
  11346. this.getPixelForOffset(ticks[index].value) :
  11347. null;
  11348. },
  11349. getValueForPixel: function(pixel) {
  11350. var me = this;
  11351. var size = me._horizontal ? me.width : me.height;
  11352. var start = me._horizontal ? me.left : me.top;
  11353. var pos = (size ? (pixel - start) / size : 0) * (me._offsets.start + 1 + me._offsets.start) - me._offsets.end;
  11354. var time = interpolate$1(me._table, 'pos', pos, 'time');
  11355. // DEPRECATION, we should return time directly
  11356. return me._adapter._create(time);
  11357. },
  11358. /**
  11359. * Crude approximation of what the label width might be
  11360. * @private
  11361. */
  11362. getLabelWidth: function(label) {
  11363. var me = this;
  11364. var ticksOpts = me.options.ticks;
  11365. var tickLabelWidth = me.ctx.measureText(label).width;
  11366. var angle = helpers$1.toRadians(ticksOpts.maxRotation);
  11367. var cosRotation = Math.cos(angle);
  11368. var sinRotation = Math.sin(angle);
  11369. var tickFontSize = valueOrDefault$c(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  11370. return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
  11371. },
  11372. /**
  11373. * @private
  11374. */
  11375. getLabelCapacity: function(exampleTime) {
  11376. var me = this;
  11377. // pick the longest format (milliseconds) for guestimation
  11378. var format = me.options.time.displayFormats.millisecond;
  11379. var exampleLabel = me.tickFormatFunction(exampleTime, 0, [], format);
  11380. var tickLabelWidth = me.getLabelWidth(exampleLabel);
  11381. var innerWidth = me.isHorizontal() ? me.width : me.height;
  11382. var capacity = Math.floor(innerWidth / tickLabelWidth);
  11383. return capacity > 0 ? capacity : 1;
  11384. }
  11385. });
  11386. // INTERNAL: static default options, registered in src/index.js
  11387. var _defaults$4 = defaultConfig$4;
  11388. scale_time._defaults = _defaults$4;
  11389. var scales = {
  11390. category: scale_category,
  11391. linear: scale_linear,
  11392. logarithmic: scale_logarithmic,
  11393. radialLinear: scale_radialLinear,
  11394. time: scale_time
  11395. };
  11396. var moment = createCommonjsModule(function (module, exports) {
  11397. (function (global, factory) {
  11398. module.exports = factory();
  11399. }(commonjsGlobal, (function () {
  11400. var hookCallback;
  11401. function hooks () {
  11402. return hookCallback.apply(null, arguments);
  11403. }
  11404. // This is done to register the method called with moment()
  11405. // without creating circular dependencies.
  11406. function setHookCallback (callback) {
  11407. hookCallback = callback;
  11408. }
  11409. function isArray(input) {
  11410. return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
  11411. }
  11412. function isObject(input) {
  11413. // IE8 will treat undefined and null as object if it wasn't for
  11414. // input != null
  11415. return input != null && Object.prototype.toString.call(input) === '[object Object]';
  11416. }
  11417. function isObjectEmpty(obj) {
  11418. if (Object.getOwnPropertyNames) {
  11419. return (Object.getOwnPropertyNames(obj).length === 0);
  11420. } else {
  11421. var k;
  11422. for (k in obj) {
  11423. if (obj.hasOwnProperty(k)) {
  11424. return false;
  11425. }
  11426. }
  11427. return true;
  11428. }
  11429. }
  11430. function isUndefined(input) {
  11431. return input === void 0;
  11432. }
  11433. function isNumber(input) {
  11434. return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
  11435. }
  11436. function isDate(input) {
  11437. return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
  11438. }
  11439. function map(arr, fn) {
  11440. var res = [], i;
  11441. for (i = 0; i < arr.length; ++i) {
  11442. res.push(fn(arr[i], i));
  11443. }
  11444. return res;
  11445. }
  11446. function hasOwnProp(a, b) {
  11447. return Object.prototype.hasOwnProperty.call(a, b);
  11448. }
  11449. function extend(a, b) {
  11450. for (var i in b) {
  11451. if (hasOwnProp(b, i)) {
  11452. a[i] = b[i];
  11453. }
  11454. }
  11455. if (hasOwnProp(b, 'toString')) {
  11456. a.toString = b.toString;
  11457. }
  11458. if (hasOwnProp(b, 'valueOf')) {
  11459. a.valueOf = b.valueOf;
  11460. }
  11461. return a;
  11462. }
  11463. function createUTC (input, format, locale, strict) {
  11464. return createLocalOrUTC(input, format, locale, strict, true).utc();
  11465. }
  11466. function defaultParsingFlags() {
  11467. // We need to deep clone this object.
  11468. return {
  11469. empty : false,
  11470. unusedTokens : [],
  11471. unusedInput : [],
  11472. overflow : -2,
  11473. charsLeftOver : 0,
  11474. nullInput : false,
  11475. invalidMonth : null,
  11476. invalidFormat : false,
  11477. userInvalidated : false,
  11478. iso : false,
  11479. parsedDateParts : [],
  11480. meridiem : null,
  11481. rfc2822 : false,
  11482. weekdayMismatch : false
  11483. };
  11484. }
  11485. function getParsingFlags(m) {
  11486. if (m._pf == null) {
  11487. m._pf = defaultParsingFlags();
  11488. }
  11489. return m._pf;
  11490. }
  11491. var some;
  11492. if (Array.prototype.some) {
  11493. some = Array.prototype.some;
  11494. } else {
  11495. some = function (fun) {
  11496. var t = Object(this);
  11497. var len = t.length >>> 0;
  11498. for (var i = 0; i < len; i++) {
  11499. if (i in t && fun.call(this, t[i], i, t)) {
  11500. return true;
  11501. }
  11502. }
  11503. return false;
  11504. };
  11505. }
  11506. function isValid(m) {
  11507. if (m._isValid == null) {
  11508. var flags = getParsingFlags(m);
  11509. var parsedParts = some.call(flags.parsedDateParts, function (i) {
  11510. return i != null;
  11511. });
  11512. var isNowValid = !isNaN(m._d.getTime()) &&
  11513. flags.overflow < 0 &&
  11514. !flags.empty &&
  11515. !flags.invalidMonth &&
  11516. !flags.invalidWeekday &&
  11517. !flags.weekdayMismatch &&
  11518. !flags.nullInput &&
  11519. !flags.invalidFormat &&
  11520. !flags.userInvalidated &&
  11521. (!flags.meridiem || (flags.meridiem && parsedParts));
  11522. if (m._strict) {
  11523. isNowValid = isNowValid &&
  11524. flags.charsLeftOver === 0 &&
  11525. flags.unusedTokens.length === 0 &&
  11526. flags.bigHour === undefined;
  11527. }
  11528. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  11529. m._isValid = isNowValid;
  11530. }
  11531. else {
  11532. return isNowValid;
  11533. }
  11534. }
  11535. return m._isValid;
  11536. }
  11537. function createInvalid (flags) {
  11538. var m = createUTC(NaN);
  11539. if (flags != null) {
  11540. extend(getParsingFlags(m), flags);
  11541. }
  11542. else {
  11543. getParsingFlags(m).userInvalidated = true;
  11544. }
  11545. return m;
  11546. }
  11547. // Plugins that add properties should also add the key here (null value),
  11548. // so we can properly clone ourselves.
  11549. var momentProperties = hooks.momentProperties = [];
  11550. function copyConfig(to, from) {
  11551. var i, prop, val;
  11552. if (!isUndefined(from._isAMomentObject)) {
  11553. to._isAMomentObject = from._isAMomentObject;
  11554. }
  11555. if (!isUndefined(from._i)) {
  11556. to._i = from._i;
  11557. }
  11558. if (!isUndefined(from._f)) {
  11559. to._f = from._f;
  11560. }
  11561. if (!isUndefined(from._l)) {
  11562. to._l = from._l;
  11563. }
  11564. if (!isUndefined(from._strict)) {
  11565. to._strict = from._strict;
  11566. }
  11567. if (!isUndefined(from._tzm)) {
  11568. to._tzm = from._tzm;
  11569. }
  11570. if (!isUndefined(from._isUTC)) {
  11571. to._isUTC = from._isUTC;
  11572. }
  11573. if (!isUndefined(from._offset)) {
  11574. to._offset = from._offset;
  11575. }
  11576. if (!isUndefined(from._pf)) {
  11577. to._pf = getParsingFlags(from);
  11578. }
  11579. if (!isUndefined(from._locale)) {
  11580. to._locale = from._locale;
  11581. }
  11582. if (momentProperties.length > 0) {
  11583. for (i = 0; i < momentProperties.length; i++) {
  11584. prop = momentProperties[i];
  11585. val = from[prop];
  11586. if (!isUndefined(val)) {
  11587. to[prop] = val;
  11588. }
  11589. }
  11590. }
  11591. return to;
  11592. }
  11593. var updateInProgress = false;
  11594. // Moment prototype object
  11595. function Moment(config) {
  11596. copyConfig(this, config);
  11597. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  11598. if (!this.isValid()) {
  11599. this._d = new Date(NaN);
  11600. }
  11601. // Prevent infinite loop in case updateOffset creates new moment
  11602. // objects.
  11603. if (updateInProgress === false) {
  11604. updateInProgress = true;
  11605. hooks.updateOffset(this);
  11606. updateInProgress = false;
  11607. }
  11608. }
  11609. function isMoment (obj) {
  11610. return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
  11611. }
  11612. function absFloor (number) {
  11613. if (number < 0) {
  11614. // -0 -> 0
  11615. return Math.ceil(number) || 0;
  11616. } else {
  11617. return Math.floor(number);
  11618. }
  11619. }
  11620. function toInt(argumentForCoercion) {
  11621. var coercedNumber = +argumentForCoercion,
  11622. value = 0;
  11623. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  11624. value = absFloor(coercedNumber);
  11625. }
  11626. return value;
  11627. }
  11628. // compare two arrays, return the number of differences
  11629. function compareArrays(array1, array2, dontConvert) {
  11630. var len = Math.min(array1.length, array2.length),
  11631. lengthDiff = Math.abs(array1.length - array2.length),
  11632. diffs = 0,
  11633. i;
  11634. for (i = 0; i < len; i++) {
  11635. if ((dontConvert && array1[i] !== array2[i]) ||
  11636. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  11637. diffs++;
  11638. }
  11639. }
  11640. return diffs + lengthDiff;
  11641. }
  11642. function warn(msg) {
  11643. if (hooks.suppressDeprecationWarnings === false &&
  11644. (typeof console !== 'undefined') && console.warn) {
  11645. console.warn('Deprecation warning: ' + msg);
  11646. }
  11647. }
  11648. function deprecate(msg, fn) {
  11649. var firstTime = true;
  11650. return extend(function () {
  11651. if (hooks.deprecationHandler != null) {
  11652. hooks.deprecationHandler(null, msg);
  11653. }
  11654. if (firstTime) {
  11655. var args = [];
  11656. var arg;
  11657. for (var i = 0; i < arguments.length; i++) {
  11658. arg = '';
  11659. if (typeof arguments[i] === 'object') {
  11660. arg += '\n[' + i + '] ';
  11661. for (var key in arguments[0]) {
  11662. arg += key + ': ' + arguments[0][key] + ', ';
  11663. }
  11664. arg = arg.slice(0, -2); // Remove trailing comma and space
  11665. } else {
  11666. arg = arguments[i];
  11667. }
  11668. args.push(arg);
  11669. }
  11670. warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
  11671. firstTime = false;
  11672. }
  11673. return fn.apply(this, arguments);
  11674. }, fn);
  11675. }
  11676. var deprecations = {};
  11677. function deprecateSimple(name, msg) {
  11678. if (hooks.deprecationHandler != null) {
  11679. hooks.deprecationHandler(name, msg);
  11680. }
  11681. if (!deprecations[name]) {
  11682. warn(msg);
  11683. deprecations[name] = true;
  11684. }
  11685. }
  11686. hooks.suppressDeprecationWarnings = false;
  11687. hooks.deprecationHandler = null;
  11688. function isFunction(input) {
  11689. return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
  11690. }
  11691. function set (config) {
  11692. var prop, i;
  11693. for (i in config) {
  11694. prop = config[i];
  11695. if (isFunction(prop)) {
  11696. this[i] = prop;
  11697. } else {
  11698. this['_' + i] = prop;
  11699. }
  11700. }
  11701. this._config = config;
  11702. // Lenient ordinal parsing accepts just a number in addition to
  11703. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  11704. // TODO: Remove "ordinalParse" fallback in next major release.
  11705. this._dayOfMonthOrdinalParseLenient = new RegExp(
  11706. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  11707. '|' + (/\d{1,2}/).source);
  11708. }
  11709. function mergeConfigs(parentConfig, childConfig) {
  11710. var res = extend({}, parentConfig), prop;
  11711. for (prop in childConfig) {
  11712. if (hasOwnProp(childConfig, prop)) {
  11713. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  11714. res[prop] = {};
  11715. extend(res[prop], parentConfig[prop]);
  11716. extend(res[prop], childConfig[prop]);
  11717. } else if (childConfig[prop] != null) {
  11718. res[prop] = childConfig[prop];
  11719. } else {
  11720. delete res[prop];
  11721. }
  11722. }
  11723. }
  11724. for (prop in parentConfig) {
  11725. if (hasOwnProp(parentConfig, prop) &&
  11726. !hasOwnProp(childConfig, prop) &&
  11727. isObject(parentConfig[prop])) {
  11728. // make sure changes to properties don't modify parent config
  11729. res[prop] = extend({}, res[prop]);
  11730. }
  11731. }
  11732. return res;
  11733. }
  11734. function Locale(config) {
  11735. if (config != null) {
  11736. this.set(config);
  11737. }
  11738. }
  11739. var keys;
  11740. if (Object.keys) {
  11741. keys = Object.keys;
  11742. } else {
  11743. keys = function (obj) {
  11744. var i, res = [];
  11745. for (i in obj) {
  11746. if (hasOwnProp(obj, i)) {
  11747. res.push(i);
  11748. }
  11749. }
  11750. return res;
  11751. };
  11752. }
  11753. var defaultCalendar = {
  11754. sameDay : '[Today at] LT',
  11755. nextDay : '[Tomorrow at] LT',
  11756. nextWeek : 'dddd [at] LT',
  11757. lastDay : '[Yesterday at] LT',
  11758. lastWeek : '[Last] dddd [at] LT',
  11759. sameElse : 'L'
  11760. };
  11761. function calendar (key, mom, now) {
  11762. var output = this._calendar[key] || this._calendar['sameElse'];
  11763. return isFunction(output) ? output.call(mom, now) : output;
  11764. }
  11765. var defaultLongDateFormat = {
  11766. LTS : 'h:mm:ss A',
  11767. LT : 'h:mm A',
  11768. L : 'MM/DD/YYYY',
  11769. LL : 'MMMM D, YYYY',
  11770. LLL : 'MMMM D, YYYY h:mm A',
  11771. LLLL : 'dddd, MMMM D, YYYY h:mm A'
  11772. };
  11773. function longDateFormat (key) {
  11774. var format = this._longDateFormat[key],
  11775. formatUpper = this._longDateFormat[key.toUpperCase()];
  11776. if (format || !formatUpper) {
  11777. return format;
  11778. }
  11779. this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
  11780. return val.slice(1);
  11781. });
  11782. return this._longDateFormat[key];
  11783. }
  11784. var defaultInvalidDate = 'Invalid date';
  11785. function invalidDate () {
  11786. return this._invalidDate;
  11787. }
  11788. var defaultOrdinal = '%d';
  11789. var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  11790. function ordinal (number) {
  11791. return this._ordinal.replace('%d', number);
  11792. }
  11793. var defaultRelativeTime = {
  11794. future : 'in %s',
  11795. past : '%s ago',
  11796. s : 'a few seconds',
  11797. ss : '%d seconds',
  11798. m : 'a minute',
  11799. mm : '%d minutes',
  11800. h : 'an hour',
  11801. hh : '%d hours',
  11802. d : 'a day',
  11803. dd : '%d days',
  11804. M : 'a month',
  11805. MM : '%d months',
  11806. y : 'a year',
  11807. yy : '%d years'
  11808. };
  11809. function relativeTime (number, withoutSuffix, string, isFuture) {
  11810. var output = this._relativeTime[string];
  11811. return (isFunction(output)) ?
  11812. output(number, withoutSuffix, string, isFuture) :
  11813. output.replace(/%d/i, number);
  11814. }
  11815. function pastFuture (diff, output) {
  11816. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  11817. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  11818. }
  11819. var aliases = {};
  11820. function addUnitAlias (unit, shorthand) {
  11821. var lowerCase = unit.toLowerCase();
  11822. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  11823. }
  11824. function normalizeUnits(units) {
  11825. return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
  11826. }
  11827. function normalizeObjectUnits(inputObject) {
  11828. var normalizedInput = {},
  11829. normalizedProp,
  11830. prop;
  11831. for (prop in inputObject) {
  11832. if (hasOwnProp(inputObject, prop)) {
  11833. normalizedProp = normalizeUnits(prop);
  11834. if (normalizedProp) {
  11835. normalizedInput[normalizedProp] = inputObject[prop];
  11836. }
  11837. }
  11838. }
  11839. return normalizedInput;
  11840. }
  11841. var priorities = {};
  11842. function addUnitPriority(unit, priority) {
  11843. priorities[unit] = priority;
  11844. }
  11845. function getPrioritizedUnits(unitsObj) {
  11846. var units = [];
  11847. for (var u in unitsObj) {
  11848. units.push({unit: u, priority: priorities[u]});
  11849. }
  11850. units.sort(function (a, b) {
  11851. return a.priority - b.priority;
  11852. });
  11853. return units;
  11854. }
  11855. function zeroFill(number, targetLength, forceSign) {
  11856. var absNumber = '' + Math.abs(number),
  11857. zerosToFill = targetLength - absNumber.length,
  11858. sign = number >= 0;
  11859. return (sign ? (forceSign ? '+' : '') : '-') +
  11860. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
  11861. }
  11862. var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
  11863. var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  11864. var formatFunctions = {};
  11865. var formatTokenFunctions = {};
  11866. // token: 'M'
  11867. // padded: ['MM', 2]
  11868. // ordinal: 'Mo'
  11869. // callback: function () { this.month() + 1 }
  11870. function addFormatToken (token, padded, ordinal, callback) {
  11871. var func = callback;
  11872. if (typeof callback === 'string') {
  11873. func = function () {
  11874. return this[callback]();
  11875. };
  11876. }
  11877. if (token) {
  11878. formatTokenFunctions[token] = func;
  11879. }
  11880. if (padded) {
  11881. formatTokenFunctions[padded[0]] = function () {
  11882. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  11883. };
  11884. }
  11885. if (ordinal) {
  11886. formatTokenFunctions[ordinal] = function () {
  11887. return this.localeData().ordinal(func.apply(this, arguments), token);
  11888. };
  11889. }
  11890. }
  11891. function removeFormattingTokens(input) {
  11892. if (input.match(/\[[\s\S]/)) {
  11893. return input.replace(/^\[|\]$/g, '');
  11894. }
  11895. return input.replace(/\\/g, '');
  11896. }
  11897. function makeFormatFunction(format) {
  11898. var array = format.match(formattingTokens), i, length;
  11899. for (i = 0, length = array.length; i < length; i++) {
  11900. if (formatTokenFunctions[array[i]]) {
  11901. array[i] = formatTokenFunctions[array[i]];
  11902. } else {
  11903. array[i] = removeFormattingTokens(array[i]);
  11904. }
  11905. }
  11906. return function (mom) {
  11907. var output = '', i;
  11908. for (i = 0; i < length; i++) {
  11909. output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
  11910. }
  11911. return output;
  11912. };
  11913. }
  11914. // format date using native date object
  11915. function formatMoment(m, format) {
  11916. if (!m.isValid()) {
  11917. return m.localeData().invalidDate();
  11918. }
  11919. format = expandFormat(format, m.localeData());
  11920. formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
  11921. return formatFunctions[format](m);
  11922. }
  11923. function expandFormat(format, locale) {
  11924. var i = 5;
  11925. function replaceLongDateFormatTokens(input) {
  11926. return locale.longDateFormat(input) || input;
  11927. }
  11928. localFormattingTokens.lastIndex = 0;
  11929. while (i >= 0 && localFormattingTokens.test(format)) {
  11930. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  11931. localFormattingTokens.lastIndex = 0;
  11932. i -= 1;
  11933. }
  11934. return format;
  11935. }
  11936. var match1 = /\d/; // 0 - 9
  11937. var match2 = /\d\d/; // 00 - 99
  11938. var match3 = /\d{3}/; // 000 - 999
  11939. var match4 = /\d{4}/; // 0000 - 9999
  11940. var match6 = /[+-]?\d{6}/; // -999999 - 999999
  11941. var match1to2 = /\d\d?/; // 0 - 99
  11942. var match3to4 = /\d\d\d\d?/; // 999 - 9999
  11943. var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
  11944. var match1to3 = /\d{1,3}/; // 0 - 999
  11945. var match1to4 = /\d{1,4}/; // 0 - 9999
  11946. var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
  11947. var matchUnsigned = /\d+/; // 0 - inf
  11948. var matchSigned = /[+-]?\d+/; // -inf - inf
  11949. var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
  11950. var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  11951. var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
  11952. // any word (or two) characters or numbers including two/three word month in arabic.
  11953. // includes scottish gaelic two word and hyphenated months
  11954. var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
  11955. var regexes = {};
  11956. function addRegexToken (token, regex, strictRegex) {
  11957. regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
  11958. return (isStrict && strictRegex) ? strictRegex : regex;
  11959. };
  11960. }
  11961. function getParseRegexForToken (token, config) {
  11962. if (!hasOwnProp(regexes, token)) {
  11963. return new RegExp(unescapeFormat(token));
  11964. }
  11965. return regexes[token](config._strict, config._locale);
  11966. }
  11967. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  11968. function unescapeFormat(s) {
  11969. return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  11970. return p1 || p2 || p3 || p4;
  11971. }));
  11972. }
  11973. function regexEscape(s) {
  11974. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  11975. }
  11976. var tokens = {};
  11977. function addParseToken (token, callback) {
  11978. var i, func = callback;
  11979. if (typeof token === 'string') {
  11980. token = [token];
  11981. }
  11982. if (isNumber(callback)) {
  11983. func = function (input, array) {
  11984. array[callback] = toInt(input);
  11985. };
  11986. }
  11987. for (i = 0; i < token.length; i++) {
  11988. tokens[token[i]] = func;
  11989. }
  11990. }
  11991. function addWeekParseToken (token, callback) {
  11992. addParseToken(token, function (input, array, config, token) {
  11993. config._w = config._w || {};
  11994. callback(input, config._w, config, token);
  11995. });
  11996. }
  11997. function addTimeToArrayFromToken(token, input, config) {
  11998. if (input != null && hasOwnProp(tokens, token)) {
  11999. tokens[token](input, config._a, config, token);
  12000. }
  12001. }
  12002. var YEAR = 0;
  12003. var MONTH = 1;
  12004. var DATE = 2;
  12005. var HOUR = 3;
  12006. var MINUTE = 4;
  12007. var SECOND = 5;
  12008. var MILLISECOND = 6;
  12009. var WEEK = 7;
  12010. var WEEKDAY = 8;
  12011. // FORMATTING
  12012. addFormatToken('Y', 0, 0, function () {
  12013. var y = this.year();
  12014. return y <= 9999 ? '' + y : '+' + y;
  12015. });
  12016. addFormatToken(0, ['YY', 2], 0, function () {
  12017. return this.year() % 100;
  12018. });
  12019. addFormatToken(0, ['YYYY', 4], 0, 'year');
  12020. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  12021. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  12022. // ALIASES
  12023. addUnitAlias('year', 'y');
  12024. // PRIORITIES
  12025. addUnitPriority('year', 1);
  12026. // PARSING
  12027. addRegexToken('Y', matchSigned);
  12028. addRegexToken('YY', match1to2, match2);
  12029. addRegexToken('YYYY', match1to4, match4);
  12030. addRegexToken('YYYYY', match1to6, match6);
  12031. addRegexToken('YYYYYY', match1to6, match6);
  12032. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  12033. addParseToken('YYYY', function (input, array) {
  12034. array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  12035. });
  12036. addParseToken('YY', function (input, array) {
  12037. array[YEAR] = hooks.parseTwoDigitYear(input);
  12038. });
  12039. addParseToken('Y', function (input, array) {
  12040. array[YEAR] = parseInt(input, 10);
  12041. });
  12042. // HELPERS
  12043. function daysInYear(year) {
  12044. return isLeapYear(year) ? 366 : 365;
  12045. }
  12046. function isLeapYear(year) {
  12047. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  12048. }
  12049. // HOOKS
  12050. hooks.parseTwoDigitYear = function (input) {
  12051. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  12052. };
  12053. // MOMENTS
  12054. var getSetYear = makeGetSet('FullYear', true);
  12055. function getIsLeapYear () {
  12056. return isLeapYear(this.year());
  12057. }
  12058. function makeGetSet (unit, keepTime) {
  12059. return function (value) {
  12060. if (value != null) {
  12061. set$1(this, unit, value);
  12062. hooks.updateOffset(this, keepTime);
  12063. return this;
  12064. } else {
  12065. return get(this, unit);
  12066. }
  12067. };
  12068. }
  12069. function get (mom, unit) {
  12070. return mom.isValid() ?
  12071. mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
  12072. }
  12073. function set$1 (mom, unit, value) {
  12074. if (mom.isValid() && !isNaN(value)) {
  12075. if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
  12076. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
  12077. }
  12078. else {
  12079. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  12080. }
  12081. }
  12082. }
  12083. // MOMENTS
  12084. function stringGet (units) {
  12085. units = normalizeUnits(units);
  12086. if (isFunction(this[units])) {
  12087. return this[units]();
  12088. }
  12089. return this;
  12090. }
  12091. function stringSet (units, value) {
  12092. if (typeof units === 'object') {
  12093. units = normalizeObjectUnits(units);
  12094. var prioritized = getPrioritizedUnits(units);
  12095. for (var i = 0; i < prioritized.length; i++) {
  12096. this[prioritized[i].unit](units[prioritized[i].unit]);
  12097. }
  12098. } else {
  12099. units = normalizeUnits(units);
  12100. if (isFunction(this[units])) {
  12101. return this[units](value);
  12102. }
  12103. }
  12104. return this;
  12105. }
  12106. function mod(n, x) {
  12107. return ((n % x) + x) % x;
  12108. }
  12109. var indexOf;
  12110. if (Array.prototype.indexOf) {
  12111. indexOf = Array.prototype.indexOf;
  12112. } else {
  12113. indexOf = function (o) {
  12114. // I know
  12115. var i;
  12116. for (i = 0; i < this.length; ++i) {
  12117. if (this[i] === o) {
  12118. return i;
  12119. }
  12120. }
  12121. return -1;
  12122. };
  12123. }
  12124. function daysInMonth(year, month) {
  12125. if (isNaN(year) || isNaN(month)) {
  12126. return NaN;
  12127. }
  12128. var modMonth = mod(month, 12);
  12129. year += (month - modMonth) / 12;
  12130. return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
  12131. }
  12132. // FORMATTING
  12133. addFormatToken('M', ['MM', 2], 'Mo', function () {
  12134. return this.month() + 1;
  12135. });
  12136. addFormatToken('MMM', 0, 0, function (format) {
  12137. return this.localeData().monthsShort(this, format);
  12138. });
  12139. addFormatToken('MMMM', 0, 0, function (format) {
  12140. return this.localeData().months(this, format);
  12141. });
  12142. // ALIASES
  12143. addUnitAlias('month', 'M');
  12144. // PRIORITY
  12145. addUnitPriority('month', 8);
  12146. // PARSING
  12147. addRegexToken('M', match1to2);
  12148. addRegexToken('MM', match1to2, match2);
  12149. addRegexToken('MMM', function (isStrict, locale) {
  12150. return locale.monthsShortRegex(isStrict);
  12151. });
  12152. addRegexToken('MMMM', function (isStrict, locale) {
  12153. return locale.monthsRegex(isStrict);
  12154. });
  12155. addParseToken(['M', 'MM'], function (input, array) {
  12156. array[MONTH] = toInt(input) - 1;
  12157. });
  12158. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  12159. var month = config._locale.monthsParse(input, token, config._strict);
  12160. // if we didn't find a month name, mark the date as invalid.
  12161. if (month != null) {
  12162. array[MONTH] = month;
  12163. } else {
  12164. getParsingFlags(config).invalidMonth = input;
  12165. }
  12166. });
  12167. // LOCALES
  12168. var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
  12169. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
  12170. function localeMonths (m, format) {
  12171. if (!m) {
  12172. return isArray(this._months) ? this._months :
  12173. this._months['standalone'];
  12174. }
  12175. return isArray(this._months) ? this._months[m.month()] :
  12176. this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
  12177. }
  12178. var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
  12179. function localeMonthsShort (m, format) {
  12180. if (!m) {
  12181. return isArray(this._monthsShort) ? this._monthsShort :
  12182. this._monthsShort['standalone'];
  12183. }
  12184. return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
  12185. this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
  12186. }
  12187. function handleStrictParse(monthName, format, strict) {
  12188. var i, ii, mom, llc = monthName.toLocaleLowerCase();
  12189. if (!this._monthsParse) {
  12190. // this is not used
  12191. this._monthsParse = [];
  12192. this._longMonthsParse = [];
  12193. this._shortMonthsParse = [];
  12194. for (i = 0; i < 12; ++i) {
  12195. mom = createUTC([2000, i]);
  12196. this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
  12197. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  12198. }
  12199. }
  12200. if (strict) {
  12201. if (format === 'MMM') {
  12202. ii = indexOf.call(this._shortMonthsParse, llc);
  12203. return ii !== -1 ? ii : null;
  12204. } else {
  12205. ii = indexOf.call(this._longMonthsParse, llc);
  12206. return ii !== -1 ? ii : null;
  12207. }
  12208. } else {
  12209. if (format === 'MMM') {
  12210. ii = indexOf.call(this._shortMonthsParse, llc);
  12211. if (ii !== -1) {
  12212. return ii;
  12213. }
  12214. ii = indexOf.call(this._longMonthsParse, llc);
  12215. return ii !== -1 ? ii : null;
  12216. } else {
  12217. ii = indexOf.call(this._longMonthsParse, llc);
  12218. if (ii !== -1) {
  12219. return ii;
  12220. }
  12221. ii = indexOf.call(this._shortMonthsParse, llc);
  12222. return ii !== -1 ? ii : null;
  12223. }
  12224. }
  12225. }
  12226. function localeMonthsParse (monthName, format, strict) {
  12227. var i, mom, regex;
  12228. if (this._monthsParseExact) {
  12229. return handleStrictParse.call(this, monthName, format, strict);
  12230. }
  12231. if (!this._monthsParse) {
  12232. this._monthsParse = [];
  12233. this._longMonthsParse = [];
  12234. this._shortMonthsParse = [];
  12235. }
  12236. // TODO: add sorting
  12237. // Sorting makes sure if one month (or abbr) is a prefix of another
  12238. // see sorting in computeMonthsParse
  12239. for (i = 0; i < 12; i++) {
  12240. // make the regex if we don't have it already
  12241. mom = createUTC([2000, i]);
  12242. if (strict && !this._longMonthsParse[i]) {
  12243. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  12244. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  12245. }
  12246. if (!strict && !this._monthsParse[i]) {
  12247. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  12248. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  12249. }
  12250. // test the regex
  12251. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  12252. return i;
  12253. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  12254. return i;
  12255. } else if (!strict && this._monthsParse[i].test(monthName)) {
  12256. return i;
  12257. }
  12258. }
  12259. }
  12260. // MOMENTS
  12261. function setMonth (mom, value) {
  12262. var dayOfMonth;
  12263. if (!mom.isValid()) {
  12264. // No op
  12265. return mom;
  12266. }
  12267. if (typeof value === 'string') {
  12268. if (/^\d+$/.test(value)) {
  12269. value = toInt(value);
  12270. } else {
  12271. value = mom.localeData().monthsParse(value);
  12272. // TODO: Another silent failure?
  12273. if (!isNumber(value)) {
  12274. return mom;
  12275. }
  12276. }
  12277. }
  12278. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  12279. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  12280. return mom;
  12281. }
  12282. function getSetMonth (value) {
  12283. if (value != null) {
  12284. setMonth(this, value);
  12285. hooks.updateOffset(this, true);
  12286. return this;
  12287. } else {
  12288. return get(this, 'Month');
  12289. }
  12290. }
  12291. function getDaysInMonth () {
  12292. return daysInMonth(this.year(), this.month());
  12293. }
  12294. var defaultMonthsShortRegex = matchWord;
  12295. function monthsShortRegex (isStrict) {
  12296. if (this._monthsParseExact) {
  12297. if (!hasOwnProp(this, '_monthsRegex')) {
  12298. computeMonthsParse.call(this);
  12299. }
  12300. if (isStrict) {
  12301. return this._monthsShortStrictRegex;
  12302. } else {
  12303. return this._monthsShortRegex;
  12304. }
  12305. } else {
  12306. if (!hasOwnProp(this, '_monthsShortRegex')) {
  12307. this._monthsShortRegex = defaultMonthsShortRegex;
  12308. }
  12309. return this._monthsShortStrictRegex && isStrict ?
  12310. this._monthsShortStrictRegex : this._monthsShortRegex;
  12311. }
  12312. }
  12313. var defaultMonthsRegex = matchWord;
  12314. function monthsRegex (isStrict) {
  12315. if (this._monthsParseExact) {
  12316. if (!hasOwnProp(this, '_monthsRegex')) {
  12317. computeMonthsParse.call(this);
  12318. }
  12319. if (isStrict) {
  12320. return this._monthsStrictRegex;
  12321. } else {
  12322. return this._monthsRegex;
  12323. }
  12324. } else {
  12325. if (!hasOwnProp(this, '_monthsRegex')) {
  12326. this._monthsRegex = defaultMonthsRegex;
  12327. }
  12328. return this._monthsStrictRegex && isStrict ?
  12329. this._monthsStrictRegex : this._monthsRegex;
  12330. }
  12331. }
  12332. function computeMonthsParse () {
  12333. function cmpLenRev(a, b) {
  12334. return b.length - a.length;
  12335. }
  12336. var shortPieces = [], longPieces = [], mixedPieces = [],
  12337. i, mom;
  12338. for (i = 0; i < 12; i++) {
  12339. // make the regex if we don't have it already
  12340. mom = createUTC([2000, i]);
  12341. shortPieces.push(this.monthsShort(mom, ''));
  12342. longPieces.push(this.months(mom, ''));
  12343. mixedPieces.push(this.months(mom, ''));
  12344. mixedPieces.push(this.monthsShort(mom, ''));
  12345. }
  12346. // Sorting makes sure if one month (or abbr) is a prefix of another it
  12347. // will match the longer piece.
  12348. shortPieces.sort(cmpLenRev);
  12349. longPieces.sort(cmpLenRev);
  12350. mixedPieces.sort(cmpLenRev);
  12351. for (i = 0; i < 12; i++) {
  12352. shortPieces[i] = regexEscape(shortPieces[i]);
  12353. longPieces[i] = regexEscape(longPieces[i]);
  12354. }
  12355. for (i = 0; i < 24; i++) {
  12356. mixedPieces[i] = regexEscape(mixedPieces[i]);
  12357. }
  12358. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  12359. this._monthsShortRegex = this._monthsRegex;
  12360. this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  12361. this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  12362. }
  12363. function createDate (y, m, d, h, M, s, ms) {
  12364. // can't just apply() to create a date:
  12365. // https://stackoverflow.com/q/181348
  12366. var date;
  12367. // the date constructor remaps years 0-99 to 1900-1999
  12368. if (y < 100 && y >= 0) {
  12369. // preserve leap years using a full 400 year cycle, then reset
  12370. date = new Date(y + 400, m, d, h, M, s, ms);
  12371. if (isFinite(date.getFullYear())) {
  12372. date.setFullYear(y);
  12373. }
  12374. } else {
  12375. date = new Date(y, m, d, h, M, s, ms);
  12376. }
  12377. return date;
  12378. }
  12379. function createUTCDate (y) {
  12380. var date;
  12381. // the Date.UTC function remaps years 0-99 to 1900-1999
  12382. if (y < 100 && y >= 0) {
  12383. var args = Array.prototype.slice.call(arguments);
  12384. // preserve leap years using a full 400 year cycle, then reset
  12385. args[0] = y + 400;
  12386. date = new Date(Date.UTC.apply(null, args));
  12387. if (isFinite(date.getUTCFullYear())) {
  12388. date.setUTCFullYear(y);
  12389. }
  12390. } else {
  12391. date = new Date(Date.UTC.apply(null, arguments));
  12392. }
  12393. return date;
  12394. }
  12395. // start-of-first-week - start-of-year
  12396. function firstWeekOffset(year, dow, doy) {
  12397. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  12398. fwd = 7 + dow - doy,
  12399. // first-week day local weekday -- which local weekday is fwd
  12400. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  12401. return -fwdlw + fwd - 1;
  12402. }
  12403. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  12404. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  12405. var localWeekday = (7 + weekday - dow) % 7,
  12406. weekOffset = firstWeekOffset(year, dow, doy),
  12407. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  12408. resYear, resDayOfYear;
  12409. if (dayOfYear <= 0) {
  12410. resYear = year - 1;
  12411. resDayOfYear = daysInYear(resYear) + dayOfYear;
  12412. } else if (dayOfYear > daysInYear(year)) {
  12413. resYear = year + 1;
  12414. resDayOfYear = dayOfYear - daysInYear(year);
  12415. } else {
  12416. resYear = year;
  12417. resDayOfYear = dayOfYear;
  12418. }
  12419. return {
  12420. year: resYear,
  12421. dayOfYear: resDayOfYear
  12422. };
  12423. }
  12424. function weekOfYear(mom, dow, doy) {
  12425. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  12426. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  12427. resWeek, resYear;
  12428. if (week < 1) {
  12429. resYear = mom.year() - 1;
  12430. resWeek = week + weeksInYear(resYear, dow, doy);
  12431. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  12432. resWeek = week - weeksInYear(mom.year(), dow, doy);
  12433. resYear = mom.year() + 1;
  12434. } else {
  12435. resYear = mom.year();
  12436. resWeek = week;
  12437. }
  12438. return {
  12439. week: resWeek,
  12440. year: resYear
  12441. };
  12442. }
  12443. function weeksInYear(year, dow, doy) {
  12444. var weekOffset = firstWeekOffset(year, dow, doy),
  12445. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  12446. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  12447. }
  12448. // FORMATTING
  12449. addFormatToken('w', ['ww', 2], 'wo', 'week');
  12450. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  12451. // ALIASES
  12452. addUnitAlias('week', 'w');
  12453. addUnitAlias('isoWeek', 'W');
  12454. // PRIORITIES
  12455. addUnitPriority('week', 5);
  12456. addUnitPriority('isoWeek', 5);
  12457. // PARSING
  12458. addRegexToken('w', match1to2);
  12459. addRegexToken('ww', match1to2, match2);
  12460. addRegexToken('W', match1to2);
  12461. addRegexToken('WW', match1to2, match2);
  12462. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
  12463. week[token.substr(0, 1)] = toInt(input);
  12464. });
  12465. // HELPERS
  12466. // LOCALES
  12467. function localeWeek (mom) {
  12468. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  12469. }
  12470. var defaultLocaleWeek = {
  12471. dow : 0, // Sunday is the first day of the week.
  12472. doy : 6 // The week that contains Jan 6th is the first week of the year.
  12473. };
  12474. function localeFirstDayOfWeek () {
  12475. return this._week.dow;
  12476. }
  12477. function localeFirstDayOfYear () {
  12478. return this._week.doy;
  12479. }
  12480. // MOMENTS
  12481. function getSetWeek (input) {
  12482. var week = this.localeData().week(this);
  12483. return input == null ? week : this.add((input - week) * 7, 'd');
  12484. }
  12485. function getSetISOWeek (input) {
  12486. var week = weekOfYear(this, 1, 4).week;
  12487. return input == null ? week : this.add((input - week) * 7, 'd');
  12488. }
  12489. // FORMATTING
  12490. addFormatToken('d', 0, 'do', 'day');
  12491. addFormatToken('dd', 0, 0, function (format) {
  12492. return this.localeData().weekdaysMin(this, format);
  12493. });
  12494. addFormatToken('ddd', 0, 0, function (format) {
  12495. return this.localeData().weekdaysShort(this, format);
  12496. });
  12497. addFormatToken('dddd', 0, 0, function (format) {
  12498. return this.localeData().weekdays(this, format);
  12499. });
  12500. addFormatToken('e', 0, 0, 'weekday');
  12501. addFormatToken('E', 0, 0, 'isoWeekday');
  12502. // ALIASES
  12503. addUnitAlias('day', 'd');
  12504. addUnitAlias('weekday', 'e');
  12505. addUnitAlias('isoWeekday', 'E');
  12506. // PRIORITY
  12507. addUnitPriority('day', 11);
  12508. addUnitPriority('weekday', 11);
  12509. addUnitPriority('isoWeekday', 11);
  12510. // PARSING
  12511. addRegexToken('d', match1to2);
  12512. addRegexToken('e', match1to2);
  12513. addRegexToken('E', match1to2);
  12514. addRegexToken('dd', function (isStrict, locale) {
  12515. return locale.weekdaysMinRegex(isStrict);
  12516. });
  12517. addRegexToken('ddd', function (isStrict, locale) {
  12518. return locale.weekdaysShortRegex(isStrict);
  12519. });
  12520. addRegexToken('dddd', function (isStrict, locale) {
  12521. return locale.weekdaysRegex(isStrict);
  12522. });
  12523. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  12524. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  12525. // if we didn't get a weekday name, mark the date as invalid
  12526. if (weekday != null) {
  12527. week.d = weekday;
  12528. } else {
  12529. getParsingFlags(config).invalidWeekday = input;
  12530. }
  12531. });
  12532. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  12533. week[token] = toInt(input);
  12534. });
  12535. // HELPERS
  12536. function parseWeekday(input, locale) {
  12537. if (typeof input !== 'string') {
  12538. return input;
  12539. }
  12540. if (!isNaN(input)) {
  12541. return parseInt(input, 10);
  12542. }
  12543. input = locale.weekdaysParse(input);
  12544. if (typeof input === 'number') {
  12545. return input;
  12546. }
  12547. return null;
  12548. }
  12549. function parseIsoWeekday(input, locale) {
  12550. if (typeof input === 'string') {
  12551. return locale.weekdaysParse(input) % 7 || 7;
  12552. }
  12553. return isNaN(input) ? null : input;
  12554. }
  12555. // LOCALES
  12556. function shiftWeekdays (ws, n) {
  12557. return ws.slice(n, 7).concat(ws.slice(0, n));
  12558. }
  12559. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
  12560. function localeWeekdays (m, format) {
  12561. var weekdays = isArray(this._weekdays) ? this._weekdays :
  12562. this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone'];
  12563. return (m === true) ? shiftWeekdays(weekdays, this._week.dow)
  12564. : (m) ? weekdays[m.day()] : weekdays;
  12565. }
  12566. var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
  12567. function localeWeekdaysShort (m) {
  12568. return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  12569. : (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
  12570. }
  12571. var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
  12572. function localeWeekdaysMin (m) {
  12573. return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  12574. : (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
  12575. }
  12576. function handleStrictParse$1(weekdayName, format, strict) {
  12577. var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
  12578. if (!this._weekdaysParse) {
  12579. this._weekdaysParse = [];
  12580. this._shortWeekdaysParse = [];
  12581. this._minWeekdaysParse = [];
  12582. for (i = 0; i < 7; ++i) {
  12583. mom = createUTC([2000, 1]).day(i);
  12584. this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
  12585. this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
  12586. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  12587. }
  12588. }
  12589. if (strict) {
  12590. if (format === 'dddd') {
  12591. ii = indexOf.call(this._weekdaysParse, llc);
  12592. return ii !== -1 ? ii : null;
  12593. } else if (format === 'ddd') {
  12594. ii = indexOf.call(this._shortWeekdaysParse, llc);
  12595. return ii !== -1 ? ii : null;
  12596. } else {
  12597. ii = indexOf.call(this._minWeekdaysParse, llc);
  12598. return ii !== -1 ? ii : null;
  12599. }
  12600. } else {
  12601. if (format === 'dddd') {
  12602. ii = indexOf.call(this._weekdaysParse, llc);
  12603. if (ii !== -1) {
  12604. return ii;
  12605. }
  12606. ii = indexOf.call(this._shortWeekdaysParse, llc);
  12607. if (ii !== -1) {
  12608. return ii;
  12609. }
  12610. ii = indexOf.call(this._minWeekdaysParse, llc);
  12611. return ii !== -1 ? ii : null;
  12612. } else if (format === 'ddd') {
  12613. ii = indexOf.call(this._shortWeekdaysParse, llc);
  12614. if (ii !== -1) {
  12615. return ii;
  12616. }
  12617. ii = indexOf.call(this._weekdaysParse, llc);
  12618. if (ii !== -1) {
  12619. return ii;
  12620. }
  12621. ii = indexOf.call(this._minWeekdaysParse, llc);
  12622. return ii !== -1 ? ii : null;
  12623. } else {
  12624. ii = indexOf.call(this._minWeekdaysParse, llc);
  12625. if (ii !== -1) {
  12626. return ii;
  12627. }
  12628. ii = indexOf.call(this._weekdaysParse, llc);
  12629. if (ii !== -1) {
  12630. return ii;
  12631. }
  12632. ii = indexOf.call(this._shortWeekdaysParse, llc);
  12633. return ii !== -1 ? ii : null;
  12634. }
  12635. }
  12636. }
  12637. function localeWeekdaysParse (weekdayName, format, strict) {
  12638. var i, mom, regex;
  12639. if (this._weekdaysParseExact) {
  12640. return handleStrictParse$1.call(this, weekdayName, format, strict);
  12641. }
  12642. if (!this._weekdaysParse) {
  12643. this._weekdaysParse = [];
  12644. this._minWeekdaysParse = [];
  12645. this._shortWeekdaysParse = [];
  12646. this._fullWeekdaysParse = [];
  12647. }
  12648. for (i = 0; i < 7; i++) {
  12649. // make the regex if we don't have it already
  12650. mom = createUTC([2000, 1]).day(i);
  12651. if (strict && !this._fullWeekdaysParse[i]) {
  12652. this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
  12653. this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
  12654. this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
  12655. }
  12656. if (!this._weekdaysParse[i]) {
  12657. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  12658. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  12659. }
  12660. // test the regex
  12661. if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
  12662. return i;
  12663. } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
  12664. return i;
  12665. } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
  12666. return i;
  12667. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  12668. return i;
  12669. }
  12670. }
  12671. }
  12672. // MOMENTS
  12673. function getSetDayOfWeek (input) {
  12674. if (!this.isValid()) {
  12675. return input != null ? this : NaN;
  12676. }
  12677. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  12678. if (input != null) {
  12679. input = parseWeekday(input, this.localeData());
  12680. return this.add(input - day, 'd');
  12681. } else {
  12682. return day;
  12683. }
  12684. }
  12685. function getSetLocaleDayOfWeek (input) {
  12686. if (!this.isValid()) {
  12687. return input != null ? this : NaN;
  12688. }
  12689. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  12690. return input == null ? weekday : this.add(input - weekday, 'd');
  12691. }
  12692. function getSetISODayOfWeek (input) {
  12693. if (!this.isValid()) {
  12694. return input != null ? this : NaN;
  12695. }
  12696. // behaves the same as moment#day except
  12697. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  12698. // as a setter, sunday should belong to the previous week.
  12699. if (input != null) {
  12700. var weekday = parseIsoWeekday(input, this.localeData());
  12701. return this.day(this.day() % 7 ? weekday : weekday - 7);
  12702. } else {
  12703. return this.day() || 7;
  12704. }
  12705. }
  12706. var defaultWeekdaysRegex = matchWord;
  12707. function weekdaysRegex (isStrict) {
  12708. if (this._weekdaysParseExact) {
  12709. if (!hasOwnProp(this, '_weekdaysRegex')) {
  12710. computeWeekdaysParse.call(this);
  12711. }
  12712. if (isStrict) {
  12713. return this._weekdaysStrictRegex;
  12714. } else {
  12715. return this._weekdaysRegex;
  12716. }
  12717. } else {
  12718. if (!hasOwnProp(this, '_weekdaysRegex')) {
  12719. this._weekdaysRegex = defaultWeekdaysRegex;
  12720. }
  12721. return this._weekdaysStrictRegex && isStrict ?
  12722. this._weekdaysStrictRegex : this._weekdaysRegex;
  12723. }
  12724. }
  12725. var defaultWeekdaysShortRegex = matchWord;
  12726. function weekdaysShortRegex (isStrict) {
  12727. if (this._weekdaysParseExact) {
  12728. if (!hasOwnProp(this, '_weekdaysRegex')) {
  12729. computeWeekdaysParse.call(this);
  12730. }
  12731. if (isStrict) {
  12732. return this._weekdaysShortStrictRegex;
  12733. } else {
  12734. return this._weekdaysShortRegex;
  12735. }
  12736. } else {
  12737. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  12738. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  12739. }
  12740. return this._weekdaysShortStrictRegex && isStrict ?
  12741. this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
  12742. }
  12743. }
  12744. var defaultWeekdaysMinRegex = matchWord;
  12745. function weekdaysMinRegex (isStrict) {
  12746. if (this._weekdaysParseExact) {
  12747. if (!hasOwnProp(this, '_weekdaysRegex')) {
  12748. computeWeekdaysParse.call(this);
  12749. }
  12750. if (isStrict) {
  12751. return this._weekdaysMinStrictRegex;
  12752. } else {
  12753. return this._weekdaysMinRegex;
  12754. }
  12755. } else {
  12756. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  12757. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  12758. }
  12759. return this._weekdaysMinStrictRegex && isStrict ?
  12760. this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
  12761. }
  12762. }
  12763. function computeWeekdaysParse () {
  12764. function cmpLenRev(a, b) {
  12765. return b.length - a.length;
  12766. }
  12767. var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
  12768. i, mom, minp, shortp, longp;
  12769. for (i = 0; i < 7; i++) {
  12770. // make the regex if we don't have it already
  12771. mom = createUTC([2000, 1]).day(i);
  12772. minp = this.weekdaysMin(mom, '');
  12773. shortp = this.weekdaysShort(mom, '');
  12774. longp = this.weekdays(mom, '');
  12775. minPieces.push(minp);
  12776. shortPieces.push(shortp);
  12777. longPieces.push(longp);
  12778. mixedPieces.push(minp);
  12779. mixedPieces.push(shortp);
  12780. mixedPieces.push(longp);
  12781. }
  12782. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  12783. // will match the longer piece.
  12784. minPieces.sort(cmpLenRev);
  12785. shortPieces.sort(cmpLenRev);
  12786. longPieces.sort(cmpLenRev);
  12787. mixedPieces.sort(cmpLenRev);
  12788. for (i = 0; i < 7; i++) {
  12789. shortPieces[i] = regexEscape(shortPieces[i]);
  12790. longPieces[i] = regexEscape(longPieces[i]);
  12791. mixedPieces[i] = regexEscape(mixedPieces[i]);
  12792. }
  12793. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  12794. this._weekdaysShortRegex = this._weekdaysRegex;
  12795. this._weekdaysMinRegex = this._weekdaysRegex;
  12796. this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  12797. this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  12798. this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
  12799. }
  12800. // FORMATTING
  12801. function hFormat() {
  12802. return this.hours() % 12 || 12;
  12803. }
  12804. function kFormat() {
  12805. return this.hours() || 24;
  12806. }
  12807. addFormatToken('H', ['HH', 2], 0, 'hour');
  12808. addFormatToken('h', ['hh', 2], 0, hFormat);
  12809. addFormatToken('k', ['kk', 2], 0, kFormat);
  12810. addFormatToken('hmm', 0, 0, function () {
  12811. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  12812. });
  12813. addFormatToken('hmmss', 0, 0, function () {
  12814. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
  12815. zeroFill(this.seconds(), 2);
  12816. });
  12817. addFormatToken('Hmm', 0, 0, function () {
  12818. return '' + this.hours() + zeroFill(this.minutes(), 2);
  12819. });
  12820. addFormatToken('Hmmss', 0, 0, function () {
  12821. return '' + this.hours() + zeroFill(this.minutes(), 2) +
  12822. zeroFill(this.seconds(), 2);
  12823. });
  12824. function meridiem (token, lowercase) {
  12825. addFormatToken(token, 0, 0, function () {
  12826. return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
  12827. });
  12828. }
  12829. meridiem('a', true);
  12830. meridiem('A', false);
  12831. // ALIASES
  12832. addUnitAlias('hour', 'h');
  12833. // PRIORITY
  12834. addUnitPriority('hour', 13);
  12835. // PARSING
  12836. function matchMeridiem (isStrict, locale) {
  12837. return locale._meridiemParse;
  12838. }
  12839. addRegexToken('a', matchMeridiem);
  12840. addRegexToken('A', matchMeridiem);
  12841. addRegexToken('H', match1to2);
  12842. addRegexToken('h', match1to2);
  12843. addRegexToken('k', match1to2);
  12844. addRegexToken('HH', match1to2, match2);
  12845. addRegexToken('hh', match1to2, match2);
  12846. addRegexToken('kk', match1to2, match2);
  12847. addRegexToken('hmm', match3to4);
  12848. addRegexToken('hmmss', match5to6);
  12849. addRegexToken('Hmm', match3to4);
  12850. addRegexToken('Hmmss', match5to6);
  12851. addParseToken(['H', 'HH'], HOUR);
  12852. addParseToken(['k', 'kk'], function (input, array, config) {
  12853. var kInput = toInt(input);
  12854. array[HOUR] = kInput === 24 ? 0 : kInput;
  12855. });
  12856. addParseToken(['a', 'A'], function (input, array, config) {
  12857. config._isPm = config._locale.isPM(input);
  12858. config._meridiem = input;
  12859. });
  12860. addParseToken(['h', 'hh'], function (input, array, config) {
  12861. array[HOUR] = toInt(input);
  12862. getParsingFlags(config).bigHour = true;
  12863. });
  12864. addParseToken('hmm', function (input, array, config) {
  12865. var pos = input.length - 2;
  12866. array[HOUR] = toInt(input.substr(0, pos));
  12867. array[MINUTE] = toInt(input.substr(pos));
  12868. getParsingFlags(config).bigHour = true;
  12869. });
  12870. addParseToken('hmmss', function (input, array, config) {
  12871. var pos1 = input.length - 4;
  12872. var pos2 = input.length - 2;
  12873. array[HOUR] = toInt(input.substr(0, pos1));
  12874. array[MINUTE] = toInt(input.substr(pos1, 2));
  12875. array[SECOND] = toInt(input.substr(pos2));
  12876. getParsingFlags(config).bigHour = true;
  12877. });
  12878. addParseToken('Hmm', function (input, array, config) {
  12879. var pos = input.length - 2;
  12880. array[HOUR] = toInt(input.substr(0, pos));
  12881. array[MINUTE] = toInt(input.substr(pos));
  12882. });
  12883. addParseToken('Hmmss', function (input, array, config) {
  12884. var pos1 = input.length - 4;
  12885. var pos2 = input.length - 2;
  12886. array[HOUR] = toInt(input.substr(0, pos1));
  12887. array[MINUTE] = toInt(input.substr(pos1, 2));
  12888. array[SECOND] = toInt(input.substr(pos2));
  12889. });
  12890. // LOCALES
  12891. function localeIsPM (input) {
  12892. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  12893. // Using charAt should be more compatible.
  12894. return ((input + '').toLowerCase().charAt(0) === 'p');
  12895. }
  12896. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  12897. function localeMeridiem (hours, minutes, isLower) {
  12898. if (hours > 11) {
  12899. return isLower ? 'pm' : 'PM';
  12900. } else {
  12901. return isLower ? 'am' : 'AM';
  12902. }
  12903. }
  12904. // MOMENTS
  12905. // Setting the hour should keep the time, because the user explicitly
  12906. // specified which hour they want. So trying to maintain the same hour (in
  12907. // a new timezone) makes sense. Adding/subtracting hours does not follow
  12908. // this rule.
  12909. var getSetHour = makeGetSet('Hours', true);
  12910. var baseConfig = {
  12911. calendar: defaultCalendar,
  12912. longDateFormat: defaultLongDateFormat,
  12913. invalidDate: defaultInvalidDate,
  12914. ordinal: defaultOrdinal,
  12915. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  12916. relativeTime: defaultRelativeTime,
  12917. months: defaultLocaleMonths,
  12918. monthsShort: defaultLocaleMonthsShort,
  12919. week: defaultLocaleWeek,
  12920. weekdays: defaultLocaleWeekdays,
  12921. weekdaysMin: defaultLocaleWeekdaysMin,
  12922. weekdaysShort: defaultLocaleWeekdaysShort,
  12923. meridiemParse: defaultLocaleMeridiemParse
  12924. };
  12925. // internal storage for locale config files
  12926. var locales = {};
  12927. var localeFamilies = {};
  12928. var globalLocale;
  12929. function normalizeLocale(key) {
  12930. return key ? key.toLowerCase().replace('_', '-') : key;
  12931. }
  12932. // pick the locale from the array
  12933. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  12934. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  12935. function chooseLocale(names) {
  12936. var i = 0, j, next, locale, split;
  12937. while (i < names.length) {
  12938. split = normalizeLocale(names[i]).split('-');
  12939. j = split.length;
  12940. next = normalizeLocale(names[i + 1]);
  12941. next = next ? next.split('-') : null;
  12942. while (j > 0) {
  12943. locale = loadLocale(split.slice(0, j).join('-'));
  12944. if (locale) {
  12945. return locale;
  12946. }
  12947. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  12948. //the next array item is better than a shallower substring of this one
  12949. break;
  12950. }
  12951. j--;
  12952. }
  12953. i++;
  12954. }
  12955. return globalLocale;
  12956. }
  12957. function loadLocale(name) {
  12958. var oldLocale = null;
  12959. // TODO: Find a better way to register and load all the locales in Node
  12960. if (!locales[name] && ('object' !== 'undefined') &&
  12961. module && module.exports) {
  12962. try {
  12963. oldLocale = globalLocale._abbr;
  12964. var aliasedRequire = commonjsRequire;
  12965. aliasedRequire('./locale/' + name);
  12966. getSetGlobalLocale(oldLocale);
  12967. } catch (e) {}
  12968. }
  12969. return locales[name];
  12970. }
  12971. // This function will load locale and then set the global locale. If
  12972. // no arguments are passed in, it will simply return the current global
  12973. // locale key.
  12974. function getSetGlobalLocale (key, values) {
  12975. var data;
  12976. if (key) {
  12977. if (isUndefined(values)) {
  12978. data = getLocale(key);
  12979. }
  12980. else {
  12981. data = defineLocale(key, values);
  12982. }
  12983. if (data) {
  12984. // moment.duration._locale = moment._locale = data;
  12985. globalLocale = data;
  12986. }
  12987. else {
  12988. if ((typeof console !== 'undefined') && console.warn) {
  12989. //warn user if arguments are passed but the locale could not be set
  12990. console.warn('Locale ' + key + ' not found. Did you forget to load it?');
  12991. }
  12992. }
  12993. }
  12994. return globalLocale._abbr;
  12995. }
  12996. function defineLocale (name, config) {
  12997. if (config !== null) {
  12998. var locale, parentConfig = baseConfig;
  12999. config.abbr = name;
  13000. if (locales[name] != null) {
  13001. deprecateSimple('defineLocaleOverride',
  13002. 'use moment.updateLocale(localeName, config) to change ' +
  13003. 'an existing locale. moment.defineLocale(localeName, ' +
  13004. 'config) should only be used for creating a new locale ' +
  13005. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
  13006. parentConfig = locales[name]._config;
  13007. } else if (config.parentLocale != null) {
  13008. if (locales[config.parentLocale] != null) {
  13009. parentConfig = locales[config.parentLocale]._config;
  13010. } else {
  13011. locale = loadLocale(config.parentLocale);
  13012. if (locale != null) {
  13013. parentConfig = locale._config;
  13014. } else {
  13015. if (!localeFamilies[config.parentLocale]) {
  13016. localeFamilies[config.parentLocale] = [];
  13017. }
  13018. localeFamilies[config.parentLocale].push({
  13019. name: name,
  13020. config: config
  13021. });
  13022. return null;
  13023. }
  13024. }
  13025. }
  13026. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  13027. if (localeFamilies[name]) {
  13028. localeFamilies[name].forEach(function (x) {
  13029. defineLocale(x.name, x.config);
  13030. });
  13031. }
  13032. // backwards compat for now: also set the locale
  13033. // make sure we set the locale AFTER all child locales have been
  13034. // created, so we won't end up with the child locale set.
  13035. getSetGlobalLocale(name);
  13036. return locales[name];
  13037. } else {
  13038. // useful for testing
  13039. delete locales[name];
  13040. return null;
  13041. }
  13042. }
  13043. function updateLocale(name, config) {
  13044. if (config != null) {
  13045. var locale, tmpLocale, parentConfig = baseConfig;
  13046. // MERGE
  13047. tmpLocale = loadLocale(name);
  13048. if (tmpLocale != null) {
  13049. parentConfig = tmpLocale._config;
  13050. }
  13051. config = mergeConfigs(parentConfig, config);
  13052. locale = new Locale(config);
  13053. locale.parentLocale = locales[name];
  13054. locales[name] = locale;
  13055. // backwards compat for now: also set the locale
  13056. getSetGlobalLocale(name);
  13057. } else {
  13058. // pass null for config to unupdate, useful for tests
  13059. if (locales[name] != null) {
  13060. if (locales[name].parentLocale != null) {
  13061. locales[name] = locales[name].parentLocale;
  13062. } else if (locales[name] != null) {
  13063. delete locales[name];
  13064. }
  13065. }
  13066. }
  13067. return locales[name];
  13068. }
  13069. // returns locale data
  13070. function getLocale (key) {
  13071. var locale;
  13072. if (key && key._locale && key._locale._abbr) {
  13073. key = key._locale._abbr;
  13074. }
  13075. if (!key) {
  13076. return globalLocale;
  13077. }
  13078. if (!isArray(key)) {
  13079. //short-circuit everything else
  13080. locale = loadLocale(key);
  13081. if (locale) {
  13082. return locale;
  13083. }
  13084. key = [key];
  13085. }
  13086. return chooseLocale(key);
  13087. }
  13088. function listLocales() {
  13089. return keys(locales);
  13090. }
  13091. function checkOverflow (m) {
  13092. var overflow;
  13093. var a = m._a;
  13094. if (a && getParsingFlags(m).overflow === -2) {
  13095. overflow =
  13096. a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
  13097. a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
  13098. a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
  13099. a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
  13100. a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
  13101. a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
  13102. -1;
  13103. if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  13104. overflow = DATE;
  13105. }
  13106. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  13107. overflow = WEEK;
  13108. }
  13109. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  13110. overflow = WEEKDAY;
  13111. }
  13112. getParsingFlags(m).overflow = overflow;
  13113. }
  13114. return m;
  13115. }
  13116. // Pick the first defined of two or three arguments.
  13117. function defaults(a, b, c) {
  13118. if (a != null) {
  13119. return a;
  13120. }
  13121. if (b != null) {
  13122. return b;
  13123. }
  13124. return c;
  13125. }
  13126. function currentDateArray(config) {
  13127. // hooks is actually the exported moment object
  13128. var nowValue = new Date(hooks.now());
  13129. if (config._useUTC) {
  13130. return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
  13131. }
  13132. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  13133. }
  13134. // convert an array to a date.
  13135. // the array should mirror the parameters below
  13136. // note: all values past the year are optional and will default to the lowest possible value.
  13137. // [year, month, day , hour, minute, second, millisecond]
  13138. function configFromArray (config) {
  13139. var i, date, input = [], currentDate, expectedWeekday, yearToUse;
  13140. if (config._d) {
  13141. return;
  13142. }
  13143. currentDate = currentDateArray(config);
  13144. //compute day of the year from weeks and weekdays
  13145. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  13146. dayOfYearFromWeekInfo(config);
  13147. }
  13148. //if the day of the year is set, figure out what it is
  13149. if (config._dayOfYear != null) {
  13150. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  13151. if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
  13152. getParsingFlags(config)._overflowDayOfYear = true;
  13153. }
  13154. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  13155. config._a[MONTH] = date.getUTCMonth();
  13156. config._a[DATE] = date.getUTCDate();
  13157. }
  13158. // Default to current date.
  13159. // * if no year, month, day of month are given, default to today
  13160. // * if day of month is given, default month and year
  13161. // * if month is given, default only year
  13162. // * if year is given, don't default anything
  13163. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  13164. config._a[i] = input[i] = currentDate[i];
  13165. }
  13166. // Zero out whatever was not defaulted, including time
  13167. for (; i < 7; i++) {
  13168. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  13169. }
  13170. // Check for 24:00:00.000
  13171. if (config._a[HOUR] === 24 &&
  13172. config._a[MINUTE] === 0 &&
  13173. config._a[SECOND] === 0 &&
  13174. config._a[MILLISECOND] === 0) {
  13175. config._nextDay = true;
  13176. config._a[HOUR] = 0;
  13177. }
  13178. config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
  13179. expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
  13180. // Apply timezone offset from input. The actual utcOffset can be changed
  13181. // with parseZone.
  13182. if (config._tzm != null) {
  13183. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  13184. }
  13185. if (config._nextDay) {
  13186. config._a[HOUR] = 24;
  13187. }
  13188. // check for mismatching day of week
  13189. if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
  13190. getParsingFlags(config).weekdayMismatch = true;
  13191. }
  13192. }
  13193. function dayOfYearFromWeekInfo(config) {
  13194. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
  13195. w = config._w;
  13196. if (w.GG != null || w.W != null || w.E != null) {
  13197. dow = 1;
  13198. doy = 4;
  13199. // TODO: We need to take the current isoWeekYear, but that depends on
  13200. // how we interpret now (local, utc, fixed offset). So create
  13201. // a now version of current config (take local/utc/offset flags, and
  13202. // create now).
  13203. weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
  13204. week = defaults(w.W, 1);
  13205. weekday = defaults(w.E, 1);
  13206. if (weekday < 1 || weekday > 7) {
  13207. weekdayOverflow = true;
  13208. }
  13209. } else {
  13210. dow = config._locale._week.dow;
  13211. doy = config._locale._week.doy;
  13212. var curWeek = weekOfYear(createLocal(), dow, doy);
  13213. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  13214. // Default to current week.
  13215. week = defaults(w.w, curWeek.week);
  13216. if (w.d != null) {
  13217. // weekday -- low day numbers are considered next week
  13218. weekday = w.d;
  13219. if (weekday < 0 || weekday > 6) {
  13220. weekdayOverflow = true;
  13221. }
  13222. } else if (w.e != null) {
  13223. // local weekday -- counting starts from beginning of week
  13224. weekday = w.e + dow;
  13225. if (w.e < 0 || w.e > 6) {
  13226. weekdayOverflow = true;
  13227. }
  13228. } else {
  13229. // default to beginning of week
  13230. weekday = dow;
  13231. }
  13232. }
  13233. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  13234. getParsingFlags(config)._overflowWeeks = true;
  13235. } else if (weekdayOverflow != null) {
  13236. getParsingFlags(config)._overflowWeekday = true;
  13237. } else {
  13238. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  13239. config._a[YEAR] = temp.year;
  13240. config._dayOfYear = temp.dayOfYear;
  13241. }
  13242. }
  13243. // iso 8601 regex
  13244. // 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)
  13245. var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
  13246. var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
  13247. var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
  13248. var isoDates = [
  13249. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  13250. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  13251. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  13252. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  13253. ['YYYY-DDD', /\d{4}-\d{3}/],
  13254. ['YYYY-MM', /\d{4}-\d\d/, false],
  13255. ['YYYYYYMMDD', /[+-]\d{10}/],
  13256. ['YYYYMMDD', /\d{8}/],
  13257. // YYYYMM is NOT allowed by the standard
  13258. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  13259. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  13260. ['YYYYDDD', /\d{7}/]
  13261. ];
  13262. // iso time formats and regexes
  13263. var isoTimes = [
  13264. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  13265. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  13266. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  13267. ['HH:mm', /\d\d:\d\d/],
  13268. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  13269. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  13270. ['HHmmss', /\d\d\d\d\d\d/],
  13271. ['HHmm', /\d\d\d\d/],
  13272. ['HH', /\d\d/]
  13273. ];
  13274. var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
  13275. // date from iso format
  13276. function configFromISO(config) {
  13277. var i, l,
  13278. string = config._i,
  13279. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  13280. allowTime, dateFormat, timeFormat, tzFormat;
  13281. if (match) {
  13282. getParsingFlags(config).iso = true;
  13283. for (i = 0, l = isoDates.length; i < l; i++) {
  13284. if (isoDates[i][1].exec(match[1])) {
  13285. dateFormat = isoDates[i][0];
  13286. allowTime = isoDates[i][2] !== false;
  13287. break;
  13288. }
  13289. }
  13290. if (dateFormat == null) {
  13291. config._isValid = false;
  13292. return;
  13293. }
  13294. if (match[3]) {
  13295. for (i = 0, l = isoTimes.length; i < l; i++) {
  13296. if (isoTimes[i][1].exec(match[3])) {
  13297. // match[2] should be 'T' or space
  13298. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  13299. break;
  13300. }
  13301. }
  13302. if (timeFormat == null) {
  13303. config._isValid = false;
  13304. return;
  13305. }
  13306. }
  13307. if (!allowTime && timeFormat != null) {
  13308. config._isValid = false;
  13309. return;
  13310. }
  13311. if (match[4]) {
  13312. if (tzRegex.exec(match[4])) {
  13313. tzFormat = 'Z';
  13314. } else {
  13315. config._isValid = false;
  13316. return;
  13317. }
  13318. }
  13319. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  13320. configFromStringAndFormat(config);
  13321. } else {
  13322. config._isValid = false;
  13323. }
  13324. }
  13325. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  13326. var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
  13327. function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  13328. var result = [
  13329. untruncateYear(yearStr),
  13330. defaultLocaleMonthsShort.indexOf(monthStr),
  13331. parseInt(dayStr, 10),
  13332. parseInt(hourStr, 10),
  13333. parseInt(minuteStr, 10)
  13334. ];
  13335. if (secondStr) {
  13336. result.push(parseInt(secondStr, 10));
  13337. }
  13338. return result;
  13339. }
  13340. function untruncateYear(yearStr) {
  13341. var year = parseInt(yearStr, 10);
  13342. if (year <= 49) {
  13343. return 2000 + year;
  13344. } else if (year <= 999) {
  13345. return 1900 + year;
  13346. }
  13347. return year;
  13348. }
  13349. function preprocessRFC2822(s) {
  13350. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  13351. return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  13352. }
  13353. function checkWeekday(weekdayStr, parsedInput, config) {
  13354. if (weekdayStr) {
  13355. // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
  13356. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  13357. weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
  13358. if (weekdayProvided !== weekdayActual) {
  13359. getParsingFlags(config).weekdayMismatch = true;
  13360. config._isValid = false;
  13361. return false;
  13362. }
  13363. }
  13364. return true;
  13365. }
  13366. var obsOffsets = {
  13367. UT: 0,
  13368. GMT: 0,
  13369. EDT: -4 * 60,
  13370. EST: -5 * 60,
  13371. CDT: -5 * 60,
  13372. CST: -6 * 60,
  13373. MDT: -6 * 60,
  13374. MST: -7 * 60,
  13375. PDT: -7 * 60,
  13376. PST: -8 * 60
  13377. };
  13378. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  13379. if (obsOffset) {
  13380. return obsOffsets[obsOffset];
  13381. } else if (militaryOffset) {
  13382. // the only allowed military tz is Z
  13383. return 0;
  13384. } else {
  13385. var hm = parseInt(numOffset, 10);
  13386. var m = hm % 100, h = (hm - m) / 100;
  13387. return h * 60 + m;
  13388. }
  13389. }
  13390. // date and time from ref 2822 format
  13391. function configFromRFC2822(config) {
  13392. var match = rfc2822.exec(preprocessRFC2822(config._i));
  13393. if (match) {
  13394. var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
  13395. if (!checkWeekday(match[1], parsedArray, config)) {
  13396. return;
  13397. }
  13398. config._a = parsedArray;
  13399. config._tzm = calculateOffset(match[8], match[9], match[10]);
  13400. config._d = createUTCDate.apply(null, config._a);
  13401. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  13402. getParsingFlags(config).rfc2822 = true;
  13403. } else {
  13404. config._isValid = false;
  13405. }
  13406. }
  13407. // date from iso format or fallback
  13408. function configFromString(config) {
  13409. var matched = aspNetJsonRegex.exec(config._i);
  13410. if (matched !== null) {
  13411. config._d = new Date(+matched[1]);
  13412. return;
  13413. }
  13414. configFromISO(config);
  13415. if (config._isValid === false) {
  13416. delete config._isValid;
  13417. } else {
  13418. return;
  13419. }
  13420. configFromRFC2822(config);
  13421. if (config._isValid === false) {
  13422. delete config._isValid;
  13423. } else {
  13424. return;
  13425. }
  13426. // Final attempt, use Input Fallback
  13427. hooks.createFromInputFallback(config);
  13428. }
  13429. hooks.createFromInputFallback = deprecate(
  13430. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  13431. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  13432. 'discouraged and will be removed in an upcoming major release. Please refer to ' +
  13433. 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  13434. function (config) {
  13435. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  13436. }
  13437. );
  13438. // constant that refers to the ISO standard
  13439. hooks.ISO_8601 = function () {};
  13440. // constant that refers to the RFC 2822 form
  13441. hooks.RFC_2822 = function () {};
  13442. // date from string and format string
  13443. function configFromStringAndFormat(config) {
  13444. // TODO: Move this to another part of the creation flow to prevent circular deps
  13445. if (config._f === hooks.ISO_8601) {
  13446. configFromISO(config);
  13447. return;
  13448. }
  13449. if (config._f === hooks.RFC_2822) {
  13450. configFromRFC2822(config);
  13451. return;
  13452. }
  13453. config._a = [];
  13454. getParsingFlags(config).empty = true;
  13455. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  13456. var string = '' + config._i,
  13457. i, parsedInput, tokens, token, skipped,
  13458. stringLength = string.length,
  13459. totalParsedInputLength = 0;
  13460. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  13461. for (i = 0; i < tokens.length; i++) {
  13462. token = tokens[i];
  13463. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  13464. // console.log('token', token, 'parsedInput', parsedInput,
  13465. // 'regex', getParseRegexForToken(token, config));
  13466. if (parsedInput) {
  13467. skipped = string.substr(0, string.indexOf(parsedInput));
  13468. if (skipped.length > 0) {
  13469. getParsingFlags(config).unusedInput.push(skipped);
  13470. }
  13471. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  13472. totalParsedInputLength += parsedInput.length;
  13473. }
  13474. // don't parse if it's not a known token
  13475. if (formatTokenFunctions[token]) {
  13476. if (parsedInput) {
  13477. getParsingFlags(config).empty = false;
  13478. }
  13479. else {
  13480. getParsingFlags(config).unusedTokens.push(token);
  13481. }
  13482. addTimeToArrayFromToken(token, parsedInput, config);
  13483. }
  13484. else if (config._strict && !parsedInput) {
  13485. getParsingFlags(config).unusedTokens.push(token);
  13486. }
  13487. }
  13488. // add remaining unparsed input length to the string
  13489. getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
  13490. if (string.length > 0) {
  13491. getParsingFlags(config).unusedInput.push(string);
  13492. }
  13493. // clear _12h flag if hour is <= 12
  13494. if (config._a[HOUR] <= 12 &&
  13495. getParsingFlags(config).bigHour === true &&
  13496. config._a[HOUR] > 0) {
  13497. getParsingFlags(config).bigHour = undefined;
  13498. }
  13499. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  13500. getParsingFlags(config).meridiem = config._meridiem;
  13501. // handle meridiem
  13502. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
  13503. configFromArray(config);
  13504. checkOverflow(config);
  13505. }
  13506. function meridiemFixWrap (locale, hour, meridiem) {
  13507. var isPm;
  13508. if (meridiem == null) {
  13509. // nothing to do
  13510. return hour;
  13511. }
  13512. if (locale.meridiemHour != null) {
  13513. return locale.meridiemHour(hour, meridiem);
  13514. } else if (locale.isPM != null) {
  13515. // Fallback
  13516. isPm = locale.isPM(meridiem);
  13517. if (isPm && hour < 12) {
  13518. hour += 12;
  13519. }
  13520. if (!isPm && hour === 12) {
  13521. hour = 0;
  13522. }
  13523. return hour;
  13524. } else {
  13525. // this is not supposed to happen
  13526. return hour;
  13527. }
  13528. }
  13529. // date from string and array of format strings
  13530. function configFromStringAndArray(config) {
  13531. var tempConfig,
  13532. bestMoment,
  13533. scoreToBeat,
  13534. i,
  13535. currentScore;
  13536. if (config._f.length === 0) {
  13537. getParsingFlags(config).invalidFormat = true;
  13538. config._d = new Date(NaN);
  13539. return;
  13540. }
  13541. for (i = 0; i < config._f.length; i++) {
  13542. currentScore = 0;
  13543. tempConfig = copyConfig({}, config);
  13544. if (config._useUTC != null) {
  13545. tempConfig._useUTC = config._useUTC;
  13546. }
  13547. tempConfig._f = config._f[i];
  13548. configFromStringAndFormat(tempConfig);
  13549. if (!isValid(tempConfig)) {
  13550. continue;
  13551. }
  13552. // if there is any input that was not parsed add a penalty for that format
  13553. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  13554. //or tokens
  13555. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  13556. getParsingFlags(tempConfig).score = currentScore;
  13557. if (scoreToBeat == null || currentScore < scoreToBeat) {
  13558. scoreToBeat = currentScore;
  13559. bestMoment = tempConfig;
  13560. }
  13561. }
  13562. extend(config, bestMoment || tempConfig);
  13563. }
  13564. function configFromObject(config) {
  13565. if (config._d) {
  13566. return;
  13567. }
  13568. var i = normalizeObjectUnits(config._i);
  13569. config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
  13570. return obj && parseInt(obj, 10);
  13571. });
  13572. configFromArray(config);
  13573. }
  13574. function createFromConfig (config) {
  13575. var res = new Moment(checkOverflow(prepareConfig(config)));
  13576. if (res._nextDay) {
  13577. // Adding is smart enough around DST
  13578. res.add(1, 'd');
  13579. res._nextDay = undefined;
  13580. }
  13581. return res;
  13582. }
  13583. function prepareConfig (config) {
  13584. var input = config._i,
  13585. format = config._f;
  13586. config._locale = config._locale || getLocale(config._l);
  13587. if (input === null || (format === undefined && input === '')) {
  13588. return createInvalid({nullInput: true});
  13589. }
  13590. if (typeof input === 'string') {
  13591. config._i = input = config._locale.preparse(input);
  13592. }
  13593. if (isMoment(input)) {
  13594. return new Moment(checkOverflow(input));
  13595. } else if (isDate(input)) {
  13596. config._d = input;
  13597. } else if (isArray(format)) {
  13598. configFromStringAndArray(config);
  13599. } else if (format) {
  13600. configFromStringAndFormat(config);
  13601. } else {
  13602. configFromInput(config);
  13603. }
  13604. if (!isValid(config)) {
  13605. config._d = null;
  13606. }
  13607. return config;
  13608. }
  13609. function configFromInput(config) {
  13610. var input = config._i;
  13611. if (isUndefined(input)) {
  13612. config._d = new Date(hooks.now());
  13613. } else if (isDate(input)) {
  13614. config._d = new Date(input.valueOf());
  13615. } else if (typeof input === 'string') {
  13616. configFromString(config);
  13617. } else if (isArray(input)) {
  13618. config._a = map(input.slice(0), function (obj) {
  13619. return parseInt(obj, 10);
  13620. });
  13621. configFromArray(config);
  13622. } else if (isObject(input)) {
  13623. configFromObject(config);
  13624. } else if (isNumber(input)) {
  13625. // from milliseconds
  13626. config._d = new Date(input);
  13627. } else {
  13628. hooks.createFromInputFallback(config);
  13629. }
  13630. }
  13631. function createLocalOrUTC (input, format, locale, strict, isUTC) {
  13632. var c = {};
  13633. if (locale === true || locale === false) {
  13634. strict = locale;
  13635. locale = undefined;
  13636. }
  13637. if ((isObject(input) && isObjectEmpty(input)) ||
  13638. (isArray(input) && input.length === 0)) {
  13639. input = undefined;
  13640. }
  13641. // object construction must be done this way.
  13642. // https://github.com/moment/moment/issues/1423
  13643. c._isAMomentObject = true;
  13644. c._useUTC = c._isUTC = isUTC;
  13645. c._l = locale;
  13646. c._i = input;
  13647. c._f = format;
  13648. c._strict = strict;
  13649. return createFromConfig(c);
  13650. }
  13651. function createLocal (input, format, locale, strict) {
  13652. return createLocalOrUTC(input, format, locale, strict, false);
  13653. }
  13654. var prototypeMin = deprecate(
  13655. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  13656. function () {
  13657. var other = createLocal.apply(null, arguments);
  13658. if (this.isValid() && other.isValid()) {
  13659. return other < this ? this : other;
  13660. } else {
  13661. return createInvalid();
  13662. }
  13663. }
  13664. );
  13665. var prototypeMax = deprecate(
  13666. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  13667. function () {
  13668. var other = createLocal.apply(null, arguments);
  13669. if (this.isValid() && other.isValid()) {
  13670. return other > this ? this : other;
  13671. } else {
  13672. return createInvalid();
  13673. }
  13674. }
  13675. );
  13676. // Pick a moment m from moments so that m[fn](other) is true for all
  13677. // other. This relies on the function fn to be transitive.
  13678. //
  13679. // moments should either be an array of moment objects or an array, whose
  13680. // first element is an array of moment objects.
  13681. function pickBy(fn, moments) {
  13682. var res, i;
  13683. if (moments.length === 1 && isArray(moments[0])) {
  13684. moments = moments[0];
  13685. }
  13686. if (!moments.length) {
  13687. return createLocal();
  13688. }
  13689. res = moments[0];
  13690. for (i = 1; i < moments.length; ++i) {
  13691. if (!moments[i].isValid() || moments[i][fn](res)) {
  13692. res = moments[i];
  13693. }
  13694. }
  13695. return res;
  13696. }
  13697. // TODO: Use [].sort instead?
  13698. function min () {
  13699. var args = [].slice.call(arguments, 0);
  13700. return pickBy('isBefore', args);
  13701. }
  13702. function max () {
  13703. var args = [].slice.call(arguments, 0);
  13704. return pickBy('isAfter', args);
  13705. }
  13706. var now = function () {
  13707. return Date.now ? Date.now() : +(new Date());
  13708. };
  13709. var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
  13710. function isDurationValid(m) {
  13711. for (var key in m) {
  13712. if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
  13713. return false;
  13714. }
  13715. }
  13716. var unitHasDecimal = false;
  13717. for (var i = 0; i < ordering.length; ++i) {
  13718. if (m[ordering[i]]) {
  13719. if (unitHasDecimal) {
  13720. return false; // only allow non-integers for smallest unit
  13721. }
  13722. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  13723. unitHasDecimal = true;
  13724. }
  13725. }
  13726. }
  13727. return true;
  13728. }
  13729. function isValid$1() {
  13730. return this._isValid;
  13731. }
  13732. function createInvalid$1() {
  13733. return createDuration(NaN);
  13734. }
  13735. function Duration (duration) {
  13736. var normalizedInput = normalizeObjectUnits(duration),
  13737. years = normalizedInput.year || 0,
  13738. quarters = normalizedInput.quarter || 0,
  13739. months = normalizedInput.month || 0,
  13740. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  13741. days = normalizedInput.day || 0,
  13742. hours = normalizedInput.hour || 0,
  13743. minutes = normalizedInput.minute || 0,
  13744. seconds = normalizedInput.second || 0,
  13745. milliseconds = normalizedInput.millisecond || 0;
  13746. this._isValid = isDurationValid(normalizedInput);
  13747. // representation for dateAddRemove
  13748. this._milliseconds = +milliseconds +
  13749. seconds * 1e3 + // 1000
  13750. minutes * 6e4 + // 1000 * 60
  13751. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  13752. // Because of dateAddRemove treats 24 hours as different from a
  13753. // day when working around DST, we need to store them separately
  13754. this._days = +days +
  13755. weeks * 7;
  13756. // It is impossible to translate months into days without knowing
  13757. // which months you are are talking about, so we have to store
  13758. // it separately.
  13759. this._months = +months +
  13760. quarters * 3 +
  13761. years * 12;
  13762. this._data = {};
  13763. this._locale = getLocale();
  13764. this._bubble();
  13765. }
  13766. function isDuration (obj) {
  13767. return obj instanceof Duration;
  13768. }
  13769. function absRound (number) {
  13770. if (number < 0) {
  13771. return Math.round(-1 * number) * -1;
  13772. } else {
  13773. return Math.round(number);
  13774. }
  13775. }
  13776. // FORMATTING
  13777. function offset (token, separator) {
  13778. addFormatToken(token, 0, 0, function () {
  13779. var offset = this.utcOffset();
  13780. var sign = '+';
  13781. if (offset < 0) {
  13782. offset = -offset;
  13783. sign = '-';
  13784. }
  13785. return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
  13786. });
  13787. }
  13788. offset('Z', ':');
  13789. offset('ZZ', '');
  13790. // PARSING
  13791. addRegexToken('Z', matchShortOffset);
  13792. addRegexToken('ZZ', matchShortOffset);
  13793. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  13794. config._useUTC = true;
  13795. config._tzm = offsetFromString(matchShortOffset, input);
  13796. });
  13797. // HELPERS
  13798. // timezone chunker
  13799. // '+10:00' > ['10', '00']
  13800. // '-1530' > ['-15', '30']
  13801. var chunkOffset = /([\+\-]|\d\d)/gi;
  13802. function offsetFromString(matcher, string) {
  13803. var matches = (string || '').match(matcher);
  13804. if (matches === null) {
  13805. return null;
  13806. }
  13807. var chunk = matches[matches.length - 1] || [];
  13808. var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  13809. var minutes = +(parts[1] * 60) + toInt(parts[2]);
  13810. return minutes === 0 ?
  13811. 0 :
  13812. parts[0] === '+' ? minutes : -minutes;
  13813. }
  13814. // Return a moment from input, that is local/utc/zone equivalent to model.
  13815. function cloneWithOffset(input, model) {
  13816. var res, diff;
  13817. if (model._isUTC) {
  13818. res = model.clone();
  13819. diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
  13820. // Use low-level api, because this fn is low-level api.
  13821. res._d.setTime(res._d.valueOf() + diff);
  13822. hooks.updateOffset(res, false);
  13823. return res;
  13824. } else {
  13825. return createLocal(input).local();
  13826. }
  13827. }
  13828. function getDateOffset (m) {
  13829. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  13830. // https://github.com/moment/moment/pull/1871
  13831. return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
  13832. }
  13833. // HOOKS
  13834. // This function will be called whenever a moment is mutated.
  13835. // It is intended to keep the offset in sync with the timezone.
  13836. hooks.updateOffset = function () {};
  13837. // MOMENTS
  13838. // keepLocalTime = true means only change the timezone, without
  13839. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  13840. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  13841. // +0200, so we adjust the time as needed, to be valid.
  13842. //
  13843. // Keeping the time actually adds/subtracts (one hour)
  13844. // from the actual represented time. That is why we call updateOffset
  13845. // a second time. In case it wants us to change the offset again
  13846. // _changeInProgress == true case, then we have to adjust, because
  13847. // there is no such time in the given timezone.
  13848. function getSetOffset (input, keepLocalTime, keepMinutes) {
  13849. var offset = this._offset || 0,
  13850. localAdjust;
  13851. if (!this.isValid()) {
  13852. return input != null ? this : NaN;
  13853. }
  13854. if (input != null) {
  13855. if (typeof input === 'string') {
  13856. input = offsetFromString(matchShortOffset, input);
  13857. if (input === null) {
  13858. return this;
  13859. }
  13860. } else if (Math.abs(input) < 16 && !keepMinutes) {
  13861. input = input * 60;
  13862. }
  13863. if (!this._isUTC && keepLocalTime) {
  13864. localAdjust = getDateOffset(this);
  13865. }
  13866. this._offset = input;
  13867. this._isUTC = true;
  13868. if (localAdjust != null) {
  13869. this.add(localAdjust, 'm');
  13870. }
  13871. if (offset !== input) {
  13872. if (!keepLocalTime || this._changeInProgress) {
  13873. addSubtract(this, createDuration(input - offset, 'm'), 1, false);
  13874. } else if (!this._changeInProgress) {
  13875. this._changeInProgress = true;
  13876. hooks.updateOffset(this, true);
  13877. this._changeInProgress = null;
  13878. }
  13879. }
  13880. return this;
  13881. } else {
  13882. return this._isUTC ? offset : getDateOffset(this);
  13883. }
  13884. }
  13885. function getSetZone (input, keepLocalTime) {
  13886. if (input != null) {
  13887. if (typeof input !== 'string') {
  13888. input = -input;
  13889. }
  13890. this.utcOffset(input, keepLocalTime);
  13891. return this;
  13892. } else {
  13893. return -this.utcOffset();
  13894. }
  13895. }
  13896. function setOffsetToUTC (keepLocalTime) {
  13897. return this.utcOffset(0, keepLocalTime);
  13898. }
  13899. function setOffsetToLocal (keepLocalTime) {
  13900. if (this._isUTC) {
  13901. this.utcOffset(0, keepLocalTime);
  13902. this._isUTC = false;
  13903. if (keepLocalTime) {
  13904. this.subtract(getDateOffset(this), 'm');
  13905. }
  13906. }
  13907. return this;
  13908. }
  13909. function setOffsetToParsedOffset () {
  13910. if (this._tzm != null) {
  13911. this.utcOffset(this._tzm, false, true);
  13912. } else if (typeof this._i === 'string') {
  13913. var tZone = offsetFromString(matchOffset, this._i);
  13914. if (tZone != null) {
  13915. this.utcOffset(tZone);
  13916. }
  13917. else {
  13918. this.utcOffset(0, true);
  13919. }
  13920. }
  13921. return this;
  13922. }
  13923. function hasAlignedHourOffset (input) {
  13924. if (!this.isValid()) {
  13925. return false;
  13926. }
  13927. input = input ? createLocal(input).utcOffset() : 0;
  13928. return (this.utcOffset() - input) % 60 === 0;
  13929. }
  13930. function isDaylightSavingTime () {
  13931. return (
  13932. this.utcOffset() > this.clone().month(0).utcOffset() ||
  13933. this.utcOffset() > this.clone().month(5).utcOffset()
  13934. );
  13935. }
  13936. function isDaylightSavingTimeShifted () {
  13937. if (!isUndefined(this._isDSTShifted)) {
  13938. return this._isDSTShifted;
  13939. }
  13940. var c = {};
  13941. copyConfig(c, this);
  13942. c = prepareConfig(c);
  13943. if (c._a) {
  13944. var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  13945. this._isDSTShifted = this.isValid() &&
  13946. compareArrays(c._a, other.toArray()) > 0;
  13947. } else {
  13948. this._isDSTShifted = false;
  13949. }
  13950. return this._isDSTShifted;
  13951. }
  13952. function isLocal () {
  13953. return this.isValid() ? !this._isUTC : false;
  13954. }
  13955. function isUtcOffset () {
  13956. return this.isValid() ? this._isUTC : false;
  13957. }
  13958. function isUtc () {
  13959. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  13960. }
  13961. // ASP.NET json date format regex
  13962. var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
  13963. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  13964. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  13965. // and further modified to allow for strings containing both week and day
  13966. var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  13967. function createDuration (input, key) {
  13968. var duration = input,
  13969. // matching against regexp is expensive, do it on demand
  13970. match = null,
  13971. sign,
  13972. ret,
  13973. diffRes;
  13974. if (isDuration(input)) {
  13975. duration = {
  13976. ms : input._milliseconds,
  13977. d : input._days,
  13978. M : input._months
  13979. };
  13980. } else if (isNumber(input)) {
  13981. duration = {};
  13982. if (key) {
  13983. duration[key] = input;
  13984. } else {
  13985. duration.milliseconds = input;
  13986. }
  13987. } else if (!!(match = aspNetRegex.exec(input))) {
  13988. sign = (match[1] === '-') ? -1 : 1;
  13989. duration = {
  13990. y : 0,
  13991. d : toInt(match[DATE]) * sign,
  13992. h : toInt(match[HOUR]) * sign,
  13993. m : toInt(match[MINUTE]) * sign,
  13994. s : toInt(match[SECOND]) * sign,
  13995. ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
  13996. };
  13997. } else if (!!(match = isoRegex.exec(input))) {
  13998. sign = (match[1] === '-') ? -1 : 1;
  13999. duration = {
  14000. y : parseIso(match[2], sign),
  14001. M : parseIso(match[3], sign),
  14002. w : parseIso(match[4], sign),
  14003. d : parseIso(match[5], sign),
  14004. h : parseIso(match[6], sign),
  14005. m : parseIso(match[7], sign),
  14006. s : parseIso(match[8], sign)
  14007. };
  14008. } else if (duration == null) {// checks for null or undefined
  14009. duration = {};
  14010. } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
  14011. diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
  14012. duration = {};
  14013. duration.ms = diffRes.milliseconds;
  14014. duration.M = diffRes.months;
  14015. }
  14016. ret = new Duration(duration);
  14017. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  14018. ret._locale = input._locale;
  14019. }
  14020. return ret;
  14021. }
  14022. createDuration.fn = Duration.prototype;
  14023. createDuration.invalid = createInvalid$1;
  14024. function parseIso (inp, sign) {
  14025. // We'd normally use ~~inp for this, but unfortunately it also
  14026. // converts floats to ints.
  14027. // inp may be undefined, so careful calling replace on it.
  14028. var res = inp && parseFloat(inp.replace(',', '.'));
  14029. // apply sign while we're at it
  14030. return (isNaN(res) ? 0 : res) * sign;
  14031. }
  14032. function positiveMomentsDifference(base, other) {
  14033. var res = {};
  14034. res.months = other.month() - base.month() +
  14035. (other.year() - base.year()) * 12;
  14036. if (base.clone().add(res.months, 'M').isAfter(other)) {
  14037. --res.months;
  14038. }
  14039. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  14040. return res;
  14041. }
  14042. function momentsDifference(base, other) {
  14043. var res;
  14044. if (!(base.isValid() && other.isValid())) {
  14045. return {milliseconds: 0, months: 0};
  14046. }
  14047. other = cloneWithOffset(other, base);
  14048. if (base.isBefore(other)) {
  14049. res = positiveMomentsDifference(base, other);
  14050. } else {
  14051. res = positiveMomentsDifference(other, base);
  14052. res.milliseconds = -res.milliseconds;
  14053. res.months = -res.months;
  14054. }
  14055. return res;
  14056. }
  14057. // TODO: remove 'name' arg after deprecation is removed
  14058. function createAdder(direction, name) {
  14059. return function (val, period) {
  14060. var dur, tmp;
  14061. //invert the arguments, but complain about it
  14062. if (period !== null && !isNaN(+period)) {
  14063. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
  14064. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
  14065. tmp = val; val = period; period = tmp;
  14066. }
  14067. val = typeof val === 'string' ? +val : val;
  14068. dur = createDuration(val, period);
  14069. addSubtract(this, dur, direction);
  14070. return this;
  14071. };
  14072. }
  14073. function addSubtract (mom, duration, isAdding, updateOffset) {
  14074. var milliseconds = duration._milliseconds,
  14075. days = absRound(duration._days),
  14076. months = absRound(duration._months);
  14077. if (!mom.isValid()) {
  14078. // No op
  14079. return;
  14080. }
  14081. updateOffset = updateOffset == null ? true : updateOffset;
  14082. if (months) {
  14083. setMonth(mom, get(mom, 'Month') + months * isAdding);
  14084. }
  14085. if (days) {
  14086. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  14087. }
  14088. if (milliseconds) {
  14089. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  14090. }
  14091. if (updateOffset) {
  14092. hooks.updateOffset(mom, days || months);
  14093. }
  14094. }
  14095. var add = createAdder(1, 'add');
  14096. var subtract = createAdder(-1, 'subtract');
  14097. function getCalendarFormat(myMoment, now) {
  14098. var diff = myMoment.diff(now, 'days', true);
  14099. return diff < -6 ? 'sameElse' :
  14100. diff < -1 ? 'lastWeek' :
  14101. diff < 0 ? 'lastDay' :
  14102. diff < 1 ? 'sameDay' :
  14103. diff < 2 ? 'nextDay' :
  14104. diff < 7 ? 'nextWeek' : 'sameElse';
  14105. }
  14106. function calendar$1 (time, formats) {
  14107. // We want to compare the start of today, vs this.
  14108. // Getting start-of-today depends on whether we're local/utc/offset or not.
  14109. var now = time || createLocal(),
  14110. sod = cloneWithOffset(now, this).startOf('day'),
  14111. format = hooks.calendarFormat(this, sod) || 'sameElse';
  14112. var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
  14113. return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
  14114. }
  14115. function clone () {
  14116. return new Moment(this);
  14117. }
  14118. function isAfter (input, units) {
  14119. var localInput = isMoment(input) ? input : createLocal(input);
  14120. if (!(this.isValid() && localInput.isValid())) {
  14121. return false;
  14122. }
  14123. units = normalizeUnits(units) || 'millisecond';
  14124. if (units === 'millisecond') {
  14125. return this.valueOf() > localInput.valueOf();
  14126. } else {
  14127. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  14128. }
  14129. }
  14130. function isBefore (input, units) {
  14131. var localInput = isMoment(input) ? input : createLocal(input);
  14132. if (!(this.isValid() && localInput.isValid())) {
  14133. return false;
  14134. }
  14135. units = normalizeUnits(units) || 'millisecond';
  14136. if (units === 'millisecond') {
  14137. return this.valueOf() < localInput.valueOf();
  14138. } else {
  14139. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  14140. }
  14141. }
  14142. function isBetween (from, to, units, inclusivity) {
  14143. var localFrom = isMoment(from) ? from : createLocal(from),
  14144. localTo = isMoment(to) ? to : createLocal(to);
  14145. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  14146. return false;
  14147. }
  14148. inclusivity = inclusivity || '()';
  14149. return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) &&
  14150. (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
  14151. }
  14152. function isSame (input, units) {
  14153. var localInput = isMoment(input) ? input : createLocal(input),
  14154. inputMs;
  14155. if (!(this.isValid() && localInput.isValid())) {
  14156. return false;
  14157. }
  14158. units = normalizeUnits(units) || 'millisecond';
  14159. if (units === 'millisecond') {
  14160. return this.valueOf() === localInput.valueOf();
  14161. } else {
  14162. inputMs = localInput.valueOf();
  14163. return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
  14164. }
  14165. }
  14166. function isSameOrAfter (input, units) {
  14167. return this.isSame(input, units) || this.isAfter(input, units);
  14168. }
  14169. function isSameOrBefore (input, units) {
  14170. return this.isSame(input, units) || this.isBefore(input, units);
  14171. }
  14172. function diff (input, units, asFloat) {
  14173. var that,
  14174. zoneDelta,
  14175. output;
  14176. if (!this.isValid()) {
  14177. return NaN;
  14178. }
  14179. that = cloneWithOffset(input, this);
  14180. if (!that.isValid()) {
  14181. return NaN;
  14182. }
  14183. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  14184. units = normalizeUnits(units);
  14185. switch (units) {
  14186. case 'year': output = monthDiff(this, that) / 12; break;
  14187. case 'month': output = monthDiff(this, that); break;
  14188. case 'quarter': output = monthDiff(this, that) / 3; break;
  14189. case 'second': output = (this - that) / 1e3; break; // 1000
  14190. case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
  14191. case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
  14192. case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
  14193. case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
  14194. default: output = this - that;
  14195. }
  14196. return asFloat ? output : absFloor(output);
  14197. }
  14198. function monthDiff (a, b) {
  14199. // difference in months
  14200. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  14201. // b is in (anchor - 1 month, anchor + 1 month)
  14202. anchor = a.clone().add(wholeMonthDiff, 'months'),
  14203. anchor2, adjust;
  14204. if (b - anchor < 0) {
  14205. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  14206. // linear across the month
  14207. adjust = (b - anchor) / (anchor - anchor2);
  14208. } else {
  14209. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  14210. // linear across the month
  14211. adjust = (b - anchor) / (anchor2 - anchor);
  14212. }
  14213. //check for negative zero, return zero if negative zero
  14214. return -(wholeMonthDiff + adjust) || 0;
  14215. }
  14216. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  14217. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  14218. function toString () {
  14219. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  14220. }
  14221. function toISOString(keepOffset) {
  14222. if (!this.isValid()) {
  14223. return null;
  14224. }
  14225. var utc = keepOffset !== true;
  14226. var m = utc ? this.clone().utc() : this;
  14227. if (m.year() < 0 || m.year() > 9999) {
  14228. return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
  14229. }
  14230. if (isFunction(Date.prototype.toISOString)) {
  14231. // native implementation is ~50x faster, use it when we can
  14232. if (utc) {
  14233. return this.toDate().toISOString();
  14234. } else {
  14235. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
  14236. }
  14237. }
  14238. return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
  14239. }
  14240. /**
  14241. * Return a human readable representation of a moment that can
  14242. * also be evaluated to get a new moment which is the same
  14243. *
  14244. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  14245. */
  14246. function inspect () {
  14247. if (!this.isValid()) {
  14248. return 'moment.invalid(/* ' + this._i + ' */)';
  14249. }
  14250. var func = 'moment';
  14251. var zone = '';
  14252. if (!this.isLocal()) {
  14253. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  14254. zone = 'Z';
  14255. }
  14256. var prefix = '[' + func + '("]';
  14257. var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
  14258. var datetime = '-MM-DD[T]HH:mm:ss.SSS';
  14259. var suffix = zone + '[")]';
  14260. return this.format(prefix + year + datetime + suffix);
  14261. }
  14262. function format (inputString) {
  14263. if (!inputString) {
  14264. inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
  14265. }
  14266. var output = formatMoment(this, inputString);
  14267. return this.localeData().postformat(output);
  14268. }
  14269. function from (time, withoutSuffix) {
  14270. if (this.isValid() &&
  14271. ((isMoment(time) && time.isValid()) ||
  14272. createLocal(time).isValid())) {
  14273. return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  14274. } else {
  14275. return this.localeData().invalidDate();
  14276. }
  14277. }
  14278. function fromNow (withoutSuffix) {
  14279. return this.from(createLocal(), withoutSuffix);
  14280. }
  14281. function to (time, withoutSuffix) {
  14282. if (this.isValid() &&
  14283. ((isMoment(time) && time.isValid()) ||
  14284. createLocal(time).isValid())) {
  14285. return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
  14286. } else {
  14287. return this.localeData().invalidDate();
  14288. }
  14289. }
  14290. function toNow (withoutSuffix) {
  14291. return this.to(createLocal(), withoutSuffix);
  14292. }
  14293. // If passed a locale key, it will set the locale for this
  14294. // instance. Otherwise, it will return the locale configuration
  14295. // variables for this instance.
  14296. function locale (key) {
  14297. var newLocaleData;
  14298. if (key === undefined) {
  14299. return this._locale._abbr;
  14300. } else {
  14301. newLocaleData = getLocale(key);
  14302. if (newLocaleData != null) {
  14303. this._locale = newLocaleData;
  14304. }
  14305. return this;
  14306. }
  14307. }
  14308. var lang = deprecate(
  14309. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  14310. function (key) {
  14311. if (key === undefined) {
  14312. return this.localeData();
  14313. } else {
  14314. return this.locale(key);
  14315. }
  14316. }
  14317. );
  14318. function localeData () {
  14319. return this._locale;
  14320. }
  14321. var MS_PER_SECOND = 1000;
  14322. var MS_PER_MINUTE = 60 * MS_PER_SECOND;
  14323. var MS_PER_HOUR = 60 * MS_PER_MINUTE;
  14324. var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  14325. // actual modulo - handles negative numbers (for dates before 1970):
  14326. function mod$1(dividend, divisor) {
  14327. return (dividend % divisor + divisor) % divisor;
  14328. }
  14329. function localStartOfDate(y, m, d) {
  14330. // the date constructor remaps years 0-99 to 1900-1999
  14331. if (y < 100 && y >= 0) {
  14332. // preserve leap years using a full 400 year cycle, then reset
  14333. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  14334. } else {
  14335. return new Date(y, m, d).valueOf();
  14336. }
  14337. }
  14338. function utcStartOfDate(y, m, d) {
  14339. // Date.UTC remaps years 0-99 to 1900-1999
  14340. if (y < 100 && y >= 0) {
  14341. // preserve leap years using a full 400 year cycle, then reset
  14342. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  14343. } else {
  14344. return Date.UTC(y, m, d);
  14345. }
  14346. }
  14347. function startOf (units) {
  14348. var time;
  14349. units = normalizeUnits(units);
  14350. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  14351. return this;
  14352. }
  14353. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  14354. switch (units) {
  14355. case 'year':
  14356. time = startOfDate(this.year(), 0, 1);
  14357. break;
  14358. case 'quarter':
  14359. time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
  14360. break;
  14361. case 'month':
  14362. time = startOfDate(this.year(), this.month(), 1);
  14363. break;
  14364. case 'week':
  14365. time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
  14366. break;
  14367. case 'isoWeek':
  14368. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
  14369. break;
  14370. case 'day':
  14371. case 'date':
  14372. time = startOfDate(this.year(), this.month(), this.date());
  14373. break;
  14374. case 'hour':
  14375. time = this._d.valueOf();
  14376. time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
  14377. break;
  14378. case 'minute':
  14379. time = this._d.valueOf();
  14380. time -= mod$1(time, MS_PER_MINUTE);
  14381. break;
  14382. case 'second':
  14383. time = this._d.valueOf();
  14384. time -= mod$1(time, MS_PER_SECOND);
  14385. break;
  14386. }
  14387. this._d.setTime(time);
  14388. hooks.updateOffset(this, true);
  14389. return this;
  14390. }
  14391. function endOf (units) {
  14392. var time;
  14393. units = normalizeUnits(units);
  14394. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  14395. return this;
  14396. }
  14397. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  14398. switch (units) {
  14399. case 'year':
  14400. time = startOfDate(this.year() + 1, 0, 1) - 1;
  14401. break;
  14402. case 'quarter':
  14403. time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
  14404. break;
  14405. case 'month':
  14406. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  14407. break;
  14408. case 'week':
  14409. time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
  14410. break;
  14411. case 'isoWeek':
  14412. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
  14413. break;
  14414. case 'day':
  14415. case 'date':
  14416. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  14417. break;
  14418. case 'hour':
  14419. time = this._d.valueOf();
  14420. time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
  14421. break;
  14422. case 'minute':
  14423. time = this._d.valueOf();
  14424. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  14425. break;
  14426. case 'second':
  14427. time = this._d.valueOf();
  14428. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  14429. break;
  14430. }
  14431. this._d.setTime(time);
  14432. hooks.updateOffset(this, true);
  14433. return this;
  14434. }
  14435. function valueOf () {
  14436. return this._d.valueOf() - ((this._offset || 0) * 60000);
  14437. }
  14438. function unix () {
  14439. return Math.floor(this.valueOf() / 1000);
  14440. }
  14441. function toDate () {
  14442. return new Date(this.valueOf());
  14443. }
  14444. function toArray () {
  14445. var m = this;
  14446. return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
  14447. }
  14448. function toObject () {
  14449. var m = this;
  14450. return {
  14451. years: m.year(),
  14452. months: m.month(),
  14453. date: m.date(),
  14454. hours: m.hours(),
  14455. minutes: m.minutes(),
  14456. seconds: m.seconds(),
  14457. milliseconds: m.milliseconds()
  14458. };
  14459. }
  14460. function toJSON () {
  14461. // new Date(NaN).toJSON() === null
  14462. return this.isValid() ? this.toISOString() : null;
  14463. }
  14464. function isValid$2 () {
  14465. return isValid(this);
  14466. }
  14467. function parsingFlags () {
  14468. return extend({}, getParsingFlags(this));
  14469. }
  14470. function invalidAt () {
  14471. return getParsingFlags(this).overflow;
  14472. }
  14473. function creationData() {
  14474. return {
  14475. input: this._i,
  14476. format: this._f,
  14477. locale: this._locale,
  14478. isUTC: this._isUTC,
  14479. strict: this._strict
  14480. };
  14481. }
  14482. // FORMATTING
  14483. addFormatToken(0, ['gg', 2], 0, function () {
  14484. return this.weekYear() % 100;
  14485. });
  14486. addFormatToken(0, ['GG', 2], 0, function () {
  14487. return this.isoWeekYear() % 100;
  14488. });
  14489. function addWeekYearFormatToken (token, getter) {
  14490. addFormatToken(0, [token, token.length], 0, getter);
  14491. }
  14492. addWeekYearFormatToken('gggg', 'weekYear');
  14493. addWeekYearFormatToken('ggggg', 'weekYear');
  14494. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  14495. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  14496. // ALIASES
  14497. addUnitAlias('weekYear', 'gg');
  14498. addUnitAlias('isoWeekYear', 'GG');
  14499. // PRIORITY
  14500. addUnitPriority('weekYear', 1);
  14501. addUnitPriority('isoWeekYear', 1);
  14502. // PARSING
  14503. addRegexToken('G', matchSigned);
  14504. addRegexToken('g', matchSigned);
  14505. addRegexToken('GG', match1to2, match2);
  14506. addRegexToken('gg', match1to2, match2);
  14507. addRegexToken('GGGG', match1to4, match4);
  14508. addRegexToken('gggg', match1to4, match4);
  14509. addRegexToken('GGGGG', match1to6, match6);
  14510. addRegexToken('ggggg', match1to6, match6);
  14511. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
  14512. week[token.substr(0, 2)] = toInt(input);
  14513. });
  14514. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  14515. week[token] = hooks.parseTwoDigitYear(input);
  14516. });
  14517. // MOMENTS
  14518. function getSetWeekYear (input) {
  14519. return getSetWeekYearHelper.call(this,
  14520. input,
  14521. this.week(),
  14522. this.weekday(),
  14523. this.localeData()._week.dow,
  14524. this.localeData()._week.doy);
  14525. }
  14526. function getSetISOWeekYear (input) {
  14527. return getSetWeekYearHelper.call(this,
  14528. input, this.isoWeek(), this.isoWeekday(), 1, 4);
  14529. }
  14530. function getISOWeeksInYear () {
  14531. return weeksInYear(this.year(), 1, 4);
  14532. }
  14533. function getWeeksInYear () {
  14534. var weekInfo = this.localeData()._week;
  14535. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  14536. }
  14537. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  14538. var weeksTarget;
  14539. if (input == null) {
  14540. return weekOfYear(this, dow, doy).year;
  14541. } else {
  14542. weeksTarget = weeksInYear(input, dow, doy);
  14543. if (week > weeksTarget) {
  14544. week = weeksTarget;
  14545. }
  14546. return setWeekAll.call(this, input, week, weekday, dow, doy);
  14547. }
  14548. }
  14549. function setWeekAll(weekYear, week, weekday, dow, doy) {
  14550. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  14551. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  14552. this.year(date.getUTCFullYear());
  14553. this.month(date.getUTCMonth());
  14554. this.date(date.getUTCDate());
  14555. return this;
  14556. }
  14557. // FORMATTING
  14558. addFormatToken('Q', 0, 'Qo', 'quarter');
  14559. // ALIASES
  14560. addUnitAlias('quarter', 'Q');
  14561. // PRIORITY
  14562. addUnitPriority('quarter', 7);
  14563. // PARSING
  14564. addRegexToken('Q', match1);
  14565. addParseToken('Q', function (input, array) {
  14566. array[MONTH] = (toInt(input) - 1) * 3;
  14567. });
  14568. // MOMENTS
  14569. function getSetQuarter (input) {
  14570. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  14571. }
  14572. // FORMATTING
  14573. addFormatToken('D', ['DD', 2], 'Do', 'date');
  14574. // ALIASES
  14575. addUnitAlias('date', 'D');
  14576. // PRIORITY
  14577. addUnitPriority('date', 9);
  14578. // PARSING
  14579. addRegexToken('D', match1to2);
  14580. addRegexToken('DD', match1to2, match2);
  14581. addRegexToken('Do', function (isStrict, locale) {
  14582. // TODO: Remove "ordinalParse" fallback in next major release.
  14583. return isStrict ?
  14584. (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
  14585. locale._dayOfMonthOrdinalParseLenient;
  14586. });
  14587. addParseToken(['D', 'DD'], DATE);
  14588. addParseToken('Do', function (input, array) {
  14589. array[DATE] = toInt(input.match(match1to2)[0]);
  14590. });
  14591. // MOMENTS
  14592. var getSetDayOfMonth = makeGetSet('Date', true);
  14593. // FORMATTING
  14594. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  14595. // ALIASES
  14596. addUnitAlias('dayOfYear', 'DDD');
  14597. // PRIORITY
  14598. addUnitPriority('dayOfYear', 4);
  14599. // PARSING
  14600. addRegexToken('DDD', match1to3);
  14601. addRegexToken('DDDD', match3);
  14602. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  14603. config._dayOfYear = toInt(input);
  14604. });
  14605. // HELPERS
  14606. // MOMENTS
  14607. function getSetDayOfYear (input) {
  14608. var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
  14609. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  14610. }
  14611. // FORMATTING
  14612. addFormatToken('m', ['mm', 2], 0, 'minute');
  14613. // ALIASES
  14614. addUnitAlias('minute', 'm');
  14615. // PRIORITY
  14616. addUnitPriority('minute', 14);
  14617. // PARSING
  14618. addRegexToken('m', match1to2);
  14619. addRegexToken('mm', match1to2, match2);
  14620. addParseToken(['m', 'mm'], MINUTE);
  14621. // MOMENTS
  14622. var getSetMinute = makeGetSet('Minutes', false);
  14623. // FORMATTING
  14624. addFormatToken('s', ['ss', 2], 0, 'second');
  14625. // ALIASES
  14626. addUnitAlias('second', 's');
  14627. // PRIORITY
  14628. addUnitPriority('second', 15);
  14629. // PARSING
  14630. addRegexToken('s', match1to2);
  14631. addRegexToken('ss', match1to2, match2);
  14632. addParseToken(['s', 'ss'], SECOND);
  14633. // MOMENTS
  14634. var getSetSecond = makeGetSet('Seconds', false);
  14635. // FORMATTING
  14636. addFormatToken('S', 0, 0, function () {
  14637. return ~~(this.millisecond() / 100);
  14638. });
  14639. addFormatToken(0, ['SS', 2], 0, function () {
  14640. return ~~(this.millisecond() / 10);
  14641. });
  14642. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  14643. addFormatToken(0, ['SSSS', 4], 0, function () {
  14644. return this.millisecond() * 10;
  14645. });
  14646. addFormatToken(0, ['SSSSS', 5], 0, function () {
  14647. return this.millisecond() * 100;
  14648. });
  14649. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  14650. return this.millisecond() * 1000;
  14651. });
  14652. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  14653. return this.millisecond() * 10000;
  14654. });
  14655. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  14656. return this.millisecond() * 100000;
  14657. });
  14658. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  14659. return this.millisecond() * 1000000;
  14660. });
  14661. // ALIASES
  14662. addUnitAlias('millisecond', 'ms');
  14663. // PRIORITY
  14664. addUnitPriority('millisecond', 16);
  14665. // PARSING
  14666. addRegexToken('S', match1to3, match1);
  14667. addRegexToken('SS', match1to3, match2);
  14668. addRegexToken('SSS', match1to3, match3);
  14669. var token;
  14670. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  14671. addRegexToken(token, matchUnsigned);
  14672. }
  14673. function parseMs(input, array) {
  14674. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  14675. }
  14676. for (token = 'S'; token.length <= 9; token += 'S') {
  14677. addParseToken(token, parseMs);
  14678. }
  14679. // MOMENTS
  14680. var getSetMillisecond = makeGetSet('Milliseconds', false);
  14681. // FORMATTING
  14682. addFormatToken('z', 0, 0, 'zoneAbbr');
  14683. addFormatToken('zz', 0, 0, 'zoneName');
  14684. // MOMENTS
  14685. function getZoneAbbr () {
  14686. return this._isUTC ? 'UTC' : '';
  14687. }
  14688. function getZoneName () {
  14689. return this._isUTC ? 'Coordinated Universal Time' : '';
  14690. }
  14691. var proto = Moment.prototype;
  14692. proto.add = add;
  14693. proto.calendar = calendar$1;
  14694. proto.clone = clone;
  14695. proto.diff = diff;
  14696. proto.endOf = endOf;
  14697. proto.format = format;
  14698. proto.from = from;
  14699. proto.fromNow = fromNow;
  14700. proto.to = to;
  14701. proto.toNow = toNow;
  14702. proto.get = stringGet;
  14703. proto.invalidAt = invalidAt;
  14704. proto.isAfter = isAfter;
  14705. proto.isBefore = isBefore;
  14706. proto.isBetween = isBetween;
  14707. proto.isSame = isSame;
  14708. proto.isSameOrAfter = isSameOrAfter;
  14709. proto.isSameOrBefore = isSameOrBefore;
  14710. proto.isValid = isValid$2;
  14711. proto.lang = lang;
  14712. proto.locale = locale;
  14713. proto.localeData = localeData;
  14714. proto.max = prototypeMax;
  14715. proto.min = prototypeMin;
  14716. proto.parsingFlags = parsingFlags;
  14717. proto.set = stringSet;
  14718. proto.startOf = startOf;
  14719. proto.subtract = subtract;
  14720. proto.toArray = toArray;
  14721. proto.toObject = toObject;
  14722. proto.toDate = toDate;
  14723. proto.toISOString = toISOString;
  14724. proto.inspect = inspect;
  14725. proto.toJSON = toJSON;
  14726. proto.toString = toString;
  14727. proto.unix = unix;
  14728. proto.valueOf = valueOf;
  14729. proto.creationData = creationData;
  14730. proto.year = getSetYear;
  14731. proto.isLeapYear = getIsLeapYear;
  14732. proto.weekYear = getSetWeekYear;
  14733. proto.isoWeekYear = getSetISOWeekYear;
  14734. proto.quarter = proto.quarters = getSetQuarter;
  14735. proto.month = getSetMonth;
  14736. proto.daysInMonth = getDaysInMonth;
  14737. proto.week = proto.weeks = getSetWeek;
  14738. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  14739. proto.weeksInYear = getWeeksInYear;
  14740. proto.isoWeeksInYear = getISOWeeksInYear;
  14741. proto.date = getSetDayOfMonth;
  14742. proto.day = proto.days = getSetDayOfWeek;
  14743. proto.weekday = getSetLocaleDayOfWeek;
  14744. proto.isoWeekday = getSetISODayOfWeek;
  14745. proto.dayOfYear = getSetDayOfYear;
  14746. proto.hour = proto.hours = getSetHour;
  14747. proto.minute = proto.minutes = getSetMinute;
  14748. proto.second = proto.seconds = getSetSecond;
  14749. proto.millisecond = proto.milliseconds = getSetMillisecond;
  14750. proto.utcOffset = getSetOffset;
  14751. proto.utc = setOffsetToUTC;
  14752. proto.local = setOffsetToLocal;
  14753. proto.parseZone = setOffsetToParsedOffset;
  14754. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  14755. proto.isDST = isDaylightSavingTime;
  14756. proto.isLocal = isLocal;
  14757. proto.isUtcOffset = isUtcOffset;
  14758. proto.isUtc = isUtc;
  14759. proto.isUTC = isUtc;
  14760. proto.zoneAbbr = getZoneAbbr;
  14761. proto.zoneName = getZoneName;
  14762. proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
  14763. proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
  14764. proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
  14765. proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
  14766. proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
  14767. function createUnix (input) {
  14768. return createLocal(input * 1000);
  14769. }
  14770. function createInZone () {
  14771. return createLocal.apply(null, arguments).parseZone();
  14772. }
  14773. function preParsePostFormat (string) {
  14774. return string;
  14775. }
  14776. var proto$1 = Locale.prototype;
  14777. proto$1.calendar = calendar;
  14778. proto$1.longDateFormat = longDateFormat;
  14779. proto$1.invalidDate = invalidDate;
  14780. proto$1.ordinal = ordinal;
  14781. proto$1.preparse = preParsePostFormat;
  14782. proto$1.postformat = preParsePostFormat;
  14783. proto$1.relativeTime = relativeTime;
  14784. proto$1.pastFuture = pastFuture;
  14785. proto$1.set = set;
  14786. proto$1.months = localeMonths;
  14787. proto$1.monthsShort = localeMonthsShort;
  14788. proto$1.monthsParse = localeMonthsParse;
  14789. proto$1.monthsRegex = monthsRegex;
  14790. proto$1.monthsShortRegex = monthsShortRegex;
  14791. proto$1.week = localeWeek;
  14792. proto$1.firstDayOfYear = localeFirstDayOfYear;
  14793. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  14794. proto$1.weekdays = localeWeekdays;
  14795. proto$1.weekdaysMin = localeWeekdaysMin;
  14796. proto$1.weekdaysShort = localeWeekdaysShort;
  14797. proto$1.weekdaysParse = localeWeekdaysParse;
  14798. proto$1.weekdaysRegex = weekdaysRegex;
  14799. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  14800. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  14801. proto$1.isPM = localeIsPM;
  14802. proto$1.meridiem = localeMeridiem;
  14803. function get$1 (format, index, field, setter) {
  14804. var locale = getLocale();
  14805. var utc = createUTC().set(setter, index);
  14806. return locale[field](utc, format);
  14807. }
  14808. function listMonthsImpl (format, index, field) {
  14809. if (isNumber(format)) {
  14810. index = format;
  14811. format = undefined;
  14812. }
  14813. format = format || '';
  14814. if (index != null) {
  14815. return get$1(format, index, field, 'month');
  14816. }
  14817. var i;
  14818. var out = [];
  14819. for (i = 0; i < 12; i++) {
  14820. out[i] = get$1(format, i, field, 'month');
  14821. }
  14822. return out;
  14823. }
  14824. // ()
  14825. // (5)
  14826. // (fmt, 5)
  14827. // (fmt)
  14828. // (true)
  14829. // (true, 5)
  14830. // (true, fmt, 5)
  14831. // (true, fmt)
  14832. function listWeekdaysImpl (localeSorted, format, index, field) {
  14833. if (typeof localeSorted === 'boolean') {
  14834. if (isNumber(format)) {
  14835. index = format;
  14836. format = undefined;
  14837. }
  14838. format = format || '';
  14839. } else {
  14840. format = localeSorted;
  14841. index = format;
  14842. localeSorted = false;
  14843. if (isNumber(format)) {
  14844. index = format;
  14845. format = undefined;
  14846. }
  14847. format = format || '';
  14848. }
  14849. var locale = getLocale(),
  14850. shift = localeSorted ? locale._week.dow : 0;
  14851. if (index != null) {
  14852. return get$1(format, (index + shift) % 7, field, 'day');
  14853. }
  14854. var i;
  14855. var out = [];
  14856. for (i = 0; i < 7; i++) {
  14857. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  14858. }
  14859. return out;
  14860. }
  14861. function listMonths (format, index) {
  14862. return listMonthsImpl(format, index, 'months');
  14863. }
  14864. function listMonthsShort (format, index) {
  14865. return listMonthsImpl(format, index, 'monthsShort');
  14866. }
  14867. function listWeekdays (localeSorted, format, index) {
  14868. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  14869. }
  14870. function listWeekdaysShort (localeSorted, format, index) {
  14871. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  14872. }
  14873. function listWeekdaysMin (localeSorted, format, index) {
  14874. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  14875. }
  14876. getSetGlobalLocale('en', {
  14877. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  14878. ordinal : function (number) {
  14879. var b = number % 10,
  14880. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  14881. (b === 1) ? 'st' :
  14882. (b === 2) ? 'nd' :
  14883. (b === 3) ? 'rd' : 'th';
  14884. return number + output;
  14885. }
  14886. });
  14887. // Side effect imports
  14888. hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
  14889. hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
  14890. var mathAbs = Math.abs;
  14891. function abs () {
  14892. var data = this._data;
  14893. this._milliseconds = mathAbs(this._milliseconds);
  14894. this._days = mathAbs(this._days);
  14895. this._months = mathAbs(this._months);
  14896. data.milliseconds = mathAbs(data.milliseconds);
  14897. data.seconds = mathAbs(data.seconds);
  14898. data.minutes = mathAbs(data.minutes);
  14899. data.hours = mathAbs(data.hours);
  14900. data.months = mathAbs(data.months);
  14901. data.years = mathAbs(data.years);
  14902. return this;
  14903. }
  14904. function addSubtract$1 (duration, input, value, direction) {
  14905. var other = createDuration(input, value);
  14906. duration._milliseconds += direction * other._milliseconds;
  14907. duration._days += direction * other._days;
  14908. duration._months += direction * other._months;
  14909. return duration._bubble();
  14910. }
  14911. // supports only 2.0-style add(1, 's') or add(duration)
  14912. function add$1 (input, value) {
  14913. return addSubtract$1(this, input, value, 1);
  14914. }
  14915. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  14916. function subtract$1 (input, value) {
  14917. return addSubtract$1(this, input, value, -1);
  14918. }
  14919. function absCeil (number) {
  14920. if (number < 0) {
  14921. return Math.floor(number);
  14922. } else {
  14923. return Math.ceil(number);
  14924. }
  14925. }
  14926. function bubble () {
  14927. var milliseconds = this._milliseconds;
  14928. var days = this._days;
  14929. var months = this._months;
  14930. var data = this._data;
  14931. var seconds, minutes, hours, years, monthsFromDays;
  14932. // if we have a mix of positive and negative values, bubble down first
  14933. // check: https://github.com/moment/moment/issues/2166
  14934. if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
  14935. (milliseconds <= 0 && days <= 0 && months <= 0))) {
  14936. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  14937. days = 0;
  14938. months = 0;
  14939. }
  14940. // The following code bubbles up values, see the tests for
  14941. // examples of what that means.
  14942. data.milliseconds = milliseconds % 1000;
  14943. seconds = absFloor(milliseconds / 1000);
  14944. data.seconds = seconds % 60;
  14945. minutes = absFloor(seconds / 60);
  14946. data.minutes = minutes % 60;
  14947. hours = absFloor(minutes / 60);
  14948. data.hours = hours % 24;
  14949. days += absFloor(hours / 24);
  14950. // convert days to months
  14951. monthsFromDays = absFloor(daysToMonths(days));
  14952. months += monthsFromDays;
  14953. days -= absCeil(monthsToDays(monthsFromDays));
  14954. // 12 months -> 1 year
  14955. years = absFloor(months / 12);
  14956. months %= 12;
  14957. data.days = days;
  14958. data.months = months;
  14959. data.years = years;
  14960. return this;
  14961. }
  14962. function daysToMonths (days) {
  14963. // 400 years have 146097 days (taking into account leap year rules)
  14964. // 400 years have 12 months === 4800
  14965. return days * 4800 / 146097;
  14966. }
  14967. function monthsToDays (months) {
  14968. // the reverse of daysToMonths
  14969. return months * 146097 / 4800;
  14970. }
  14971. function as (units) {
  14972. if (!this.isValid()) {
  14973. return NaN;
  14974. }
  14975. var days;
  14976. var months;
  14977. var milliseconds = this._milliseconds;
  14978. units = normalizeUnits(units);
  14979. if (units === 'month' || units === 'quarter' || units === 'year') {
  14980. days = this._days + milliseconds / 864e5;
  14981. months = this._months + daysToMonths(days);
  14982. switch (units) {
  14983. case 'month': return months;
  14984. case 'quarter': return months / 3;
  14985. case 'year': return months / 12;
  14986. }
  14987. } else {
  14988. // handle milliseconds separately because of floating point math errors (issue #1867)
  14989. days = this._days + Math.round(monthsToDays(this._months));
  14990. switch (units) {
  14991. case 'week' : return days / 7 + milliseconds / 6048e5;
  14992. case 'day' : return days + milliseconds / 864e5;
  14993. case 'hour' : return days * 24 + milliseconds / 36e5;
  14994. case 'minute' : return days * 1440 + milliseconds / 6e4;
  14995. case 'second' : return days * 86400 + milliseconds / 1000;
  14996. // Math.floor prevents floating point math errors here
  14997. case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
  14998. default: throw new Error('Unknown unit ' + units);
  14999. }
  15000. }
  15001. }
  15002. // TODO: Use this.as('ms')?
  15003. function valueOf$1 () {
  15004. if (!this.isValid()) {
  15005. return NaN;
  15006. }
  15007. return (
  15008. this._milliseconds +
  15009. this._days * 864e5 +
  15010. (this._months % 12) * 2592e6 +
  15011. toInt(this._months / 12) * 31536e6
  15012. );
  15013. }
  15014. function makeAs (alias) {
  15015. return function () {
  15016. return this.as(alias);
  15017. };
  15018. }
  15019. var asMilliseconds = makeAs('ms');
  15020. var asSeconds = makeAs('s');
  15021. var asMinutes = makeAs('m');
  15022. var asHours = makeAs('h');
  15023. var asDays = makeAs('d');
  15024. var asWeeks = makeAs('w');
  15025. var asMonths = makeAs('M');
  15026. var asQuarters = makeAs('Q');
  15027. var asYears = makeAs('y');
  15028. function clone$1 () {
  15029. return createDuration(this);
  15030. }
  15031. function get$2 (units) {
  15032. units = normalizeUnits(units);
  15033. return this.isValid() ? this[units + 's']() : NaN;
  15034. }
  15035. function makeGetter(name) {
  15036. return function () {
  15037. return this.isValid() ? this._data[name] : NaN;
  15038. };
  15039. }
  15040. var milliseconds = makeGetter('milliseconds');
  15041. var seconds = makeGetter('seconds');
  15042. var minutes = makeGetter('minutes');
  15043. var hours = makeGetter('hours');
  15044. var days = makeGetter('days');
  15045. var months = makeGetter('months');
  15046. var years = makeGetter('years');
  15047. function weeks () {
  15048. return absFloor(this.days() / 7);
  15049. }
  15050. var round = Math.round;
  15051. var thresholds = {
  15052. ss: 44, // a few seconds to seconds
  15053. s : 45, // seconds to minute
  15054. m : 45, // minutes to hour
  15055. h : 22, // hours to day
  15056. d : 26, // days to month
  15057. M : 11 // months to year
  15058. };
  15059. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  15060. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  15061. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  15062. }
  15063. function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
  15064. var duration = createDuration(posNegDuration).abs();
  15065. var seconds = round(duration.as('s'));
  15066. var minutes = round(duration.as('m'));
  15067. var hours = round(duration.as('h'));
  15068. var days = round(duration.as('d'));
  15069. var months = round(duration.as('M'));
  15070. var years = round(duration.as('y'));
  15071. var a = seconds <= thresholds.ss && ['s', seconds] ||
  15072. seconds < thresholds.s && ['ss', seconds] ||
  15073. minutes <= 1 && ['m'] ||
  15074. minutes < thresholds.m && ['mm', minutes] ||
  15075. hours <= 1 && ['h'] ||
  15076. hours < thresholds.h && ['hh', hours] ||
  15077. days <= 1 && ['d'] ||
  15078. days < thresholds.d && ['dd', days] ||
  15079. months <= 1 && ['M'] ||
  15080. months < thresholds.M && ['MM', months] ||
  15081. years <= 1 && ['y'] || ['yy', years];
  15082. a[2] = withoutSuffix;
  15083. a[3] = +posNegDuration > 0;
  15084. a[4] = locale;
  15085. return substituteTimeAgo.apply(null, a);
  15086. }
  15087. // This function allows you to set the rounding function for relative time strings
  15088. function getSetRelativeTimeRounding (roundingFunction) {
  15089. if (roundingFunction === undefined) {
  15090. return round;
  15091. }
  15092. if (typeof(roundingFunction) === 'function') {
  15093. round = roundingFunction;
  15094. return true;
  15095. }
  15096. return false;
  15097. }
  15098. // This function allows you to set a threshold for relative time strings
  15099. function getSetRelativeTimeThreshold (threshold, limit) {
  15100. if (thresholds[threshold] === undefined) {
  15101. return false;
  15102. }
  15103. if (limit === undefined) {
  15104. return thresholds[threshold];
  15105. }
  15106. thresholds[threshold] = limit;
  15107. if (threshold === 's') {
  15108. thresholds.ss = limit - 1;
  15109. }
  15110. return true;
  15111. }
  15112. function humanize (withSuffix) {
  15113. if (!this.isValid()) {
  15114. return this.localeData().invalidDate();
  15115. }
  15116. var locale = this.localeData();
  15117. var output = relativeTime$1(this, !withSuffix, locale);
  15118. if (withSuffix) {
  15119. output = locale.pastFuture(+this, output);
  15120. }
  15121. return locale.postformat(output);
  15122. }
  15123. var abs$1 = Math.abs;
  15124. function sign(x) {
  15125. return ((x > 0) - (x < 0)) || +x;
  15126. }
  15127. function toISOString$1() {
  15128. // for ISO strings we do not use the normal bubbling rules:
  15129. // * milliseconds bubble up until they become hours
  15130. // * days do not bubble at all
  15131. // * months bubble up until they become years
  15132. // This is because there is no context-free conversion between hours and days
  15133. // (think of clock changes)
  15134. // and also not between days and months (28-31 days per month)
  15135. if (!this.isValid()) {
  15136. return this.localeData().invalidDate();
  15137. }
  15138. var seconds = abs$1(this._milliseconds) / 1000;
  15139. var days = abs$1(this._days);
  15140. var months = abs$1(this._months);
  15141. var minutes, hours, years;
  15142. // 3600 seconds -> 60 minutes -> 1 hour
  15143. minutes = absFloor(seconds / 60);
  15144. hours = absFloor(minutes / 60);
  15145. seconds %= 60;
  15146. minutes %= 60;
  15147. // 12 months -> 1 year
  15148. years = absFloor(months / 12);
  15149. months %= 12;
  15150. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  15151. var Y = years;
  15152. var M = months;
  15153. var D = days;
  15154. var h = hours;
  15155. var m = minutes;
  15156. var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  15157. var total = this.asSeconds();
  15158. if (!total) {
  15159. // this is the same as C#'s (Noda) and python (isodate)...
  15160. // but not other JS (goog.date)
  15161. return 'P0D';
  15162. }
  15163. var totalSign = total < 0 ? '-' : '';
  15164. var ymSign = sign(this._months) !== sign(total) ? '-' : '';
  15165. var daysSign = sign(this._days) !== sign(total) ? '-' : '';
  15166. var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  15167. return totalSign + 'P' +
  15168. (Y ? ymSign + Y + 'Y' : '') +
  15169. (M ? ymSign + M + 'M' : '') +
  15170. (D ? daysSign + D + 'D' : '') +
  15171. ((h || m || s) ? 'T' : '') +
  15172. (h ? hmsSign + h + 'H' : '') +
  15173. (m ? hmsSign + m + 'M' : '') +
  15174. (s ? hmsSign + s + 'S' : '');
  15175. }
  15176. var proto$2 = Duration.prototype;
  15177. proto$2.isValid = isValid$1;
  15178. proto$2.abs = abs;
  15179. proto$2.add = add$1;
  15180. proto$2.subtract = subtract$1;
  15181. proto$2.as = as;
  15182. proto$2.asMilliseconds = asMilliseconds;
  15183. proto$2.asSeconds = asSeconds;
  15184. proto$2.asMinutes = asMinutes;
  15185. proto$2.asHours = asHours;
  15186. proto$2.asDays = asDays;
  15187. proto$2.asWeeks = asWeeks;
  15188. proto$2.asMonths = asMonths;
  15189. proto$2.asQuarters = asQuarters;
  15190. proto$2.asYears = asYears;
  15191. proto$2.valueOf = valueOf$1;
  15192. proto$2._bubble = bubble;
  15193. proto$2.clone = clone$1;
  15194. proto$2.get = get$2;
  15195. proto$2.milliseconds = milliseconds;
  15196. proto$2.seconds = seconds;
  15197. proto$2.minutes = minutes;
  15198. proto$2.hours = hours;
  15199. proto$2.days = days;
  15200. proto$2.weeks = weeks;
  15201. proto$2.months = months;
  15202. proto$2.years = years;
  15203. proto$2.humanize = humanize;
  15204. proto$2.toISOString = toISOString$1;
  15205. proto$2.toString = toISOString$1;
  15206. proto$2.toJSON = toISOString$1;
  15207. proto$2.locale = locale;
  15208. proto$2.localeData = localeData;
  15209. proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
  15210. proto$2.lang = lang;
  15211. // Side effect imports
  15212. // FORMATTING
  15213. addFormatToken('X', 0, 0, 'unix');
  15214. addFormatToken('x', 0, 0, 'valueOf');
  15215. // PARSING
  15216. addRegexToken('x', matchSigned);
  15217. addRegexToken('X', matchTimestamp);
  15218. addParseToken('X', function (input, array, config) {
  15219. config._d = new Date(parseFloat(input, 10) * 1000);
  15220. });
  15221. addParseToken('x', function (input, array, config) {
  15222. config._d = new Date(toInt(input));
  15223. });
  15224. // Side effect imports
  15225. hooks.version = '2.24.0';
  15226. setHookCallback(createLocal);
  15227. hooks.fn = proto;
  15228. hooks.min = min;
  15229. hooks.max = max;
  15230. hooks.now = now;
  15231. hooks.utc = createUTC;
  15232. hooks.unix = createUnix;
  15233. hooks.months = listMonths;
  15234. hooks.isDate = isDate;
  15235. hooks.locale = getSetGlobalLocale;
  15236. hooks.invalid = createInvalid;
  15237. hooks.duration = createDuration;
  15238. hooks.isMoment = isMoment;
  15239. hooks.weekdays = listWeekdays;
  15240. hooks.parseZone = createInZone;
  15241. hooks.localeData = getLocale;
  15242. hooks.isDuration = isDuration;
  15243. hooks.monthsShort = listMonthsShort;
  15244. hooks.weekdaysMin = listWeekdaysMin;
  15245. hooks.defineLocale = defineLocale;
  15246. hooks.updateLocale = updateLocale;
  15247. hooks.locales = listLocales;
  15248. hooks.weekdaysShort = listWeekdaysShort;
  15249. hooks.normalizeUnits = normalizeUnits;
  15250. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  15251. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  15252. hooks.calendarFormat = getCalendarFormat;
  15253. hooks.prototype = proto;
  15254. // currently HTML5 input type only supports 24-hour formats
  15255. hooks.HTML5_FMT = {
  15256. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  15257. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  15258. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  15259. DATE: 'YYYY-MM-DD', // <input type="date" />
  15260. TIME: 'HH:mm', // <input type="time" />
  15261. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  15262. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  15263. WEEK: 'GGGG-[W]WW', // <input type="week" />
  15264. MONTH: 'YYYY-MM' // <input type="month" />
  15265. };
  15266. return hooks;
  15267. })));
  15268. });
  15269. var FORMATS = {
  15270. datetime: 'MMM D, YYYY, h:mm:ss a',
  15271. millisecond: 'h:mm:ss.SSS a',
  15272. second: 'h:mm:ss a',
  15273. minute: 'h:mm a',
  15274. hour: 'hA',
  15275. day: 'MMM D',
  15276. week: 'll',
  15277. month: 'MMM YYYY',
  15278. quarter: '[Q]Q - YYYY',
  15279. year: 'YYYY'
  15280. };
  15281. core_adapters._date.override(typeof moment === 'function' ? {
  15282. _id: 'moment', // DEBUG ONLY
  15283. formats: function() {
  15284. return FORMATS;
  15285. },
  15286. parse: function(value, format) {
  15287. if (typeof value === 'string' && typeof format === 'string') {
  15288. value = moment(value, format);
  15289. } else if (!(value instanceof moment)) {
  15290. value = moment(value);
  15291. }
  15292. return value.isValid() ? value.valueOf() : null;
  15293. },
  15294. format: function(time, format) {
  15295. return moment(time).format(format);
  15296. },
  15297. add: function(time, amount, unit) {
  15298. return moment(time).add(amount, unit).valueOf();
  15299. },
  15300. diff: function(max, min, unit) {
  15301. return moment.duration(moment(max).diff(moment(min))).as(unit);
  15302. },
  15303. startOf: function(time, unit, weekday) {
  15304. time = moment(time);
  15305. if (unit === 'isoWeek') {
  15306. return time.isoWeekday(weekday).valueOf();
  15307. }
  15308. return time.startOf(unit).valueOf();
  15309. },
  15310. endOf: function(time, unit) {
  15311. return moment(time).endOf(unit).valueOf();
  15312. },
  15313. // DEPRECATIONS
  15314. /**
  15315. * Provided for backward compatibility with scale.getValueForPixel().
  15316. * @deprecated since version 2.8.0
  15317. * @todo remove at version 3
  15318. * @private
  15319. */
  15320. _create: function(time) {
  15321. return moment(time);
  15322. },
  15323. } : {});
  15324. core_defaults._set('global', {
  15325. plugins: {
  15326. filler: {
  15327. propagate: true
  15328. }
  15329. }
  15330. });
  15331. var mappers = {
  15332. dataset: function(source) {
  15333. var index = source.fill;
  15334. var chart = source.chart;
  15335. var meta = chart.getDatasetMeta(index);
  15336. var visible = meta && chart.isDatasetVisible(index);
  15337. var points = (visible && meta.dataset._children) || [];
  15338. var length = points.length || 0;
  15339. return !length ? null : function(point, i) {
  15340. return (i < length && points[i]._view) || null;
  15341. };
  15342. },
  15343. boundary: function(source) {
  15344. var boundary = source.boundary;
  15345. var x = boundary ? boundary.x : null;
  15346. var y = boundary ? boundary.y : null;
  15347. return function(point) {
  15348. return {
  15349. x: x === null ? point.x : x,
  15350. y: y === null ? point.y : y,
  15351. };
  15352. };
  15353. }
  15354. };
  15355. // @todo if (fill[0] === '#')
  15356. function decodeFill(el, index, count) {
  15357. var model = el._model || {};
  15358. var fill = model.fill;
  15359. var target;
  15360. if (fill === undefined) {
  15361. fill = !!model.backgroundColor;
  15362. }
  15363. if (fill === false || fill === null) {
  15364. return false;
  15365. }
  15366. if (fill === true) {
  15367. return 'origin';
  15368. }
  15369. target = parseFloat(fill, 10);
  15370. if (isFinite(target) && Math.floor(target) === target) {
  15371. if (fill[0] === '-' || fill[0] === '+') {
  15372. target = index + target;
  15373. }
  15374. if (target === index || target < 0 || target >= count) {
  15375. return false;
  15376. }
  15377. return target;
  15378. }
  15379. switch (fill) {
  15380. // compatibility
  15381. case 'bottom':
  15382. return 'start';
  15383. case 'top':
  15384. return 'end';
  15385. case 'zero':
  15386. return 'origin';
  15387. // supported boundaries
  15388. case 'origin':
  15389. case 'start':
  15390. case 'end':
  15391. return fill;
  15392. // invalid fill values
  15393. default:
  15394. return false;
  15395. }
  15396. }
  15397. function computeBoundary(source) {
  15398. var model = source.el._model || {};
  15399. var scale = source.el._scale || {};
  15400. var fill = source.fill;
  15401. var target = null;
  15402. var horizontal;
  15403. if (isFinite(fill)) {
  15404. return null;
  15405. }
  15406. // Backward compatibility: until v3, we still need to support boundary values set on
  15407. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  15408. // controllers might still use it (e.g. the Smith chart).
  15409. if (fill === 'start') {
  15410. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  15411. } else if (fill === 'end') {
  15412. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  15413. } else if (model.scaleZero !== undefined) {
  15414. target = model.scaleZero;
  15415. } else if (scale.getBasePosition) {
  15416. target = scale.getBasePosition();
  15417. } else if (scale.getBasePixel) {
  15418. target = scale.getBasePixel();
  15419. }
  15420. if (target !== undefined && target !== null) {
  15421. if (target.x !== undefined && target.y !== undefined) {
  15422. return target;
  15423. }
  15424. if (helpers$1.isFinite(target)) {
  15425. horizontal = scale.isHorizontal();
  15426. return {
  15427. x: horizontal ? target : null,
  15428. y: horizontal ? null : target
  15429. };
  15430. }
  15431. }
  15432. return null;
  15433. }
  15434. function resolveTarget(sources, index, propagate) {
  15435. var source = sources[index];
  15436. var fill = source.fill;
  15437. var visited = [index];
  15438. var target;
  15439. if (!propagate) {
  15440. return fill;
  15441. }
  15442. while (fill !== false && visited.indexOf(fill) === -1) {
  15443. if (!isFinite(fill)) {
  15444. return fill;
  15445. }
  15446. target = sources[fill];
  15447. if (!target) {
  15448. return false;
  15449. }
  15450. if (target.visible) {
  15451. return fill;
  15452. }
  15453. visited.push(fill);
  15454. fill = target.fill;
  15455. }
  15456. return false;
  15457. }
  15458. function createMapper(source) {
  15459. var fill = source.fill;
  15460. var type = 'dataset';
  15461. if (fill === false) {
  15462. return null;
  15463. }
  15464. if (!isFinite(fill)) {
  15465. type = 'boundary';
  15466. }
  15467. return mappers[type](source);
  15468. }
  15469. function isDrawable(point) {
  15470. return point && !point.skip;
  15471. }
  15472. function drawArea(ctx, curve0, curve1, len0, len1) {
  15473. var i;
  15474. if (!len0 || !len1) {
  15475. return;
  15476. }
  15477. // building first area curve (normal)
  15478. ctx.moveTo(curve0[0].x, curve0[0].y);
  15479. for (i = 1; i < len0; ++i) {
  15480. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  15481. }
  15482. // joining the two area curves
  15483. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  15484. // building opposite area curve (reverse)
  15485. for (i = len1 - 1; i > 0; --i) {
  15486. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  15487. }
  15488. }
  15489. function doFill(ctx, points, mapper, view, color, loop) {
  15490. var count = points.length;
  15491. var span = view.spanGaps;
  15492. var curve0 = [];
  15493. var curve1 = [];
  15494. var len0 = 0;
  15495. var len1 = 0;
  15496. var i, ilen, index, p0, p1, d0, d1;
  15497. ctx.beginPath();
  15498. for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {
  15499. index = i % count;
  15500. p0 = points[index]._view;
  15501. p1 = mapper(p0, index, view);
  15502. d0 = isDrawable(p0);
  15503. d1 = isDrawable(p1);
  15504. if (d0 && d1) {
  15505. len0 = curve0.push(p0);
  15506. len1 = curve1.push(p1);
  15507. } else if (len0 && len1) {
  15508. if (!span) {
  15509. drawArea(ctx, curve0, curve1, len0, len1);
  15510. len0 = len1 = 0;
  15511. curve0 = [];
  15512. curve1 = [];
  15513. } else {
  15514. if (d0) {
  15515. curve0.push(p0);
  15516. }
  15517. if (d1) {
  15518. curve1.push(p1);
  15519. }
  15520. }
  15521. }
  15522. }
  15523. drawArea(ctx, curve0, curve1, len0, len1);
  15524. ctx.closePath();
  15525. ctx.fillStyle = color;
  15526. ctx.fill();
  15527. }
  15528. var plugin_filler = {
  15529. id: 'filler',
  15530. afterDatasetsUpdate: function(chart, options) {
  15531. var count = (chart.data.datasets || []).length;
  15532. var propagate = options.propagate;
  15533. var sources = [];
  15534. var meta, i, el, source;
  15535. for (i = 0; i < count; ++i) {
  15536. meta = chart.getDatasetMeta(i);
  15537. el = meta.dataset;
  15538. source = null;
  15539. if (el && el._model && el instanceof elements.Line) {
  15540. source = {
  15541. visible: chart.isDatasetVisible(i),
  15542. fill: decodeFill(el, i, count),
  15543. chart: chart,
  15544. el: el
  15545. };
  15546. }
  15547. meta.$filler = source;
  15548. sources.push(source);
  15549. }
  15550. for (i = 0; i < count; ++i) {
  15551. source = sources[i];
  15552. if (!source) {
  15553. continue;
  15554. }
  15555. source.fill = resolveTarget(sources, i, propagate);
  15556. source.boundary = computeBoundary(source);
  15557. source.mapper = createMapper(source);
  15558. }
  15559. },
  15560. beforeDatasetDraw: function(chart, args) {
  15561. var meta = args.meta.$filler;
  15562. if (!meta) {
  15563. return;
  15564. }
  15565. var ctx = chart.ctx;
  15566. var el = meta.el;
  15567. var view = el._view;
  15568. var points = el._children || [];
  15569. var mapper = meta.mapper;
  15570. var color = view.backgroundColor || core_defaults.global.defaultColor;
  15571. if (mapper && color && points.length) {
  15572. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  15573. doFill(ctx, points, mapper, view, color, el._loop);
  15574. helpers$1.canvas.unclipArea(ctx);
  15575. }
  15576. }
  15577. };
  15578. var noop$1 = helpers$1.noop;
  15579. var valueOrDefault$d = helpers$1.valueOrDefault;
  15580. core_defaults._set('global', {
  15581. legend: {
  15582. display: true,
  15583. position: 'top',
  15584. fullWidth: true,
  15585. reverse: false,
  15586. weight: 1000,
  15587. // a callback that will handle
  15588. onClick: function(e, legendItem) {
  15589. var index = legendItem.datasetIndex;
  15590. var ci = this.chart;
  15591. var meta = ci.getDatasetMeta(index);
  15592. // See controller.isDatasetVisible comment
  15593. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  15594. // We hid a dataset ... rerender the chart
  15595. ci.update();
  15596. },
  15597. onHover: null,
  15598. onLeave: null,
  15599. labels: {
  15600. boxWidth: 40,
  15601. padding: 10,
  15602. // Generates labels shown in the legend
  15603. // Valid properties to return:
  15604. // text : text to display
  15605. // fillStyle : fill of coloured box
  15606. // strokeStyle: stroke of coloured box
  15607. // hidden : if this legend item refers to a hidden item
  15608. // lineCap : cap style for line
  15609. // lineDash
  15610. // lineDashOffset :
  15611. // lineJoin :
  15612. // lineWidth :
  15613. generateLabels: function(chart) {
  15614. var data = chart.data;
  15615. return helpers$1.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
  15616. return {
  15617. text: dataset.label,
  15618. fillStyle: (!helpers$1.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
  15619. hidden: !chart.isDatasetVisible(i),
  15620. lineCap: dataset.borderCapStyle,
  15621. lineDash: dataset.borderDash,
  15622. lineDashOffset: dataset.borderDashOffset,
  15623. lineJoin: dataset.borderJoinStyle,
  15624. lineWidth: dataset.borderWidth,
  15625. strokeStyle: dataset.borderColor,
  15626. pointStyle: dataset.pointStyle,
  15627. // Below is extra data used for toggling the datasets
  15628. datasetIndex: i
  15629. };
  15630. }, this) : [];
  15631. }
  15632. }
  15633. },
  15634. legendCallback: function(chart) {
  15635. var text = [];
  15636. text.push('<ul class="' + chart.id + '-legend">');
  15637. for (var i = 0; i < chart.data.datasets.length; i++) {
  15638. text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
  15639. if (chart.data.datasets[i].label) {
  15640. text.push(chart.data.datasets[i].label);
  15641. }
  15642. text.push('</li>');
  15643. }
  15644. text.push('</ul>');
  15645. return text.join('');
  15646. }
  15647. });
  15648. /**
  15649. * Helper function to get the box width based on the usePointStyle option
  15650. * @param {object} labelopts - the label options on the legend
  15651. * @param {number} fontSize - the label font size
  15652. * @return {number} width of the color box area
  15653. */
  15654. function getBoxWidth(labelOpts, fontSize) {
  15655. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  15656. fontSize :
  15657. labelOpts.boxWidth;
  15658. }
  15659. /**
  15660. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  15661. */
  15662. var Legend = core_element.extend({
  15663. initialize: function(config) {
  15664. helpers$1.extend(this, config);
  15665. // Contains hit boxes for each dataset (in dataset order)
  15666. this.legendHitBoxes = [];
  15667. /**
  15668. * @private
  15669. */
  15670. this._hoveredItem = null;
  15671. // Are we in doughnut mode which has a different data type
  15672. this.doughnutMode = false;
  15673. },
  15674. // These methods are ordered by lifecycle. Utilities then follow.
  15675. // Any function defined here is inherited by all legend types.
  15676. // Any function can be extended by the legend type
  15677. beforeUpdate: noop$1,
  15678. update: function(maxWidth, maxHeight, margins) {
  15679. var me = this;
  15680. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  15681. me.beforeUpdate();
  15682. // Absorb the master measurements
  15683. me.maxWidth = maxWidth;
  15684. me.maxHeight = maxHeight;
  15685. me.margins = margins;
  15686. // Dimensions
  15687. me.beforeSetDimensions();
  15688. me.setDimensions();
  15689. me.afterSetDimensions();
  15690. // Labels
  15691. me.beforeBuildLabels();
  15692. me.buildLabels();
  15693. me.afterBuildLabels();
  15694. // Fit
  15695. me.beforeFit();
  15696. me.fit();
  15697. me.afterFit();
  15698. //
  15699. me.afterUpdate();
  15700. return me.minSize;
  15701. },
  15702. afterUpdate: noop$1,
  15703. //
  15704. beforeSetDimensions: noop$1,
  15705. setDimensions: function() {
  15706. var me = this;
  15707. // Set the unconstrained dimension before label rotation
  15708. if (me.isHorizontal()) {
  15709. // Reset position before calculating rotation
  15710. me.width = me.maxWidth;
  15711. me.left = 0;
  15712. me.right = me.width;
  15713. } else {
  15714. me.height = me.maxHeight;
  15715. // Reset position before calculating rotation
  15716. me.top = 0;
  15717. me.bottom = me.height;
  15718. }
  15719. // Reset padding
  15720. me.paddingLeft = 0;
  15721. me.paddingTop = 0;
  15722. me.paddingRight = 0;
  15723. me.paddingBottom = 0;
  15724. // Reset minSize
  15725. me.minSize = {
  15726. width: 0,
  15727. height: 0
  15728. };
  15729. },
  15730. afterSetDimensions: noop$1,
  15731. //
  15732. beforeBuildLabels: noop$1,
  15733. buildLabels: function() {
  15734. var me = this;
  15735. var labelOpts = me.options.labels || {};
  15736. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  15737. if (labelOpts.filter) {
  15738. legendItems = legendItems.filter(function(item) {
  15739. return labelOpts.filter(item, me.chart.data);
  15740. });
  15741. }
  15742. if (me.options.reverse) {
  15743. legendItems.reverse();
  15744. }
  15745. me.legendItems = legendItems;
  15746. },
  15747. afterBuildLabels: noop$1,
  15748. //
  15749. beforeFit: noop$1,
  15750. fit: function() {
  15751. var me = this;
  15752. var opts = me.options;
  15753. var labelOpts = opts.labels;
  15754. var display = opts.display;
  15755. var ctx = me.ctx;
  15756. var labelFont = helpers$1.options._parseFont(labelOpts);
  15757. var fontSize = labelFont.size;
  15758. // Reset hit boxes
  15759. var hitboxes = me.legendHitBoxes = [];
  15760. var minSize = me.minSize;
  15761. var isHorizontal = me.isHorizontal();
  15762. if (isHorizontal) {
  15763. minSize.width = me.maxWidth; // fill all the width
  15764. minSize.height = display ? 10 : 0;
  15765. } else {
  15766. minSize.width = display ? 10 : 0;
  15767. minSize.height = me.maxHeight; // fill all the height
  15768. }
  15769. // Increase sizes here
  15770. if (display) {
  15771. ctx.font = labelFont.string;
  15772. if (isHorizontal) {
  15773. // Labels
  15774. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  15775. var lineWidths = me.lineWidths = [0];
  15776. var totalHeight = 0;
  15777. ctx.textAlign = 'left';
  15778. ctx.textBaseline = 'top';
  15779. helpers$1.each(me.legendItems, function(legendItem, i) {
  15780. var boxWidth = getBoxWidth(labelOpts, fontSize);
  15781. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  15782. if (i === 0 || lineWidths[lineWidths.length - 1] + width + labelOpts.padding > minSize.width) {
  15783. totalHeight += fontSize + labelOpts.padding;
  15784. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = labelOpts.padding;
  15785. }
  15786. // Store the hitbox width and height here. Final position will be updated in `draw`
  15787. hitboxes[i] = {
  15788. left: 0,
  15789. top: 0,
  15790. width: width,
  15791. height: fontSize
  15792. };
  15793. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  15794. });
  15795. minSize.height += totalHeight;
  15796. } else {
  15797. var vPadding = labelOpts.padding;
  15798. var columnWidths = me.columnWidths = [];
  15799. var totalWidth = labelOpts.padding;
  15800. var currentColWidth = 0;
  15801. var currentColHeight = 0;
  15802. var itemHeight = fontSize + vPadding;
  15803. helpers$1.each(me.legendItems, function(legendItem, i) {
  15804. var boxWidth = getBoxWidth(labelOpts, fontSize);
  15805. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  15806. // If too tall, go to new column
  15807. if (i > 0 && currentColHeight + itemHeight > minSize.height - vPadding) {
  15808. totalWidth += currentColWidth + labelOpts.padding;
  15809. columnWidths.push(currentColWidth); // previous column width
  15810. currentColWidth = 0;
  15811. currentColHeight = 0;
  15812. }
  15813. // Get max width
  15814. currentColWidth = Math.max(currentColWidth, itemWidth);
  15815. currentColHeight += itemHeight;
  15816. // Store the hitbox width and height here. Final position will be updated in `draw`
  15817. hitboxes[i] = {
  15818. left: 0,
  15819. top: 0,
  15820. width: itemWidth,
  15821. height: fontSize
  15822. };
  15823. });
  15824. totalWidth += currentColWidth;
  15825. columnWidths.push(currentColWidth);
  15826. minSize.width += totalWidth;
  15827. }
  15828. }
  15829. me.width = minSize.width;
  15830. me.height = minSize.height;
  15831. },
  15832. afterFit: noop$1,
  15833. // Shared Methods
  15834. isHorizontal: function() {
  15835. return this.options.position === 'top' || this.options.position === 'bottom';
  15836. },
  15837. // Actually draw the legend on the canvas
  15838. draw: function() {
  15839. var me = this;
  15840. var opts = me.options;
  15841. var labelOpts = opts.labels;
  15842. var globalDefaults = core_defaults.global;
  15843. var defaultColor = globalDefaults.defaultColor;
  15844. var lineDefault = globalDefaults.elements.line;
  15845. var legendWidth = me.width;
  15846. var lineWidths = me.lineWidths;
  15847. if (opts.display) {
  15848. var ctx = me.ctx;
  15849. var fontColor = valueOrDefault$d(labelOpts.fontColor, globalDefaults.defaultFontColor);
  15850. var labelFont = helpers$1.options._parseFont(labelOpts);
  15851. var fontSize = labelFont.size;
  15852. var cursor;
  15853. // Canvas setup
  15854. ctx.textAlign = 'left';
  15855. ctx.textBaseline = 'middle';
  15856. ctx.lineWidth = 0.5;
  15857. ctx.strokeStyle = fontColor; // for strikethrough effect
  15858. ctx.fillStyle = fontColor; // render in correct colour
  15859. ctx.font = labelFont.string;
  15860. var boxWidth = getBoxWidth(labelOpts, fontSize);
  15861. var hitboxes = me.legendHitBoxes;
  15862. // current position
  15863. var drawLegendBox = function(x, y, legendItem) {
  15864. if (isNaN(boxWidth) || boxWidth <= 0) {
  15865. return;
  15866. }
  15867. // Set the ctx for the box
  15868. ctx.save();
  15869. var lineWidth = valueOrDefault$d(legendItem.lineWidth, lineDefault.borderWidth);
  15870. ctx.fillStyle = valueOrDefault$d(legendItem.fillStyle, defaultColor);
  15871. ctx.lineCap = valueOrDefault$d(legendItem.lineCap, lineDefault.borderCapStyle);
  15872. ctx.lineDashOffset = valueOrDefault$d(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  15873. ctx.lineJoin = valueOrDefault$d(legendItem.lineJoin, lineDefault.borderJoinStyle);
  15874. ctx.lineWidth = lineWidth;
  15875. ctx.strokeStyle = valueOrDefault$d(legendItem.strokeStyle, defaultColor);
  15876. if (ctx.setLineDash) {
  15877. // IE 9 and 10 do not support line dash
  15878. ctx.setLineDash(valueOrDefault$d(legendItem.lineDash, lineDefault.borderDash));
  15879. }
  15880. if (opts.labels && opts.labels.usePointStyle) {
  15881. // Recalculate x and y for drawPoint() because its expecting
  15882. // x and y to be center of figure (instead of top left)
  15883. var radius = boxWidth * Math.SQRT2 / 2;
  15884. var centerX = x + boxWidth / 2;
  15885. var centerY = y + fontSize / 2;
  15886. // Draw pointStyle as legend symbol
  15887. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
  15888. } else {
  15889. // Draw box as legend symbol
  15890. if (lineWidth !== 0) {
  15891. ctx.strokeRect(x, y, boxWidth, fontSize);
  15892. }
  15893. ctx.fillRect(x, y, boxWidth, fontSize);
  15894. }
  15895. ctx.restore();
  15896. };
  15897. var fillText = function(x, y, legendItem, textWidth) {
  15898. var halfFontSize = fontSize / 2;
  15899. var xLeft = boxWidth + halfFontSize + x;
  15900. var yMiddle = y + halfFontSize;
  15901. ctx.fillText(legendItem.text, xLeft, yMiddle);
  15902. if (legendItem.hidden) {
  15903. // Strikethrough the text if hidden
  15904. ctx.beginPath();
  15905. ctx.lineWidth = 2;
  15906. ctx.moveTo(xLeft, yMiddle);
  15907. ctx.lineTo(xLeft + textWidth, yMiddle);
  15908. ctx.stroke();
  15909. }
  15910. };
  15911. // Horizontal
  15912. var isHorizontal = me.isHorizontal();
  15913. if (isHorizontal) {
  15914. cursor = {
  15915. x: me.left + ((legendWidth - lineWidths[0]) / 2) + labelOpts.padding,
  15916. y: me.top + labelOpts.padding,
  15917. line: 0
  15918. };
  15919. } else {
  15920. cursor = {
  15921. x: me.left + labelOpts.padding,
  15922. y: me.top + labelOpts.padding,
  15923. line: 0
  15924. };
  15925. }
  15926. var itemHeight = fontSize + labelOpts.padding;
  15927. helpers$1.each(me.legendItems, function(legendItem, i) {
  15928. var textWidth = ctx.measureText(legendItem.text).width;
  15929. var width = boxWidth + (fontSize / 2) + textWidth;
  15930. var x = cursor.x;
  15931. var y = cursor.y;
  15932. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  15933. // instead of me.right and me.bottom because me.width and me.height
  15934. // may have been changed since me.minSize was calculated
  15935. if (isHorizontal) {
  15936. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  15937. y = cursor.y += itemHeight;
  15938. cursor.line++;
  15939. x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2) + labelOpts.padding;
  15940. }
  15941. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  15942. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  15943. y = cursor.y = me.top + labelOpts.padding;
  15944. cursor.line++;
  15945. }
  15946. drawLegendBox(x, y, legendItem);
  15947. hitboxes[i].left = x;
  15948. hitboxes[i].top = y;
  15949. // Fill the actual label
  15950. fillText(x, y, legendItem, textWidth);
  15951. if (isHorizontal) {
  15952. cursor.x += width + labelOpts.padding;
  15953. } else {
  15954. cursor.y += itemHeight;
  15955. }
  15956. });
  15957. }
  15958. },
  15959. /**
  15960. * @private
  15961. */
  15962. _getLegendItemAt: function(x, y) {
  15963. var me = this;
  15964. var i, hitBox, lh;
  15965. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  15966. // See if we are touching one of the dataset boxes
  15967. lh = me.legendHitBoxes;
  15968. for (i = 0; i < lh.length; ++i) {
  15969. hitBox = lh[i];
  15970. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  15971. // Touching an element
  15972. return me.legendItems[i];
  15973. }
  15974. }
  15975. }
  15976. return null;
  15977. },
  15978. /**
  15979. * Handle an event
  15980. * @private
  15981. * @param {IEvent} event - The event to handle
  15982. */
  15983. handleEvent: function(e) {
  15984. var me = this;
  15985. var opts = me.options;
  15986. var type = e.type === 'mouseup' ? 'click' : e.type;
  15987. var hoveredItem;
  15988. if (type === 'mousemove') {
  15989. if (!opts.onHover && !opts.onLeave) {
  15990. return;
  15991. }
  15992. } else if (type === 'click') {
  15993. if (!opts.onClick) {
  15994. return;
  15995. }
  15996. } else {
  15997. return;
  15998. }
  15999. // Chart event already has relative position in it
  16000. hoveredItem = me._getLegendItemAt(e.x, e.y);
  16001. if (type === 'click') {
  16002. if (hoveredItem && opts.onClick) {
  16003. // use e.native for backwards compatibility
  16004. opts.onClick.call(me, e.native, hoveredItem);
  16005. }
  16006. } else {
  16007. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  16008. if (me._hoveredItem) {
  16009. opts.onLeave.call(me, e.native, me._hoveredItem);
  16010. }
  16011. me._hoveredItem = hoveredItem;
  16012. }
  16013. if (opts.onHover && hoveredItem) {
  16014. // use e.native for backwards compatibility
  16015. opts.onHover.call(me, e.native, hoveredItem);
  16016. }
  16017. }
  16018. }
  16019. });
  16020. function createNewLegendAndAttach(chart, legendOpts) {
  16021. var legend = new Legend({
  16022. ctx: chart.ctx,
  16023. options: legendOpts,
  16024. chart: chart
  16025. });
  16026. core_layouts.configure(chart, legend, legendOpts);
  16027. core_layouts.addBox(chart, legend);
  16028. chart.legend = legend;
  16029. }
  16030. var plugin_legend = {
  16031. id: 'legend',
  16032. /**
  16033. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  16034. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  16035. * the plugin, which one will be re-exposed in the chart.js file.
  16036. * https://github.com/chartjs/Chart.js/pull/2640
  16037. * @private
  16038. */
  16039. _element: Legend,
  16040. beforeInit: function(chart) {
  16041. var legendOpts = chart.options.legend;
  16042. if (legendOpts) {
  16043. createNewLegendAndAttach(chart, legendOpts);
  16044. }
  16045. },
  16046. beforeUpdate: function(chart) {
  16047. var legendOpts = chart.options.legend;
  16048. var legend = chart.legend;
  16049. if (legendOpts) {
  16050. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  16051. if (legend) {
  16052. core_layouts.configure(chart, legend, legendOpts);
  16053. legend.options = legendOpts;
  16054. } else {
  16055. createNewLegendAndAttach(chart, legendOpts);
  16056. }
  16057. } else if (legend) {
  16058. core_layouts.removeBox(chart, legend);
  16059. delete chart.legend;
  16060. }
  16061. },
  16062. afterEvent: function(chart, e) {
  16063. var legend = chart.legend;
  16064. if (legend) {
  16065. legend.handleEvent(e);
  16066. }
  16067. }
  16068. };
  16069. var noop$2 = helpers$1.noop;
  16070. core_defaults._set('global', {
  16071. title: {
  16072. display: false,
  16073. fontStyle: 'bold',
  16074. fullWidth: true,
  16075. padding: 10,
  16076. position: 'top',
  16077. text: '',
  16078. weight: 2000 // by default greater than legend (1000) to be above
  16079. }
  16080. });
  16081. /**
  16082. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  16083. */
  16084. var Title = core_element.extend({
  16085. initialize: function(config) {
  16086. var me = this;
  16087. helpers$1.extend(me, config);
  16088. // Contains hit boxes for each dataset (in dataset order)
  16089. me.legendHitBoxes = [];
  16090. },
  16091. // These methods are ordered by lifecycle. Utilities then follow.
  16092. beforeUpdate: noop$2,
  16093. update: function(maxWidth, maxHeight, margins) {
  16094. var me = this;
  16095. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  16096. me.beforeUpdate();
  16097. // Absorb the master measurements
  16098. me.maxWidth = maxWidth;
  16099. me.maxHeight = maxHeight;
  16100. me.margins = margins;
  16101. // Dimensions
  16102. me.beforeSetDimensions();
  16103. me.setDimensions();
  16104. me.afterSetDimensions();
  16105. // Labels
  16106. me.beforeBuildLabels();
  16107. me.buildLabels();
  16108. me.afterBuildLabels();
  16109. // Fit
  16110. me.beforeFit();
  16111. me.fit();
  16112. me.afterFit();
  16113. //
  16114. me.afterUpdate();
  16115. return me.minSize;
  16116. },
  16117. afterUpdate: noop$2,
  16118. //
  16119. beforeSetDimensions: noop$2,
  16120. setDimensions: function() {
  16121. var me = this;
  16122. // Set the unconstrained dimension before label rotation
  16123. if (me.isHorizontal()) {
  16124. // Reset position before calculating rotation
  16125. me.width = me.maxWidth;
  16126. me.left = 0;
  16127. me.right = me.width;
  16128. } else {
  16129. me.height = me.maxHeight;
  16130. // Reset position before calculating rotation
  16131. me.top = 0;
  16132. me.bottom = me.height;
  16133. }
  16134. // Reset padding
  16135. me.paddingLeft = 0;
  16136. me.paddingTop = 0;
  16137. me.paddingRight = 0;
  16138. me.paddingBottom = 0;
  16139. // Reset minSize
  16140. me.minSize = {
  16141. width: 0,
  16142. height: 0
  16143. };
  16144. },
  16145. afterSetDimensions: noop$2,
  16146. //
  16147. beforeBuildLabels: noop$2,
  16148. buildLabels: noop$2,
  16149. afterBuildLabels: noop$2,
  16150. //
  16151. beforeFit: noop$2,
  16152. fit: function() {
  16153. var me = this;
  16154. var opts = me.options;
  16155. var display = opts.display;
  16156. var minSize = me.minSize;
  16157. var lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  16158. var fontOpts = helpers$1.options._parseFont(opts);
  16159. var textSize = display ? (lineCount * fontOpts.lineHeight) + (opts.padding * 2) : 0;
  16160. if (me.isHorizontal()) {
  16161. minSize.width = me.maxWidth; // fill all the width
  16162. minSize.height = textSize;
  16163. } else {
  16164. minSize.width = textSize;
  16165. minSize.height = me.maxHeight; // fill all the height
  16166. }
  16167. me.width = minSize.width;
  16168. me.height = minSize.height;
  16169. },
  16170. afterFit: noop$2,
  16171. // Shared Methods
  16172. isHorizontal: function() {
  16173. var pos = this.options.position;
  16174. return pos === 'top' || pos === 'bottom';
  16175. },
  16176. // Actually draw the title block on the canvas
  16177. draw: function() {
  16178. var me = this;
  16179. var ctx = me.ctx;
  16180. var opts = me.options;
  16181. if (opts.display) {
  16182. var fontOpts = helpers$1.options._parseFont(opts);
  16183. var lineHeight = fontOpts.lineHeight;
  16184. var offset = lineHeight / 2 + opts.padding;
  16185. var rotation = 0;
  16186. var top = me.top;
  16187. var left = me.left;
  16188. var bottom = me.bottom;
  16189. var right = me.right;
  16190. var maxWidth, titleX, titleY;
  16191. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  16192. ctx.font = fontOpts.string;
  16193. // Horizontal
  16194. if (me.isHorizontal()) {
  16195. titleX = left + ((right - left) / 2); // midpoint of the width
  16196. titleY = top + offset;
  16197. maxWidth = right - left;
  16198. } else {
  16199. titleX = opts.position === 'left' ? left + offset : right - offset;
  16200. titleY = top + ((bottom - top) / 2);
  16201. maxWidth = bottom - top;
  16202. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  16203. }
  16204. ctx.save();
  16205. ctx.translate(titleX, titleY);
  16206. ctx.rotate(rotation);
  16207. ctx.textAlign = 'center';
  16208. ctx.textBaseline = 'middle';
  16209. var text = opts.text;
  16210. if (helpers$1.isArray(text)) {
  16211. var y = 0;
  16212. for (var i = 0; i < text.length; ++i) {
  16213. ctx.fillText(text[i], 0, y, maxWidth);
  16214. y += lineHeight;
  16215. }
  16216. } else {
  16217. ctx.fillText(text, 0, 0, maxWidth);
  16218. }
  16219. ctx.restore();
  16220. }
  16221. }
  16222. });
  16223. function createNewTitleBlockAndAttach(chart, titleOpts) {
  16224. var title = new Title({
  16225. ctx: chart.ctx,
  16226. options: titleOpts,
  16227. chart: chart
  16228. });
  16229. core_layouts.configure(chart, title, titleOpts);
  16230. core_layouts.addBox(chart, title);
  16231. chart.titleBlock = title;
  16232. }
  16233. var plugin_title = {
  16234. id: 'title',
  16235. /**
  16236. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  16237. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  16238. * the plugin, which one will be re-exposed in the chart.js file.
  16239. * https://github.com/chartjs/Chart.js/pull/2640
  16240. * @private
  16241. */
  16242. _element: Title,
  16243. beforeInit: function(chart) {
  16244. var titleOpts = chart.options.title;
  16245. if (titleOpts) {
  16246. createNewTitleBlockAndAttach(chart, titleOpts);
  16247. }
  16248. },
  16249. beforeUpdate: function(chart) {
  16250. var titleOpts = chart.options.title;
  16251. var titleBlock = chart.titleBlock;
  16252. if (titleOpts) {
  16253. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  16254. if (titleBlock) {
  16255. core_layouts.configure(chart, titleBlock, titleOpts);
  16256. titleBlock.options = titleOpts;
  16257. } else {
  16258. createNewTitleBlockAndAttach(chart, titleOpts);
  16259. }
  16260. } else if (titleBlock) {
  16261. core_layouts.removeBox(chart, titleBlock);
  16262. delete chart.titleBlock;
  16263. }
  16264. }
  16265. };
  16266. var plugins = {};
  16267. var filler = plugin_filler;
  16268. var legend = plugin_legend;
  16269. var title = plugin_title;
  16270. plugins.filler = filler;
  16271. plugins.legend = legend;
  16272. plugins.title = title;
  16273. /**
  16274. * @namespace Chart
  16275. */
  16276. core_controller.helpers = helpers$1;
  16277. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  16278. core_helpers(core_controller);
  16279. core_controller._adapters = core_adapters;
  16280. core_controller.Animation = core_animation;
  16281. core_controller.animationService = core_animations;
  16282. core_controller.controllers = controllers;
  16283. core_controller.DatasetController = core_datasetController;
  16284. core_controller.defaults = core_defaults;
  16285. core_controller.Element = core_element;
  16286. core_controller.elements = elements;
  16287. core_controller.Interaction = core_interaction;
  16288. core_controller.layouts = core_layouts;
  16289. core_controller.platform = platform;
  16290. core_controller.plugins = core_plugins;
  16291. core_controller.Scale = core_scale;
  16292. core_controller.scaleService = core_scaleService;
  16293. core_controller.Ticks = core_ticks;
  16294. core_controller.Tooltip = core_tooltip;
  16295. // Register built-in scales
  16296. core_controller.helpers.each(scales, function(scale, type) {
  16297. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  16298. });
  16299. // Load to register built-in adapters (as side effects)
  16300. // Loading built-in plugins
  16301. for (var k in plugins) {
  16302. if (plugins.hasOwnProperty(k)) {
  16303. core_controller.plugins.register(plugins[k]);
  16304. }
  16305. }
  16306. core_controller.platform.initialize();
  16307. var src = core_controller;
  16308. if (typeof window !== 'undefined') {
  16309. window.Chart = core_controller;
  16310. }
  16311. // DEPRECATIONS
  16312. /**
  16313. * Provided for backward compatibility, not available anymore
  16314. * @namespace Chart.Chart
  16315. * @deprecated since version 2.8.0
  16316. * @todo remove at version 3
  16317. * @private
  16318. */
  16319. core_controller.Chart = core_controller;
  16320. /**
  16321. * Provided for backward compatibility, not available anymore
  16322. * @namespace Chart.Legend
  16323. * @deprecated since version 2.1.5
  16324. * @todo remove at version 3
  16325. * @private
  16326. */
  16327. core_controller.Legend = plugins.legend._element;
  16328. /**
  16329. * Provided for backward compatibility, not available anymore
  16330. * @namespace Chart.Title
  16331. * @deprecated since version 2.1.5
  16332. * @todo remove at version 3
  16333. * @private
  16334. */
  16335. core_controller.Title = plugins.title._element;
  16336. /**
  16337. * Provided for backward compatibility, use Chart.plugins instead
  16338. * @namespace Chart.pluginService
  16339. * @deprecated since version 2.1.5
  16340. * @todo remove at version 3
  16341. * @private
  16342. */
  16343. core_controller.pluginService = core_controller.plugins;
  16344. /**
  16345. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  16346. * effect, instead simply create/register plugins via plain JavaScript objects.
  16347. * @interface Chart.PluginBase
  16348. * @deprecated since version 2.5.0
  16349. * @todo remove at version 3
  16350. * @private
  16351. */
  16352. core_controller.PluginBase = core_controller.Element.extend({});
  16353. /**
  16354. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  16355. * @namespace Chart.canvasHelpers
  16356. * @deprecated since version 2.6.0
  16357. * @todo remove at version 3
  16358. * @private
  16359. */
  16360. core_controller.canvasHelpers = core_controller.helpers.canvas;
  16361. /**
  16362. * Provided for backward compatibility, use Chart.layouts instead.
  16363. * @namespace Chart.layoutService
  16364. * @deprecated since version 2.7.3
  16365. * @todo remove at version 3
  16366. * @private
  16367. */
  16368. core_controller.layoutService = core_controller.layouts;
  16369. /**
  16370. * Provided for backward compatibility, not available anymore.
  16371. * @namespace Chart.LinearScaleBase
  16372. * @deprecated since version 2.8
  16373. * @todo remove at version 3
  16374. * @private
  16375. */
  16376. core_controller.LinearScaleBase = scale_linearbase;
  16377. /**
  16378. * Provided for backward compatibility, instead we should create a new Chart
  16379. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  16380. * @deprecated since version 2.8.0
  16381. * @todo remove at version 3
  16382. */
  16383. core_controller.helpers.each(
  16384. [
  16385. 'Bar',
  16386. 'Bubble',
  16387. 'Doughnut',
  16388. 'Line',
  16389. 'PolarArea',
  16390. 'Radar',
  16391. 'Scatter'
  16392. ],
  16393. function(klass) {
  16394. core_controller[klass] = function(ctx, cfg) {
  16395. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  16396. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  16397. }));
  16398. };
  16399. }
  16400. );
  16401. return src;
  16402. })));