Chart.bundle.js 566 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778
  1. /*!
  2. * Chart.js v2.9.3
  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 = global || self, global.Chart = factory());
  11. }(this, (function () { 'use strict';
  12. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  13. function commonjsRequire () {
  14. throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
  15. }
  16. function createCommonjsModule(fn, module) {
  17. return module = { exports: {} }, fn(module, module.exports), module.exports;
  18. }
  19. function getCjsExportFromNamespace (n) {
  20. return n && n['default'] || n;
  21. }
  22. var colorName = {
  23. "aliceblue": [240, 248, 255],
  24. "antiquewhite": [250, 235, 215],
  25. "aqua": [0, 255, 255],
  26. "aquamarine": [127, 255, 212],
  27. "azure": [240, 255, 255],
  28. "beige": [245, 245, 220],
  29. "bisque": [255, 228, 196],
  30. "black": [0, 0, 0],
  31. "blanchedalmond": [255, 235, 205],
  32. "blue": [0, 0, 255],
  33. "blueviolet": [138, 43, 226],
  34. "brown": [165, 42, 42],
  35. "burlywood": [222, 184, 135],
  36. "cadetblue": [95, 158, 160],
  37. "chartreuse": [127, 255, 0],
  38. "chocolate": [210, 105, 30],
  39. "coral": [255, 127, 80],
  40. "cornflowerblue": [100, 149, 237],
  41. "cornsilk": [255, 248, 220],
  42. "crimson": [220, 20, 60],
  43. "cyan": [0, 255, 255],
  44. "darkblue": [0, 0, 139],
  45. "darkcyan": [0, 139, 139],
  46. "darkgoldenrod": [184, 134, 11],
  47. "darkgray": [169, 169, 169],
  48. "darkgreen": [0, 100, 0],
  49. "darkgrey": [169, 169, 169],
  50. "darkkhaki": [189, 183, 107],
  51. "darkmagenta": [139, 0, 139],
  52. "darkolivegreen": [85, 107, 47],
  53. "darkorange": [255, 140, 0],
  54. "darkorchid": [153, 50, 204],
  55. "darkred": [139, 0, 0],
  56. "darksalmon": [233, 150, 122],
  57. "darkseagreen": [143, 188, 143],
  58. "darkslateblue": [72, 61, 139],
  59. "darkslategray": [47, 79, 79],
  60. "darkslategrey": [47, 79, 79],
  61. "darkturquoise": [0, 206, 209],
  62. "darkviolet": [148, 0, 211],
  63. "deeppink": [255, 20, 147],
  64. "deepskyblue": [0, 191, 255],
  65. "dimgray": [105, 105, 105],
  66. "dimgrey": [105, 105, 105],
  67. "dodgerblue": [30, 144, 255],
  68. "firebrick": [178, 34, 34],
  69. "floralwhite": [255, 250, 240],
  70. "forestgreen": [34, 139, 34],
  71. "fuchsia": [255, 0, 255],
  72. "gainsboro": [220, 220, 220],
  73. "ghostwhite": [248, 248, 255],
  74. "gold": [255, 215, 0],
  75. "goldenrod": [218, 165, 32],
  76. "gray": [128, 128, 128],
  77. "green": [0, 128, 0],
  78. "greenyellow": [173, 255, 47],
  79. "grey": [128, 128, 128],
  80. "honeydew": [240, 255, 240],
  81. "hotpink": [255, 105, 180],
  82. "indianred": [205, 92, 92],
  83. "indigo": [75, 0, 130],
  84. "ivory": [255, 255, 240],
  85. "khaki": [240, 230, 140],
  86. "lavender": [230, 230, 250],
  87. "lavenderblush": [255, 240, 245],
  88. "lawngreen": [124, 252, 0],
  89. "lemonchiffon": [255, 250, 205],
  90. "lightblue": [173, 216, 230],
  91. "lightcoral": [240, 128, 128],
  92. "lightcyan": [224, 255, 255],
  93. "lightgoldenrodyellow": [250, 250, 210],
  94. "lightgray": [211, 211, 211],
  95. "lightgreen": [144, 238, 144],
  96. "lightgrey": [211, 211, 211],
  97. "lightpink": [255, 182, 193],
  98. "lightsalmon": [255, 160, 122],
  99. "lightseagreen": [32, 178, 170],
  100. "lightskyblue": [135, 206, 250],
  101. "lightslategray": [119, 136, 153],
  102. "lightslategrey": [119, 136, 153],
  103. "lightsteelblue": [176, 196, 222],
  104. "lightyellow": [255, 255, 224],
  105. "lime": [0, 255, 0],
  106. "limegreen": [50, 205, 50],
  107. "linen": [250, 240, 230],
  108. "magenta": [255, 0, 255],
  109. "maroon": [128, 0, 0],
  110. "mediumaquamarine": [102, 205, 170],
  111. "mediumblue": [0, 0, 205],
  112. "mediumorchid": [186, 85, 211],
  113. "mediumpurple": [147, 112, 219],
  114. "mediumseagreen": [60, 179, 113],
  115. "mediumslateblue": [123, 104, 238],
  116. "mediumspringgreen": [0, 250, 154],
  117. "mediumturquoise": [72, 209, 204],
  118. "mediumvioletred": [199, 21, 133],
  119. "midnightblue": [25, 25, 112],
  120. "mintcream": [245, 255, 250],
  121. "mistyrose": [255, 228, 225],
  122. "moccasin": [255, 228, 181],
  123. "navajowhite": [255, 222, 173],
  124. "navy": [0, 0, 128],
  125. "oldlace": [253, 245, 230],
  126. "olive": [128, 128, 0],
  127. "olivedrab": [107, 142, 35],
  128. "orange": [255, 165, 0],
  129. "orangered": [255, 69, 0],
  130. "orchid": [218, 112, 214],
  131. "palegoldenrod": [238, 232, 170],
  132. "palegreen": [152, 251, 152],
  133. "paleturquoise": [175, 238, 238],
  134. "palevioletred": [219, 112, 147],
  135. "papayawhip": [255, 239, 213],
  136. "peachpuff": [255, 218, 185],
  137. "peru": [205, 133, 63],
  138. "pink": [255, 192, 203],
  139. "plum": [221, 160, 221],
  140. "powderblue": [176, 224, 230],
  141. "purple": [128, 0, 128],
  142. "rebeccapurple": [102, 51, 153],
  143. "red": [255, 0, 0],
  144. "rosybrown": [188, 143, 143],
  145. "royalblue": [65, 105, 225],
  146. "saddlebrown": [139, 69, 19],
  147. "salmon": [250, 128, 114],
  148. "sandybrown": [244, 164, 96],
  149. "seagreen": [46, 139, 87],
  150. "seashell": [255, 245, 238],
  151. "sienna": [160, 82, 45],
  152. "silver": [192, 192, 192],
  153. "skyblue": [135, 206, 235],
  154. "slateblue": [106, 90, 205],
  155. "slategray": [112, 128, 144],
  156. "slategrey": [112, 128, 144],
  157. "snow": [255, 250, 250],
  158. "springgreen": [0, 255, 127],
  159. "steelblue": [70, 130, 180],
  160. "tan": [210, 180, 140],
  161. "teal": [0, 128, 128],
  162. "thistle": [216, 191, 216],
  163. "tomato": [255, 99, 71],
  164. "turquoise": [64, 224, 208],
  165. "violet": [238, 130, 238],
  166. "wheat": [245, 222, 179],
  167. "white": [255, 255, 255],
  168. "whitesmoke": [245, 245, 245],
  169. "yellow": [255, 255, 0],
  170. "yellowgreen": [154, 205, 50]
  171. };
  172. var conversions = createCommonjsModule(function (module) {
  173. /* MIT license */
  174. // NOTE: conversions should only return primitive values (i.e. arrays, or
  175. // values that give correct `typeof` results).
  176. // do not use box values types (i.e. Number(), String(), etc.)
  177. var reverseKeywords = {};
  178. for (var key in colorName) {
  179. if (colorName.hasOwnProperty(key)) {
  180. reverseKeywords[colorName[key]] = key;
  181. }
  182. }
  183. var convert = module.exports = {
  184. rgb: {channels: 3, labels: 'rgb'},
  185. hsl: {channels: 3, labels: 'hsl'},
  186. hsv: {channels: 3, labels: 'hsv'},
  187. hwb: {channels: 3, labels: 'hwb'},
  188. cmyk: {channels: 4, labels: 'cmyk'},
  189. xyz: {channels: 3, labels: 'xyz'},
  190. lab: {channels: 3, labels: 'lab'},
  191. lch: {channels: 3, labels: 'lch'},
  192. hex: {channels: 1, labels: ['hex']},
  193. keyword: {channels: 1, labels: ['keyword']},
  194. ansi16: {channels: 1, labels: ['ansi16']},
  195. ansi256: {channels: 1, labels: ['ansi256']},
  196. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  197. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  198. gray: {channels: 1, labels: ['gray']}
  199. };
  200. // hide .channels and .labels properties
  201. for (var model in convert) {
  202. if (convert.hasOwnProperty(model)) {
  203. if (!('channels' in convert[model])) {
  204. throw new Error('missing channels property: ' + model);
  205. }
  206. if (!('labels' in convert[model])) {
  207. throw new Error('missing channel labels property: ' + model);
  208. }
  209. if (convert[model].labels.length !== convert[model].channels) {
  210. throw new Error('channel and label counts mismatch: ' + model);
  211. }
  212. var channels = convert[model].channels;
  213. var labels = convert[model].labels;
  214. delete convert[model].channels;
  215. delete convert[model].labels;
  216. Object.defineProperty(convert[model], 'channels', {value: channels});
  217. Object.defineProperty(convert[model], 'labels', {value: labels});
  218. }
  219. }
  220. convert.rgb.hsl = function (rgb) {
  221. var r = rgb[0] / 255;
  222. var g = rgb[1] / 255;
  223. var b = rgb[2] / 255;
  224. var min = Math.min(r, g, b);
  225. var max = Math.max(r, g, b);
  226. var delta = max - min;
  227. var h;
  228. var s;
  229. var l;
  230. if (max === min) {
  231. h = 0;
  232. } else if (r === max) {
  233. h = (g - b) / delta;
  234. } else if (g === max) {
  235. h = 2 + (b - r) / delta;
  236. } else if (b === max) {
  237. h = 4 + (r - g) / delta;
  238. }
  239. h = Math.min(h * 60, 360);
  240. if (h < 0) {
  241. h += 360;
  242. }
  243. l = (min + max) / 2;
  244. if (max === min) {
  245. s = 0;
  246. } else if (l <= 0.5) {
  247. s = delta / (max + min);
  248. } else {
  249. s = delta / (2 - max - min);
  250. }
  251. return [h, s * 100, l * 100];
  252. };
  253. convert.rgb.hsv = function (rgb) {
  254. var rdif;
  255. var gdif;
  256. var bdif;
  257. var h;
  258. var s;
  259. var r = rgb[0] / 255;
  260. var g = rgb[1] / 255;
  261. var b = rgb[2] / 255;
  262. var v = Math.max(r, g, b);
  263. var diff = v - Math.min(r, g, b);
  264. var diffc = function (c) {
  265. return (v - c) / 6 / diff + 1 / 2;
  266. };
  267. if (diff === 0) {
  268. h = s = 0;
  269. } else {
  270. s = diff / v;
  271. rdif = diffc(r);
  272. gdif = diffc(g);
  273. bdif = diffc(b);
  274. if (r === v) {
  275. h = bdif - gdif;
  276. } else if (g === v) {
  277. h = (1 / 3) + rdif - bdif;
  278. } else if (b === v) {
  279. h = (2 / 3) + gdif - rdif;
  280. }
  281. if (h < 0) {
  282. h += 1;
  283. } else if (h > 1) {
  284. h -= 1;
  285. }
  286. }
  287. return [
  288. h * 360,
  289. s * 100,
  290. v * 100
  291. ];
  292. };
  293. convert.rgb.hwb = function (rgb) {
  294. var r = rgb[0];
  295. var g = rgb[1];
  296. var b = rgb[2];
  297. var h = convert.rgb.hsl(rgb)[0];
  298. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  299. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  300. return [h, w * 100, b * 100];
  301. };
  302. convert.rgb.cmyk = function (rgb) {
  303. var r = rgb[0] / 255;
  304. var g = rgb[1] / 255;
  305. var b = rgb[2] / 255;
  306. var c;
  307. var m;
  308. var y;
  309. var k;
  310. k = Math.min(1 - r, 1 - g, 1 - b);
  311. c = (1 - r - k) / (1 - k) || 0;
  312. m = (1 - g - k) / (1 - k) || 0;
  313. y = (1 - b - k) / (1 - k) || 0;
  314. return [c * 100, m * 100, y * 100, k * 100];
  315. };
  316. /**
  317. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  318. * */
  319. function comparativeDistance(x, y) {
  320. return (
  321. Math.pow(x[0] - y[0], 2) +
  322. Math.pow(x[1] - y[1], 2) +
  323. Math.pow(x[2] - y[2], 2)
  324. );
  325. }
  326. convert.rgb.keyword = function (rgb) {
  327. var reversed = reverseKeywords[rgb];
  328. if (reversed) {
  329. return reversed;
  330. }
  331. var currentClosestDistance = Infinity;
  332. var currentClosestKeyword;
  333. for (var keyword in colorName) {
  334. if (colorName.hasOwnProperty(keyword)) {
  335. var value = colorName[keyword];
  336. // Compute comparative distance
  337. var distance = comparativeDistance(rgb, value);
  338. // Check if its less, if so set as closest
  339. if (distance < currentClosestDistance) {
  340. currentClosestDistance = distance;
  341. currentClosestKeyword = keyword;
  342. }
  343. }
  344. }
  345. return currentClosestKeyword;
  346. };
  347. convert.keyword.rgb = function (keyword) {
  348. return colorName[keyword];
  349. };
  350. convert.rgb.xyz = function (rgb) {
  351. var r = rgb[0] / 255;
  352. var g = rgb[1] / 255;
  353. var b = rgb[2] / 255;
  354. // assume sRGB
  355. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  356. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  357. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  358. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  359. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  360. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  361. return [x * 100, y * 100, z * 100];
  362. };
  363. convert.rgb.lab = function (rgb) {
  364. var xyz = convert.rgb.xyz(rgb);
  365. var x = xyz[0];
  366. var y = xyz[1];
  367. var z = xyz[2];
  368. var l;
  369. var a;
  370. var b;
  371. x /= 95.047;
  372. y /= 100;
  373. z /= 108.883;
  374. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  375. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  376. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  377. l = (116 * y) - 16;
  378. a = 500 * (x - y);
  379. b = 200 * (y - z);
  380. return [l, a, b];
  381. };
  382. convert.hsl.rgb = function (hsl) {
  383. var h = hsl[0] / 360;
  384. var s = hsl[1] / 100;
  385. var l = hsl[2] / 100;
  386. var t1;
  387. var t2;
  388. var t3;
  389. var rgb;
  390. var val;
  391. if (s === 0) {
  392. val = l * 255;
  393. return [val, val, val];
  394. }
  395. if (l < 0.5) {
  396. t2 = l * (1 + s);
  397. } else {
  398. t2 = l + s - l * s;
  399. }
  400. t1 = 2 * l - t2;
  401. rgb = [0, 0, 0];
  402. for (var i = 0; i < 3; i++) {
  403. t3 = h + 1 / 3 * -(i - 1);
  404. if (t3 < 0) {
  405. t3++;
  406. }
  407. if (t3 > 1) {
  408. t3--;
  409. }
  410. if (6 * t3 < 1) {
  411. val = t1 + (t2 - t1) * 6 * t3;
  412. } else if (2 * t3 < 1) {
  413. val = t2;
  414. } else if (3 * t3 < 2) {
  415. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  416. } else {
  417. val = t1;
  418. }
  419. rgb[i] = val * 255;
  420. }
  421. return rgb;
  422. };
  423. convert.hsl.hsv = function (hsl) {
  424. var h = hsl[0];
  425. var s = hsl[1] / 100;
  426. var l = hsl[2] / 100;
  427. var smin = s;
  428. var lmin = Math.max(l, 0.01);
  429. var sv;
  430. var v;
  431. l *= 2;
  432. s *= (l <= 1) ? l : 2 - l;
  433. smin *= lmin <= 1 ? lmin : 2 - lmin;
  434. v = (l + s) / 2;
  435. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  436. return [h, sv * 100, v * 100];
  437. };
  438. convert.hsv.rgb = function (hsv) {
  439. var h = hsv[0] / 60;
  440. var s = hsv[1] / 100;
  441. var v = hsv[2] / 100;
  442. var hi = Math.floor(h) % 6;
  443. var f = h - Math.floor(h);
  444. var p = 255 * v * (1 - s);
  445. var q = 255 * v * (1 - (s * f));
  446. var t = 255 * v * (1 - (s * (1 - f)));
  447. v *= 255;
  448. switch (hi) {
  449. case 0:
  450. return [v, t, p];
  451. case 1:
  452. return [q, v, p];
  453. case 2:
  454. return [p, v, t];
  455. case 3:
  456. return [p, q, v];
  457. case 4:
  458. return [t, p, v];
  459. case 5:
  460. return [v, p, q];
  461. }
  462. };
  463. convert.hsv.hsl = function (hsv) {
  464. var h = hsv[0];
  465. var s = hsv[1] / 100;
  466. var v = hsv[2] / 100;
  467. var vmin = Math.max(v, 0.01);
  468. var lmin;
  469. var sl;
  470. var l;
  471. l = (2 - s) * v;
  472. lmin = (2 - s) * vmin;
  473. sl = s * vmin;
  474. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  475. sl = sl || 0;
  476. l /= 2;
  477. return [h, sl * 100, l * 100];
  478. };
  479. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  480. convert.hwb.rgb = function (hwb) {
  481. var h = hwb[0] / 360;
  482. var wh = hwb[1] / 100;
  483. var bl = hwb[2] / 100;
  484. var ratio = wh + bl;
  485. var i;
  486. var v;
  487. var f;
  488. var n;
  489. // wh + bl cant be > 1
  490. if (ratio > 1) {
  491. wh /= ratio;
  492. bl /= ratio;
  493. }
  494. i = Math.floor(6 * h);
  495. v = 1 - bl;
  496. f = 6 * h - i;
  497. if ((i & 0x01) !== 0) {
  498. f = 1 - f;
  499. }
  500. n = wh + f * (v - wh); // linear interpolation
  501. var r;
  502. var g;
  503. var b;
  504. switch (i) {
  505. default:
  506. case 6:
  507. case 0: r = v; g = n; b = wh; break;
  508. case 1: r = n; g = v; b = wh; break;
  509. case 2: r = wh; g = v; b = n; break;
  510. case 3: r = wh; g = n; b = v; break;
  511. case 4: r = n; g = wh; b = v; break;
  512. case 5: r = v; g = wh; b = n; break;
  513. }
  514. return [r * 255, g * 255, b * 255];
  515. };
  516. convert.cmyk.rgb = function (cmyk) {
  517. var c = cmyk[0] / 100;
  518. var m = cmyk[1] / 100;
  519. var y = cmyk[2] / 100;
  520. var k = cmyk[3] / 100;
  521. var r;
  522. var g;
  523. var b;
  524. r = 1 - Math.min(1, c * (1 - k) + k);
  525. g = 1 - Math.min(1, m * (1 - k) + k);
  526. b = 1 - Math.min(1, y * (1 - k) + k);
  527. return [r * 255, g * 255, b * 255];
  528. };
  529. convert.xyz.rgb = function (xyz) {
  530. var x = xyz[0] / 100;
  531. var y = xyz[1] / 100;
  532. var z = xyz[2] / 100;
  533. var r;
  534. var g;
  535. var b;
  536. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  537. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  538. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  539. // assume sRGB
  540. r = r > 0.0031308
  541. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  542. : r * 12.92;
  543. g = g > 0.0031308
  544. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  545. : g * 12.92;
  546. b = b > 0.0031308
  547. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  548. : b * 12.92;
  549. r = Math.min(Math.max(0, r), 1);
  550. g = Math.min(Math.max(0, g), 1);
  551. b = Math.min(Math.max(0, b), 1);
  552. return [r * 255, g * 255, b * 255];
  553. };
  554. convert.xyz.lab = function (xyz) {
  555. var x = xyz[0];
  556. var y = xyz[1];
  557. var z = xyz[2];
  558. var l;
  559. var a;
  560. var b;
  561. x /= 95.047;
  562. y /= 100;
  563. z /= 108.883;
  564. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  565. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  566. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  567. l = (116 * y) - 16;
  568. a = 500 * (x - y);
  569. b = 200 * (y - z);
  570. return [l, a, b];
  571. };
  572. convert.lab.xyz = function (lab) {
  573. var l = lab[0];
  574. var a = lab[1];
  575. var b = lab[2];
  576. var x;
  577. var y;
  578. var z;
  579. y = (l + 16) / 116;
  580. x = a / 500 + y;
  581. z = y - b / 200;
  582. var y2 = Math.pow(y, 3);
  583. var x2 = Math.pow(x, 3);
  584. var z2 = Math.pow(z, 3);
  585. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  586. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  587. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  588. x *= 95.047;
  589. y *= 100;
  590. z *= 108.883;
  591. return [x, y, z];
  592. };
  593. convert.lab.lch = function (lab) {
  594. var l = lab[0];
  595. var a = lab[1];
  596. var b = lab[2];
  597. var hr;
  598. var h;
  599. var c;
  600. hr = Math.atan2(b, a);
  601. h = hr * 360 / 2 / Math.PI;
  602. if (h < 0) {
  603. h += 360;
  604. }
  605. c = Math.sqrt(a * a + b * b);
  606. return [l, c, h];
  607. };
  608. convert.lch.lab = function (lch) {
  609. var l = lch[0];
  610. var c = lch[1];
  611. var h = lch[2];
  612. var a;
  613. var b;
  614. var hr;
  615. hr = h / 360 * 2 * Math.PI;
  616. a = c * Math.cos(hr);
  617. b = c * Math.sin(hr);
  618. return [l, a, b];
  619. };
  620. convert.rgb.ansi16 = function (args) {
  621. var r = args[0];
  622. var g = args[1];
  623. var b = args[2];
  624. var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  625. value = Math.round(value / 50);
  626. if (value === 0) {
  627. return 30;
  628. }
  629. var ansi = 30
  630. + ((Math.round(b / 255) << 2)
  631. | (Math.round(g / 255) << 1)
  632. | Math.round(r / 255));
  633. if (value === 2) {
  634. ansi += 60;
  635. }
  636. return ansi;
  637. };
  638. convert.hsv.ansi16 = function (args) {
  639. // optimization here; we already know the value and don't need to get
  640. // it converted for us.
  641. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  642. };
  643. convert.rgb.ansi256 = function (args) {
  644. var r = args[0];
  645. var g = args[1];
  646. var b = args[2];
  647. // we use the extended greyscale palette here, with the exception of
  648. // black and white. normal palette only has 4 greyscale shades.
  649. if (r === g && g === b) {
  650. if (r < 8) {
  651. return 16;
  652. }
  653. if (r > 248) {
  654. return 231;
  655. }
  656. return Math.round(((r - 8) / 247) * 24) + 232;
  657. }
  658. var ansi = 16
  659. + (36 * Math.round(r / 255 * 5))
  660. + (6 * Math.round(g / 255 * 5))
  661. + Math.round(b / 255 * 5);
  662. return ansi;
  663. };
  664. convert.ansi16.rgb = function (args) {
  665. var color = args % 10;
  666. // handle greyscale
  667. if (color === 0 || color === 7) {
  668. if (args > 50) {
  669. color += 3.5;
  670. }
  671. color = color / 10.5 * 255;
  672. return [color, color, color];
  673. }
  674. var mult = (~~(args > 50) + 1) * 0.5;
  675. var r = ((color & 1) * mult) * 255;
  676. var g = (((color >> 1) & 1) * mult) * 255;
  677. var b = (((color >> 2) & 1) * mult) * 255;
  678. return [r, g, b];
  679. };
  680. convert.ansi256.rgb = function (args) {
  681. // handle greyscale
  682. if (args >= 232) {
  683. var c = (args - 232) * 10 + 8;
  684. return [c, c, c];
  685. }
  686. args -= 16;
  687. var rem;
  688. var r = Math.floor(args / 36) / 5 * 255;
  689. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  690. var b = (rem % 6) / 5 * 255;
  691. return [r, g, b];
  692. };
  693. convert.rgb.hex = function (args) {
  694. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  695. + ((Math.round(args[1]) & 0xFF) << 8)
  696. + (Math.round(args[2]) & 0xFF);
  697. var string = integer.toString(16).toUpperCase();
  698. return '000000'.substring(string.length) + string;
  699. };
  700. convert.hex.rgb = function (args) {
  701. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  702. if (!match) {
  703. return [0, 0, 0];
  704. }
  705. var colorString = match[0];
  706. if (match[0].length === 3) {
  707. colorString = colorString.split('').map(function (char) {
  708. return char + char;
  709. }).join('');
  710. }
  711. var integer = parseInt(colorString, 16);
  712. var r = (integer >> 16) & 0xFF;
  713. var g = (integer >> 8) & 0xFF;
  714. var b = integer & 0xFF;
  715. return [r, g, b];
  716. };
  717. convert.rgb.hcg = function (rgb) {
  718. var r = rgb[0] / 255;
  719. var g = rgb[1] / 255;
  720. var b = rgb[2] / 255;
  721. var max = Math.max(Math.max(r, g), b);
  722. var min = Math.min(Math.min(r, g), b);
  723. var chroma = (max - min);
  724. var grayscale;
  725. var hue;
  726. if (chroma < 1) {
  727. grayscale = min / (1 - chroma);
  728. } else {
  729. grayscale = 0;
  730. }
  731. if (chroma <= 0) {
  732. hue = 0;
  733. } else
  734. if (max === r) {
  735. hue = ((g - b) / chroma) % 6;
  736. } else
  737. if (max === g) {
  738. hue = 2 + (b - r) / chroma;
  739. } else {
  740. hue = 4 + (r - g) / chroma + 4;
  741. }
  742. hue /= 6;
  743. hue %= 1;
  744. return [hue * 360, chroma * 100, grayscale * 100];
  745. };
  746. convert.hsl.hcg = function (hsl) {
  747. var s = hsl[1] / 100;
  748. var l = hsl[2] / 100;
  749. var c = 1;
  750. var f = 0;
  751. if (l < 0.5) {
  752. c = 2.0 * s * l;
  753. } else {
  754. c = 2.0 * s * (1.0 - l);
  755. }
  756. if (c < 1.0) {
  757. f = (l - 0.5 * c) / (1.0 - c);
  758. }
  759. return [hsl[0], c * 100, f * 100];
  760. };
  761. convert.hsv.hcg = function (hsv) {
  762. var s = hsv[1] / 100;
  763. var v = hsv[2] / 100;
  764. var c = s * v;
  765. var f = 0;
  766. if (c < 1.0) {
  767. f = (v - c) / (1 - c);
  768. }
  769. return [hsv[0], c * 100, f * 100];
  770. };
  771. convert.hcg.rgb = function (hcg) {
  772. var h = hcg[0] / 360;
  773. var c = hcg[1] / 100;
  774. var g = hcg[2] / 100;
  775. if (c === 0.0) {
  776. return [g * 255, g * 255, g * 255];
  777. }
  778. var pure = [0, 0, 0];
  779. var hi = (h % 1) * 6;
  780. var v = hi % 1;
  781. var w = 1 - v;
  782. var mg = 0;
  783. switch (Math.floor(hi)) {
  784. case 0:
  785. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  786. case 1:
  787. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  788. case 2:
  789. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  790. case 3:
  791. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  792. case 4:
  793. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  794. default:
  795. pure[0] = 1; pure[1] = 0; pure[2] = w;
  796. }
  797. mg = (1.0 - c) * g;
  798. return [
  799. (c * pure[0] + mg) * 255,
  800. (c * pure[1] + mg) * 255,
  801. (c * pure[2] + mg) * 255
  802. ];
  803. };
  804. convert.hcg.hsv = function (hcg) {
  805. var c = hcg[1] / 100;
  806. var g = hcg[2] / 100;
  807. var v = c + g * (1.0 - c);
  808. var f = 0;
  809. if (v > 0.0) {
  810. f = c / v;
  811. }
  812. return [hcg[0], f * 100, v * 100];
  813. };
  814. convert.hcg.hsl = function (hcg) {
  815. var c = hcg[1] / 100;
  816. var g = hcg[2] / 100;
  817. var l = g * (1.0 - c) + 0.5 * c;
  818. var s = 0;
  819. if (l > 0.0 && l < 0.5) {
  820. s = c / (2 * l);
  821. } else
  822. if (l >= 0.5 && l < 1.0) {
  823. s = c / (2 * (1 - l));
  824. }
  825. return [hcg[0], s * 100, l * 100];
  826. };
  827. convert.hcg.hwb = function (hcg) {
  828. var c = hcg[1] / 100;
  829. var g = hcg[2] / 100;
  830. var v = c + g * (1.0 - c);
  831. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  832. };
  833. convert.hwb.hcg = function (hwb) {
  834. var w = hwb[1] / 100;
  835. var b = hwb[2] / 100;
  836. var v = 1 - b;
  837. var c = v - w;
  838. var g = 0;
  839. if (c < 1) {
  840. g = (v - c) / (1 - c);
  841. }
  842. return [hwb[0], c * 100, g * 100];
  843. };
  844. convert.apple.rgb = function (apple) {
  845. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  846. };
  847. convert.rgb.apple = function (rgb) {
  848. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  849. };
  850. convert.gray.rgb = function (args) {
  851. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  852. };
  853. convert.gray.hsl = convert.gray.hsv = function (args) {
  854. return [0, 0, args[0]];
  855. };
  856. convert.gray.hwb = function (gray) {
  857. return [0, 100, gray[0]];
  858. };
  859. convert.gray.cmyk = function (gray) {
  860. return [0, 0, 0, gray[0]];
  861. };
  862. convert.gray.lab = function (gray) {
  863. return [gray[0], 0, 0];
  864. };
  865. convert.gray.hex = function (gray) {
  866. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  867. var integer = (val << 16) + (val << 8) + val;
  868. var string = integer.toString(16).toUpperCase();
  869. return '000000'.substring(string.length) + string;
  870. };
  871. convert.rgb.gray = function (rgb) {
  872. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  873. return [val / 255 * 100];
  874. };
  875. });
  876. var conversions_1 = conversions.rgb;
  877. var conversions_2 = conversions.hsl;
  878. var conversions_3 = conversions.hsv;
  879. var conversions_4 = conversions.hwb;
  880. var conversions_5 = conversions.cmyk;
  881. var conversions_6 = conversions.xyz;
  882. var conversions_7 = conversions.lab;
  883. var conversions_8 = conversions.lch;
  884. var conversions_9 = conversions.hex;
  885. var conversions_10 = conversions.keyword;
  886. var conversions_11 = conversions.ansi16;
  887. var conversions_12 = conversions.ansi256;
  888. var conversions_13 = conversions.hcg;
  889. var conversions_14 = conversions.apple;
  890. var conversions_15 = conversions.gray;
  891. /*
  892. this function routes a model to all other models.
  893. all functions that are routed have a property `.conversion` attached
  894. to the returned synthetic function. This property is an array
  895. of strings, each with the steps in between the 'from' and 'to'
  896. color models (inclusive).
  897. conversions that are not possible simply are not included.
  898. */
  899. function buildGraph() {
  900. var graph = {};
  901. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  902. var models = Object.keys(conversions);
  903. for (var len = models.length, i = 0; i < len; i++) {
  904. graph[models[i]] = {
  905. // http://jsperf.com/1-vs-infinity
  906. // micro-opt, but this is simple.
  907. distance: -1,
  908. parent: null
  909. };
  910. }
  911. return graph;
  912. }
  913. // https://en.wikipedia.org/wiki/Breadth-first_search
  914. function deriveBFS(fromModel) {
  915. var graph = buildGraph();
  916. var queue = [fromModel]; // unshift -> queue -> pop
  917. graph[fromModel].distance = 0;
  918. while (queue.length) {
  919. var current = queue.pop();
  920. var adjacents = Object.keys(conversions[current]);
  921. for (var len = adjacents.length, i = 0; i < len; i++) {
  922. var adjacent = adjacents[i];
  923. var node = graph[adjacent];
  924. if (node.distance === -1) {
  925. node.distance = graph[current].distance + 1;
  926. node.parent = current;
  927. queue.unshift(adjacent);
  928. }
  929. }
  930. }
  931. return graph;
  932. }
  933. function link(from, to) {
  934. return function (args) {
  935. return to(from(args));
  936. };
  937. }
  938. function wrapConversion(toModel, graph) {
  939. var path = [graph[toModel].parent, toModel];
  940. var fn = conversions[graph[toModel].parent][toModel];
  941. var cur = graph[toModel].parent;
  942. while (graph[cur].parent) {
  943. path.unshift(graph[cur].parent);
  944. fn = link(conversions[graph[cur].parent][cur], fn);
  945. cur = graph[cur].parent;
  946. }
  947. fn.conversion = path;
  948. return fn;
  949. }
  950. var route = function (fromModel) {
  951. var graph = deriveBFS(fromModel);
  952. var conversion = {};
  953. var models = Object.keys(graph);
  954. for (var len = models.length, i = 0; i < len; i++) {
  955. var toModel = models[i];
  956. var node = graph[toModel];
  957. if (node.parent === null) {
  958. // no possible conversion, or this node is the source model.
  959. continue;
  960. }
  961. conversion[toModel] = wrapConversion(toModel, graph);
  962. }
  963. return conversion;
  964. };
  965. var convert = {};
  966. var models = Object.keys(conversions);
  967. function wrapRaw(fn) {
  968. var wrappedFn = function (args) {
  969. if (args === undefined || args === null) {
  970. return args;
  971. }
  972. if (arguments.length > 1) {
  973. args = Array.prototype.slice.call(arguments);
  974. }
  975. return fn(args);
  976. };
  977. // preserve .conversion property if there is one
  978. if ('conversion' in fn) {
  979. wrappedFn.conversion = fn.conversion;
  980. }
  981. return wrappedFn;
  982. }
  983. function wrapRounded(fn) {
  984. var wrappedFn = function (args) {
  985. if (args === undefined || args === null) {
  986. return args;
  987. }
  988. if (arguments.length > 1) {
  989. args = Array.prototype.slice.call(arguments);
  990. }
  991. var result = fn(args);
  992. // we're assuming the result is an array here.
  993. // see notice in conversions.js; don't use box types
  994. // in conversion functions.
  995. if (typeof result === 'object') {
  996. for (var len = result.length, i = 0; i < len; i++) {
  997. result[i] = Math.round(result[i]);
  998. }
  999. }
  1000. return result;
  1001. };
  1002. // preserve .conversion property if there is one
  1003. if ('conversion' in fn) {
  1004. wrappedFn.conversion = fn.conversion;
  1005. }
  1006. return wrappedFn;
  1007. }
  1008. models.forEach(function (fromModel) {
  1009. convert[fromModel] = {};
  1010. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  1011. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  1012. var routes = route(fromModel);
  1013. var routeModels = Object.keys(routes);
  1014. routeModels.forEach(function (toModel) {
  1015. var fn = routes[toModel];
  1016. convert[fromModel][toModel] = wrapRounded(fn);
  1017. convert[fromModel][toModel].raw = wrapRaw(fn);
  1018. });
  1019. });
  1020. var colorConvert = convert;
  1021. var colorName$1 = {
  1022. "aliceblue": [240, 248, 255],
  1023. "antiquewhite": [250, 235, 215],
  1024. "aqua": [0, 255, 255],
  1025. "aquamarine": [127, 255, 212],
  1026. "azure": [240, 255, 255],
  1027. "beige": [245, 245, 220],
  1028. "bisque": [255, 228, 196],
  1029. "black": [0, 0, 0],
  1030. "blanchedalmond": [255, 235, 205],
  1031. "blue": [0, 0, 255],
  1032. "blueviolet": [138, 43, 226],
  1033. "brown": [165, 42, 42],
  1034. "burlywood": [222, 184, 135],
  1035. "cadetblue": [95, 158, 160],
  1036. "chartreuse": [127, 255, 0],
  1037. "chocolate": [210, 105, 30],
  1038. "coral": [255, 127, 80],
  1039. "cornflowerblue": [100, 149, 237],
  1040. "cornsilk": [255, 248, 220],
  1041. "crimson": [220, 20, 60],
  1042. "cyan": [0, 255, 255],
  1043. "darkblue": [0, 0, 139],
  1044. "darkcyan": [0, 139, 139],
  1045. "darkgoldenrod": [184, 134, 11],
  1046. "darkgray": [169, 169, 169],
  1047. "darkgreen": [0, 100, 0],
  1048. "darkgrey": [169, 169, 169],
  1049. "darkkhaki": [189, 183, 107],
  1050. "darkmagenta": [139, 0, 139],
  1051. "darkolivegreen": [85, 107, 47],
  1052. "darkorange": [255, 140, 0],
  1053. "darkorchid": [153, 50, 204],
  1054. "darkred": [139, 0, 0],
  1055. "darksalmon": [233, 150, 122],
  1056. "darkseagreen": [143, 188, 143],
  1057. "darkslateblue": [72, 61, 139],
  1058. "darkslategray": [47, 79, 79],
  1059. "darkslategrey": [47, 79, 79],
  1060. "darkturquoise": [0, 206, 209],
  1061. "darkviolet": [148, 0, 211],
  1062. "deeppink": [255, 20, 147],
  1063. "deepskyblue": [0, 191, 255],
  1064. "dimgray": [105, 105, 105],
  1065. "dimgrey": [105, 105, 105],
  1066. "dodgerblue": [30, 144, 255],
  1067. "firebrick": [178, 34, 34],
  1068. "floralwhite": [255, 250, 240],
  1069. "forestgreen": [34, 139, 34],
  1070. "fuchsia": [255, 0, 255],
  1071. "gainsboro": [220, 220, 220],
  1072. "ghostwhite": [248, 248, 255],
  1073. "gold": [255, 215, 0],
  1074. "goldenrod": [218, 165, 32],
  1075. "gray": [128, 128, 128],
  1076. "green": [0, 128, 0],
  1077. "greenyellow": [173, 255, 47],
  1078. "grey": [128, 128, 128],
  1079. "honeydew": [240, 255, 240],
  1080. "hotpink": [255, 105, 180],
  1081. "indianred": [205, 92, 92],
  1082. "indigo": [75, 0, 130],
  1083. "ivory": [255, 255, 240],
  1084. "khaki": [240, 230, 140],
  1085. "lavender": [230, 230, 250],
  1086. "lavenderblush": [255, 240, 245],
  1087. "lawngreen": [124, 252, 0],
  1088. "lemonchiffon": [255, 250, 205],
  1089. "lightblue": [173, 216, 230],
  1090. "lightcoral": [240, 128, 128],
  1091. "lightcyan": [224, 255, 255],
  1092. "lightgoldenrodyellow": [250, 250, 210],
  1093. "lightgray": [211, 211, 211],
  1094. "lightgreen": [144, 238, 144],
  1095. "lightgrey": [211, 211, 211],
  1096. "lightpink": [255, 182, 193],
  1097. "lightsalmon": [255, 160, 122],
  1098. "lightseagreen": [32, 178, 170],
  1099. "lightskyblue": [135, 206, 250],
  1100. "lightslategray": [119, 136, 153],
  1101. "lightslategrey": [119, 136, 153],
  1102. "lightsteelblue": [176, 196, 222],
  1103. "lightyellow": [255, 255, 224],
  1104. "lime": [0, 255, 0],
  1105. "limegreen": [50, 205, 50],
  1106. "linen": [250, 240, 230],
  1107. "magenta": [255, 0, 255],
  1108. "maroon": [128, 0, 0],
  1109. "mediumaquamarine": [102, 205, 170],
  1110. "mediumblue": [0, 0, 205],
  1111. "mediumorchid": [186, 85, 211],
  1112. "mediumpurple": [147, 112, 219],
  1113. "mediumseagreen": [60, 179, 113],
  1114. "mediumslateblue": [123, 104, 238],
  1115. "mediumspringgreen": [0, 250, 154],
  1116. "mediumturquoise": [72, 209, 204],
  1117. "mediumvioletred": [199, 21, 133],
  1118. "midnightblue": [25, 25, 112],
  1119. "mintcream": [245, 255, 250],
  1120. "mistyrose": [255, 228, 225],
  1121. "moccasin": [255, 228, 181],
  1122. "navajowhite": [255, 222, 173],
  1123. "navy": [0, 0, 128],
  1124. "oldlace": [253, 245, 230],
  1125. "olive": [128, 128, 0],
  1126. "olivedrab": [107, 142, 35],
  1127. "orange": [255, 165, 0],
  1128. "orangered": [255, 69, 0],
  1129. "orchid": [218, 112, 214],
  1130. "palegoldenrod": [238, 232, 170],
  1131. "palegreen": [152, 251, 152],
  1132. "paleturquoise": [175, 238, 238],
  1133. "palevioletred": [219, 112, 147],
  1134. "papayawhip": [255, 239, 213],
  1135. "peachpuff": [255, 218, 185],
  1136. "peru": [205, 133, 63],
  1137. "pink": [255, 192, 203],
  1138. "plum": [221, 160, 221],
  1139. "powderblue": [176, 224, 230],
  1140. "purple": [128, 0, 128],
  1141. "rebeccapurple": [102, 51, 153],
  1142. "red": [255, 0, 0],
  1143. "rosybrown": [188, 143, 143],
  1144. "royalblue": [65, 105, 225],
  1145. "saddlebrown": [139, 69, 19],
  1146. "salmon": [250, 128, 114],
  1147. "sandybrown": [244, 164, 96],
  1148. "seagreen": [46, 139, 87],
  1149. "seashell": [255, 245, 238],
  1150. "sienna": [160, 82, 45],
  1151. "silver": [192, 192, 192],
  1152. "skyblue": [135, 206, 235],
  1153. "slateblue": [106, 90, 205],
  1154. "slategray": [112, 128, 144],
  1155. "slategrey": [112, 128, 144],
  1156. "snow": [255, 250, 250],
  1157. "springgreen": [0, 255, 127],
  1158. "steelblue": [70, 130, 180],
  1159. "tan": [210, 180, 140],
  1160. "teal": [0, 128, 128],
  1161. "thistle": [216, 191, 216],
  1162. "tomato": [255, 99, 71],
  1163. "turquoise": [64, 224, 208],
  1164. "violet": [238, 130, 238],
  1165. "wheat": [245, 222, 179],
  1166. "white": [255, 255, 255],
  1167. "whitesmoke": [245, 245, 245],
  1168. "yellow": [255, 255, 0],
  1169. "yellowgreen": [154, 205, 50]
  1170. };
  1171. /* MIT license */
  1172. var colorString = {
  1173. getRgba: getRgba,
  1174. getHsla: getHsla,
  1175. getRgb: getRgb,
  1176. getHsl: getHsl,
  1177. getHwb: getHwb,
  1178. getAlpha: getAlpha,
  1179. hexString: hexString,
  1180. rgbString: rgbString,
  1181. rgbaString: rgbaString,
  1182. percentString: percentString,
  1183. percentaString: percentaString,
  1184. hslString: hslString,
  1185. hslaString: hslaString,
  1186. hwbString: hwbString,
  1187. keyword: keyword
  1188. };
  1189. function getRgba(string) {
  1190. if (!string) {
  1191. return;
  1192. }
  1193. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  1194. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  1195. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1196. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1197. keyword = /(\w+)/;
  1198. var rgb = [0, 0, 0],
  1199. a = 1,
  1200. match = string.match(abbr),
  1201. hexAlpha = "";
  1202. if (match) {
  1203. match = match[1];
  1204. hexAlpha = match[3];
  1205. for (var i = 0; i < rgb.length; i++) {
  1206. rgb[i] = parseInt(match[i] + match[i], 16);
  1207. }
  1208. if (hexAlpha) {
  1209. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  1210. }
  1211. }
  1212. else if (match = string.match(hex)) {
  1213. hexAlpha = match[2];
  1214. match = match[1];
  1215. for (var i = 0; i < rgb.length; i++) {
  1216. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  1217. }
  1218. if (hexAlpha) {
  1219. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  1220. }
  1221. }
  1222. else if (match = string.match(rgba)) {
  1223. for (var i = 0; i < rgb.length; i++) {
  1224. rgb[i] = parseInt(match[i + 1]);
  1225. }
  1226. a = parseFloat(match[4]);
  1227. }
  1228. else if (match = string.match(per)) {
  1229. for (var i = 0; i < rgb.length; i++) {
  1230. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  1231. }
  1232. a = parseFloat(match[4]);
  1233. }
  1234. else if (match = string.match(keyword)) {
  1235. if (match[1] == "transparent") {
  1236. return [0, 0, 0, 0];
  1237. }
  1238. rgb = colorName$1[match[1]];
  1239. if (!rgb) {
  1240. return;
  1241. }
  1242. }
  1243. for (var i = 0; i < rgb.length; i++) {
  1244. rgb[i] = scale(rgb[i], 0, 255);
  1245. }
  1246. if (!a && a != 0) {
  1247. a = 1;
  1248. }
  1249. else {
  1250. a = scale(a, 0, 1);
  1251. }
  1252. rgb[3] = a;
  1253. return rgb;
  1254. }
  1255. function getHsla(string) {
  1256. if (!string) {
  1257. return;
  1258. }
  1259. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1260. var match = string.match(hsl);
  1261. if (match) {
  1262. var alpha = parseFloat(match[4]);
  1263. var h = scale(parseInt(match[1]), 0, 360),
  1264. s = scale(parseFloat(match[2]), 0, 100),
  1265. l = scale(parseFloat(match[3]), 0, 100),
  1266. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1267. return [h, s, l, a];
  1268. }
  1269. }
  1270. function getHwb(string) {
  1271. if (!string) {
  1272. return;
  1273. }
  1274. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1275. var match = string.match(hwb);
  1276. if (match) {
  1277. var alpha = parseFloat(match[4]);
  1278. var h = scale(parseInt(match[1]), 0, 360),
  1279. w = scale(parseFloat(match[2]), 0, 100),
  1280. b = scale(parseFloat(match[3]), 0, 100),
  1281. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1282. return [h, w, b, a];
  1283. }
  1284. }
  1285. function getRgb(string) {
  1286. var rgba = getRgba(string);
  1287. return rgba && rgba.slice(0, 3);
  1288. }
  1289. function getHsl(string) {
  1290. var hsla = getHsla(string);
  1291. return hsla && hsla.slice(0, 3);
  1292. }
  1293. function getAlpha(string) {
  1294. var vals = getRgba(string);
  1295. if (vals) {
  1296. return vals[3];
  1297. }
  1298. else if (vals = getHsla(string)) {
  1299. return vals[3];
  1300. }
  1301. else if (vals = getHwb(string)) {
  1302. return vals[3];
  1303. }
  1304. }
  1305. // generators
  1306. function hexString(rgba, a) {
  1307. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  1308. return "#" + hexDouble(rgba[0])
  1309. + hexDouble(rgba[1])
  1310. + hexDouble(rgba[2])
  1311. + (
  1312. (a >= 0 && a < 1)
  1313. ? hexDouble(Math.round(a * 255))
  1314. : ""
  1315. );
  1316. }
  1317. function rgbString(rgba, alpha) {
  1318. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1319. return rgbaString(rgba, alpha);
  1320. }
  1321. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  1322. }
  1323. function rgbaString(rgba, alpha) {
  1324. if (alpha === undefined) {
  1325. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  1326. }
  1327. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  1328. + ", " + alpha + ")";
  1329. }
  1330. function percentString(rgba, alpha) {
  1331. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1332. return percentaString(rgba, alpha);
  1333. }
  1334. var r = Math.round(rgba[0]/255 * 100),
  1335. g = Math.round(rgba[1]/255 * 100),
  1336. b = Math.round(rgba[2]/255 * 100);
  1337. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  1338. }
  1339. function percentaString(rgba, alpha) {
  1340. var r = Math.round(rgba[0]/255 * 100),
  1341. g = Math.round(rgba[1]/255 * 100),
  1342. b = Math.round(rgba[2]/255 * 100);
  1343. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  1344. }
  1345. function hslString(hsla, alpha) {
  1346. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1347. return hslaString(hsla, alpha);
  1348. }
  1349. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1350. }
  1351. function hslaString(hsla, alpha) {
  1352. if (alpha === undefined) {
  1353. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1354. }
  1355. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1356. + alpha + ")";
  1357. }
  1358. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1359. // (hwb have alpha optional & 1 is default value)
  1360. function hwbString(hwb, alpha) {
  1361. if (alpha === undefined) {
  1362. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1363. }
  1364. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1365. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1366. }
  1367. function keyword(rgb) {
  1368. return reverseNames[rgb.slice(0, 3)];
  1369. }
  1370. // helpers
  1371. function scale(num, min, max) {
  1372. return Math.min(Math.max(min, num), max);
  1373. }
  1374. function hexDouble(num) {
  1375. var str = num.toString(16).toUpperCase();
  1376. return (str.length < 2) ? "0" + str : str;
  1377. }
  1378. //create a list of reverse color names
  1379. var reverseNames = {};
  1380. for (var name in colorName$1) {
  1381. reverseNames[colorName$1[name]] = name;
  1382. }
  1383. /* MIT license */
  1384. var Color = function (obj) {
  1385. if (obj instanceof Color) {
  1386. return obj;
  1387. }
  1388. if (!(this instanceof Color)) {
  1389. return new Color(obj);
  1390. }
  1391. this.valid = false;
  1392. this.values = {
  1393. rgb: [0, 0, 0],
  1394. hsl: [0, 0, 0],
  1395. hsv: [0, 0, 0],
  1396. hwb: [0, 0, 0],
  1397. cmyk: [0, 0, 0, 0],
  1398. alpha: 1
  1399. };
  1400. // parse Color() argument
  1401. var vals;
  1402. if (typeof obj === 'string') {
  1403. vals = colorString.getRgba(obj);
  1404. if (vals) {
  1405. this.setValues('rgb', vals);
  1406. } else if (vals = colorString.getHsla(obj)) {
  1407. this.setValues('hsl', vals);
  1408. } else if (vals = colorString.getHwb(obj)) {
  1409. this.setValues('hwb', vals);
  1410. }
  1411. } else if (typeof obj === 'object') {
  1412. vals = obj;
  1413. if (vals.r !== undefined || vals.red !== undefined) {
  1414. this.setValues('rgb', vals);
  1415. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1416. this.setValues('hsl', vals);
  1417. } else if (vals.v !== undefined || vals.value !== undefined) {
  1418. this.setValues('hsv', vals);
  1419. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1420. this.setValues('hwb', vals);
  1421. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1422. this.setValues('cmyk', vals);
  1423. }
  1424. }
  1425. };
  1426. Color.prototype = {
  1427. isValid: function () {
  1428. return this.valid;
  1429. },
  1430. rgb: function () {
  1431. return this.setSpace('rgb', arguments);
  1432. },
  1433. hsl: function () {
  1434. return this.setSpace('hsl', arguments);
  1435. },
  1436. hsv: function () {
  1437. return this.setSpace('hsv', arguments);
  1438. },
  1439. hwb: function () {
  1440. return this.setSpace('hwb', arguments);
  1441. },
  1442. cmyk: function () {
  1443. return this.setSpace('cmyk', arguments);
  1444. },
  1445. rgbArray: function () {
  1446. return this.values.rgb;
  1447. },
  1448. hslArray: function () {
  1449. return this.values.hsl;
  1450. },
  1451. hsvArray: function () {
  1452. return this.values.hsv;
  1453. },
  1454. hwbArray: function () {
  1455. var values = this.values;
  1456. if (values.alpha !== 1) {
  1457. return values.hwb.concat([values.alpha]);
  1458. }
  1459. return values.hwb;
  1460. },
  1461. cmykArray: function () {
  1462. return this.values.cmyk;
  1463. },
  1464. rgbaArray: function () {
  1465. var values = this.values;
  1466. return values.rgb.concat([values.alpha]);
  1467. },
  1468. hslaArray: function () {
  1469. var values = this.values;
  1470. return values.hsl.concat([values.alpha]);
  1471. },
  1472. alpha: function (val) {
  1473. if (val === undefined) {
  1474. return this.values.alpha;
  1475. }
  1476. this.setValues('alpha', val);
  1477. return this;
  1478. },
  1479. red: function (val) {
  1480. return this.setChannel('rgb', 0, val);
  1481. },
  1482. green: function (val) {
  1483. return this.setChannel('rgb', 1, val);
  1484. },
  1485. blue: function (val) {
  1486. return this.setChannel('rgb', 2, val);
  1487. },
  1488. hue: function (val) {
  1489. if (val) {
  1490. val %= 360;
  1491. val = val < 0 ? 360 + val : val;
  1492. }
  1493. return this.setChannel('hsl', 0, val);
  1494. },
  1495. saturation: function (val) {
  1496. return this.setChannel('hsl', 1, val);
  1497. },
  1498. lightness: function (val) {
  1499. return this.setChannel('hsl', 2, val);
  1500. },
  1501. saturationv: function (val) {
  1502. return this.setChannel('hsv', 1, val);
  1503. },
  1504. whiteness: function (val) {
  1505. return this.setChannel('hwb', 1, val);
  1506. },
  1507. blackness: function (val) {
  1508. return this.setChannel('hwb', 2, val);
  1509. },
  1510. value: function (val) {
  1511. return this.setChannel('hsv', 2, val);
  1512. },
  1513. cyan: function (val) {
  1514. return this.setChannel('cmyk', 0, val);
  1515. },
  1516. magenta: function (val) {
  1517. return this.setChannel('cmyk', 1, val);
  1518. },
  1519. yellow: function (val) {
  1520. return this.setChannel('cmyk', 2, val);
  1521. },
  1522. black: function (val) {
  1523. return this.setChannel('cmyk', 3, val);
  1524. },
  1525. hexString: function () {
  1526. return colorString.hexString(this.values.rgb);
  1527. },
  1528. rgbString: function () {
  1529. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1530. },
  1531. rgbaString: function () {
  1532. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1533. },
  1534. percentString: function () {
  1535. return colorString.percentString(this.values.rgb, this.values.alpha);
  1536. },
  1537. hslString: function () {
  1538. return colorString.hslString(this.values.hsl, this.values.alpha);
  1539. },
  1540. hslaString: function () {
  1541. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1542. },
  1543. hwbString: function () {
  1544. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1545. },
  1546. keyword: function () {
  1547. return colorString.keyword(this.values.rgb, this.values.alpha);
  1548. },
  1549. rgbNumber: function () {
  1550. var rgb = this.values.rgb;
  1551. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1552. },
  1553. luminosity: function () {
  1554. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1555. var rgb = this.values.rgb;
  1556. var lum = [];
  1557. for (var i = 0; i < rgb.length; i++) {
  1558. var chan = rgb[i] / 255;
  1559. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1560. }
  1561. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1562. },
  1563. contrast: function (color2) {
  1564. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1565. var lum1 = this.luminosity();
  1566. var lum2 = color2.luminosity();
  1567. if (lum1 > lum2) {
  1568. return (lum1 + 0.05) / (lum2 + 0.05);
  1569. }
  1570. return (lum2 + 0.05) / (lum1 + 0.05);
  1571. },
  1572. level: function (color2) {
  1573. var contrastRatio = this.contrast(color2);
  1574. if (contrastRatio >= 7.1) {
  1575. return 'AAA';
  1576. }
  1577. return (contrastRatio >= 4.5) ? 'AA' : '';
  1578. },
  1579. dark: function () {
  1580. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1581. var rgb = this.values.rgb;
  1582. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1583. return yiq < 128;
  1584. },
  1585. light: function () {
  1586. return !this.dark();
  1587. },
  1588. negate: function () {
  1589. var rgb = [];
  1590. for (var i = 0; i < 3; i++) {
  1591. rgb[i] = 255 - this.values.rgb[i];
  1592. }
  1593. this.setValues('rgb', rgb);
  1594. return this;
  1595. },
  1596. lighten: function (ratio) {
  1597. var hsl = this.values.hsl;
  1598. hsl[2] += hsl[2] * ratio;
  1599. this.setValues('hsl', hsl);
  1600. return this;
  1601. },
  1602. darken: function (ratio) {
  1603. var hsl = this.values.hsl;
  1604. hsl[2] -= hsl[2] * ratio;
  1605. this.setValues('hsl', hsl);
  1606. return this;
  1607. },
  1608. saturate: function (ratio) {
  1609. var hsl = this.values.hsl;
  1610. hsl[1] += hsl[1] * ratio;
  1611. this.setValues('hsl', hsl);
  1612. return this;
  1613. },
  1614. desaturate: function (ratio) {
  1615. var hsl = this.values.hsl;
  1616. hsl[1] -= hsl[1] * ratio;
  1617. this.setValues('hsl', hsl);
  1618. return this;
  1619. },
  1620. whiten: function (ratio) {
  1621. var hwb = this.values.hwb;
  1622. hwb[1] += hwb[1] * ratio;
  1623. this.setValues('hwb', hwb);
  1624. return this;
  1625. },
  1626. blacken: function (ratio) {
  1627. var hwb = this.values.hwb;
  1628. hwb[2] += hwb[2] * ratio;
  1629. this.setValues('hwb', hwb);
  1630. return this;
  1631. },
  1632. greyscale: function () {
  1633. var rgb = this.values.rgb;
  1634. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1635. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1636. this.setValues('rgb', [val, val, val]);
  1637. return this;
  1638. },
  1639. clearer: function (ratio) {
  1640. var alpha = this.values.alpha;
  1641. this.setValues('alpha', alpha - (alpha * ratio));
  1642. return this;
  1643. },
  1644. opaquer: function (ratio) {
  1645. var alpha = this.values.alpha;
  1646. this.setValues('alpha', alpha + (alpha * ratio));
  1647. return this;
  1648. },
  1649. rotate: function (degrees) {
  1650. var hsl = this.values.hsl;
  1651. var hue = (hsl[0] + degrees) % 360;
  1652. hsl[0] = hue < 0 ? 360 + hue : hue;
  1653. this.setValues('hsl', hsl);
  1654. return this;
  1655. },
  1656. /**
  1657. * Ported from sass implementation in C
  1658. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1659. */
  1660. mix: function (mixinColor, weight) {
  1661. var color1 = this;
  1662. var color2 = mixinColor;
  1663. var p = weight === undefined ? 0.5 : weight;
  1664. var w = 2 * p - 1;
  1665. var a = color1.alpha() - color2.alpha();
  1666. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1667. var w2 = 1 - w1;
  1668. return this
  1669. .rgb(
  1670. w1 * color1.red() + w2 * color2.red(),
  1671. w1 * color1.green() + w2 * color2.green(),
  1672. w1 * color1.blue() + w2 * color2.blue()
  1673. )
  1674. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1675. },
  1676. toJSON: function () {
  1677. return this.rgb();
  1678. },
  1679. clone: function () {
  1680. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1681. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1682. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1683. // except 'alpha' which is a number.
  1684. var result = new Color();
  1685. var source = this.values;
  1686. var target = result.values;
  1687. var value, type;
  1688. for (var prop in source) {
  1689. if (source.hasOwnProperty(prop)) {
  1690. value = source[prop];
  1691. type = ({}).toString.call(value);
  1692. if (type === '[object Array]') {
  1693. target[prop] = value.slice(0);
  1694. } else if (type === '[object Number]') {
  1695. target[prop] = value;
  1696. } else {
  1697. console.error('unexpected color value:', value);
  1698. }
  1699. }
  1700. }
  1701. return result;
  1702. }
  1703. };
  1704. Color.prototype.spaces = {
  1705. rgb: ['red', 'green', 'blue'],
  1706. hsl: ['hue', 'saturation', 'lightness'],
  1707. hsv: ['hue', 'saturation', 'value'],
  1708. hwb: ['hue', 'whiteness', 'blackness'],
  1709. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1710. };
  1711. Color.prototype.maxes = {
  1712. rgb: [255, 255, 255],
  1713. hsl: [360, 100, 100],
  1714. hsv: [360, 100, 100],
  1715. hwb: [360, 100, 100],
  1716. cmyk: [100, 100, 100, 100]
  1717. };
  1718. Color.prototype.getValues = function (space) {
  1719. var values = this.values;
  1720. var vals = {};
  1721. for (var i = 0; i < space.length; i++) {
  1722. vals[space.charAt(i)] = values[space][i];
  1723. }
  1724. if (values.alpha !== 1) {
  1725. vals.a = values.alpha;
  1726. }
  1727. // {r: 255, g: 255, b: 255, a: 0.4}
  1728. return vals;
  1729. };
  1730. Color.prototype.setValues = function (space, vals) {
  1731. var values = this.values;
  1732. var spaces = this.spaces;
  1733. var maxes = this.maxes;
  1734. var alpha = 1;
  1735. var i;
  1736. this.valid = true;
  1737. if (space === 'alpha') {
  1738. alpha = vals;
  1739. } else if (vals.length) {
  1740. // [10, 10, 10]
  1741. values[space] = vals.slice(0, space.length);
  1742. alpha = vals[space.length];
  1743. } else if (vals[space.charAt(0)] !== undefined) {
  1744. // {r: 10, g: 10, b: 10}
  1745. for (i = 0; i < space.length; i++) {
  1746. values[space][i] = vals[space.charAt(i)];
  1747. }
  1748. alpha = vals.a;
  1749. } else if (vals[spaces[space][0]] !== undefined) {
  1750. // {red: 10, green: 10, blue: 10}
  1751. var chans = spaces[space];
  1752. for (i = 0; i < space.length; i++) {
  1753. values[space][i] = vals[chans[i]];
  1754. }
  1755. alpha = vals.alpha;
  1756. }
  1757. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1758. if (space === 'alpha') {
  1759. return false;
  1760. }
  1761. var capped;
  1762. // cap values of the space prior converting all values
  1763. for (i = 0; i < space.length; i++) {
  1764. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1765. values[space][i] = Math.round(capped);
  1766. }
  1767. // convert to all the other color spaces
  1768. for (var sname in spaces) {
  1769. if (sname !== space) {
  1770. values[sname] = colorConvert[space][sname](values[space]);
  1771. }
  1772. }
  1773. return true;
  1774. };
  1775. Color.prototype.setSpace = function (space, args) {
  1776. var vals = args[0];
  1777. if (vals === undefined) {
  1778. // color.rgb()
  1779. return this.getValues(space);
  1780. }
  1781. // color.rgb(10, 10, 10)
  1782. if (typeof vals === 'number') {
  1783. vals = Array.prototype.slice.call(args);
  1784. }
  1785. this.setValues(space, vals);
  1786. return this;
  1787. };
  1788. Color.prototype.setChannel = function (space, index, val) {
  1789. var svalues = this.values[space];
  1790. if (val === undefined) {
  1791. // color.red()
  1792. return svalues[index];
  1793. } else if (val === svalues[index]) {
  1794. // color.red(color.red())
  1795. return this;
  1796. }
  1797. // color.red(100)
  1798. svalues[index] = val;
  1799. this.setValues(space, svalues);
  1800. return this;
  1801. };
  1802. if (typeof window !== 'undefined') {
  1803. window.Color = Color;
  1804. }
  1805. var chartjsColor = Color;
  1806. /**
  1807. * @namespace Chart.helpers
  1808. */
  1809. var helpers = {
  1810. /**
  1811. * An empty function that can be used, for example, for optional callback.
  1812. */
  1813. noop: function() {},
  1814. /**
  1815. * Returns a unique id, sequentially generated from a global variable.
  1816. * @returns {number}
  1817. * @function
  1818. */
  1819. uid: (function() {
  1820. var id = 0;
  1821. return function() {
  1822. return id++;
  1823. };
  1824. }()),
  1825. /**
  1826. * Returns true if `value` is neither null nor undefined, else returns false.
  1827. * @param {*} value - The value to test.
  1828. * @returns {boolean}
  1829. * @since 2.7.0
  1830. */
  1831. isNullOrUndef: function(value) {
  1832. return value === null || typeof value === 'undefined';
  1833. },
  1834. /**
  1835. * Returns true if `value` is an array (including typed arrays), else returns false.
  1836. * @param {*} value - The value to test.
  1837. * @returns {boolean}
  1838. * @function
  1839. */
  1840. isArray: function(value) {
  1841. if (Array.isArray && Array.isArray(value)) {
  1842. return true;
  1843. }
  1844. var type = Object.prototype.toString.call(value);
  1845. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1846. return true;
  1847. }
  1848. return false;
  1849. },
  1850. /**
  1851. * Returns true if `value` is an object (excluding null), else returns false.
  1852. * @param {*} value - The value to test.
  1853. * @returns {boolean}
  1854. * @since 2.7.0
  1855. */
  1856. isObject: function(value) {
  1857. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1858. },
  1859. /**
  1860. * Returns true if `value` is a finite number, else returns false
  1861. * @param {*} value - The value to test.
  1862. * @returns {boolean}
  1863. */
  1864. isFinite: function(value) {
  1865. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1866. },
  1867. /**
  1868. * Returns `value` if defined, else returns `defaultValue`.
  1869. * @param {*} value - The value to return if defined.
  1870. * @param {*} defaultValue - The value to return if `value` is undefined.
  1871. * @returns {*}
  1872. */
  1873. valueOrDefault: function(value, defaultValue) {
  1874. return typeof value === 'undefined' ? defaultValue : value;
  1875. },
  1876. /**
  1877. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1878. * @param {Array} value - The array to lookup for value at `index`.
  1879. * @param {number} index - The index in `value` to lookup for value.
  1880. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1881. * @returns {*}
  1882. */
  1883. valueAtIndexOrDefault: function(value, index, defaultValue) {
  1884. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1885. },
  1886. /**
  1887. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1888. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1889. * @param {function} fn - The function to call.
  1890. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1891. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1892. * @returns {*}
  1893. */
  1894. callback: function(fn, args, thisArg) {
  1895. if (fn && typeof fn.call === 'function') {
  1896. return fn.apply(thisArg, args);
  1897. }
  1898. },
  1899. /**
  1900. * Note(SB) for performance sake, this method should only be used when loopable type
  1901. * is unknown or in none intensive code (not called often and small loopable). Else
  1902. * it's preferable to use a regular for() loop and save extra function calls.
  1903. * @param {object|Array} loopable - The object or array to be iterated.
  1904. * @param {function} fn - The function to call for each item.
  1905. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1906. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1907. */
  1908. each: function(loopable, fn, thisArg, reverse) {
  1909. var i, len, keys;
  1910. if (helpers.isArray(loopable)) {
  1911. len = loopable.length;
  1912. if (reverse) {
  1913. for (i = len - 1; i >= 0; i--) {
  1914. fn.call(thisArg, loopable[i], i);
  1915. }
  1916. } else {
  1917. for (i = 0; i < len; i++) {
  1918. fn.call(thisArg, loopable[i], i);
  1919. }
  1920. }
  1921. } else if (helpers.isObject(loopable)) {
  1922. keys = Object.keys(loopable);
  1923. len = keys.length;
  1924. for (i = 0; i < len; i++) {
  1925. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1926. }
  1927. }
  1928. },
  1929. /**
  1930. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1931. * @see https://stackoverflow.com/a/14853974
  1932. * @param {Array} a0 - The array to compare
  1933. * @param {Array} a1 - The array to compare
  1934. * @returns {boolean}
  1935. */
  1936. arrayEquals: function(a0, a1) {
  1937. var i, ilen, v0, v1;
  1938. if (!a0 || !a1 || a0.length !== a1.length) {
  1939. return false;
  1940. }
  1941. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1942. v0 = a0[i];
  1943. v1 = a1[i];
  1944. if (v0 instanceof Array && v1 instanceof Array) {
  1945. if (!helpers.arrayEquals(v0, v1)) {
  1946. return false;
  1947. }
  1948. } else if (v0 !== v1) {
  1949. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1950. return false;
  1951. }
  1952. }
  1953. return true;
  1954. },
  1955. /**
  1956. * Returns a deep copy of `source` without keeping references on objects and arrays.
  1957. * @param {*} source - The value to clone.
  1958. * @returns {*}
  1959. */
  1960. clone: function(source) {
  1961. if (helpers.isArray(source)) {
  1962. return source.map(helpers.clone);
  1963. }
  1964. if (helpers.isObject(source)) {
  1965. var target = {};
  1966. var keys = Object.keys(source);
  1967. var klen = keys.length;
  1968. var k = 0;
  1969. for (; k < klen; ++k) {
  1970. target[keys[k]] = helpers.clone(source[keys[k]]);
  1971. }
  1972. return target;
  1973. }
  1974. return source;
  1975. },
  1976. /**
  1977. * The default merger when Chart.helpers.merge is called without merger option.
  1978. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  1979. * @private
  1980. */
  1981. _merger: function(key, target, source, options) {
  1982. var tval = target[key];
  1983. var sval = source[key];
  1984. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1985. helpers.merge(tval, sval, options);
  1986. } else {
  1987. target[key] = helpers.clone(sval);
  1988. }
  1989. },
  1990. /**
  1991. * Merges source[key] in target[key] only if target[key] is undefined.
  1992. * @private
  1993. */
  1994. _mergerIf: function(key, target, source) {
  1995. var tval = target[key];
  1996. var sval = source[key];
  1997. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1998. helpers.mergeIf(tval, sval);
  1999. } else if (!target.hasOwnProperty(key)) {
  2000. target[key] = helpers.clone(sval);
  2001. }
  2002. },
  2003. /**
  2004. * Recursively deep copies `source` properties into `target` with the given `options`.
  2005. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2006. * @param {object} target - The target object in which all sources are merged into.
  2007. * @param {object|object[]} source - Object(s) to merge into `target`.
  2008. * @param {object} [options] - Merging options:
  2009. * @param {function} [options.merger] - The merge method (key, target, source, options)
  2010. * @returns {object} The `target` object.
  2011. */
  2012. merge: function(target, source, options) {
  2013. var sources = helpers.isArray(source) ? source : [source];
  2014. var ilen = sources.length;
  2015. var merge, i, keys, klen, k;
  2016. if (!helpers.isObject(target)) {
  2017. return target;
  2018. }
  2019. options = options || {};
  2020. merge = options.merger || helpers._merger;
  2021. for (i = 0; i < ilen; ++i) {
  2022. source = sources[i];
  2023. if (!helpers.isObject(source)) {
  2024. continue;
  2025. }
  2026. keys = Object.keys(source);
  2027. for (k = 0, klen = keys.length; k < klen; ++k) {
  2028. merge(keys[k], target, source, options);
  2029. }
  2030. }
  2031. return target;
  2032. },
  2033. /**
  2034. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  2035. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2036. * @param {object} target - The target object in which all sources are merged into.
  2037. * @param {object|object[]} source - Object(s) to merge into `target`.
  2038. * @returns {object} The `target` object.
  2039. */
  2040. mergeIf: function(target, source) {
  2041. return helpers.merge(target, source, {merger: helpers._mergerIf});
  2042. },
  2043. /**
  2044. * Applies the contents of two or more objects together into the first object.
  2045. * @param {object} target - The target object in which all objects are merged into.
  2046. * @param {object} arg1 - Object containing additional properties to merge in target.
  2047. * @param {object} argN - Additional objects containing properties to merge in target.
  2048. * @returns {object} The `target` object.
  2049. */
  2050. extend: Object.assign || function(target) {
  2051. return helpers.merge(target, [].slice.call(arguments, 1), {
  2052. merger: function(key, dst, src) {
  2053. dst[key] = src[key];
  2054. }
  2055. });
  2056. },
  2057. /**
  2058. * Basic javascript inheritance based on the model created in Backbone.js
  2059. */
  2060. inherits: function(extensions) {
  2061. var me = this;
  2062. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  2063. return me.apply(this, arguments);
  2064. };
  2065. var Surrogate = function() {
  2066. this.constructor = ChartElement;
  2067. };
  2068. Surrogate.prototype = me.prototype;
  2069. ChartElement.prototype = new Surrogate();
  2070. ChartElement.extend = helpers.inherits;
  2071. if (extensions) {
  2072. helpers.extend(ChartElement.prototype, extensions);
  2073. }
  2074. ChartElement.__super__ = me.prototype;
  2075. return ChartElement;
  2076. },
  2077. _deprecated: function(scope, value, previous, current) {
  2078. if (value !== undefined) {
  2079. console.warn(scope + ': "' + previous +
  2080. '" is deprecated. Please use "' + current + '" instead');
  2081. }
  2082. }
  2083. };
  2084. var helpers_core = helpers;
  2085. // DEPRECATIONS
  2086. /**
  2087. * Provided for backward compatibility, use Chart.helpers.callback instead.
  2088. * @function Chart.helpers.callCallback
  2089. * @deprecated since version 2.6.0
  2090. * @todo remove at version 3
  2091. * @private
  2092. */
  2093. helpers.callCallback = helpers.callback;
  2094. /**
  2095. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  2096. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  2097. * @function Chart.helpers.indexOf
  2098. * @deprecated since version 2.7.0
  2099. * @todo remove at version 3
  2100. * @private
  2101. */
  2102. helpers.indexOf = function(array, item, fromIndex) {
  2103. return Array.prototype.indexOf.call(array, item, fromIndex);
  2104. };
  2105. /**
  2106. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  2107. * @function Chart.helpers.getValueOrDefault
  2108. * @deprecated since version 2.7.0
  2109. * @todo remove at version 3
  2110. * @private
  2111. */
  2112. helpers.getValueOrDefault = helpers.valueOrDefault;
  2113. /**
  2114. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  2115. * @function Chart.helpers.getValueAtIndexOrDefault
  2116. * @deprecated since version 2.7.0
  2117. * @todo remove at version 3
  2118. * @private
  2119. */
  2120. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  2121. /**
  2122. * Easing functions adapted from Robert Penner's easing equations.
  2123. * @namespace Chart.helpers.easingEffects
  2124. * @see http://www.robertpenner.com/easing/
  2125. */
  2126. var effects = {
  2127. linear: function(t) {
  2128. return t;
  2129. },
  2130. easeInQuad: function(t) {
  2131. return t * t;
  2132. },
  2133. easeOutQuad: function(t) {
  2134. return -t * (t - 2);
  2135. },
  2136. easeInOutQuad: function(t) {
  2137. if ((t /= 0.5) < 1) {
  2138. return 0.5 * t * t;
  2139. }
  2140. return -0.5 * ((--t) * (t - 2) - 1);
  2141. },
  2142. easeInCubic: function(t) {
  2143. return t * t * t;
  2144. },
  2145. easeOutCubic: function(t) {
  2146. return (t = t - 1) * t * t + 1;
  2147. },
  2148. easeInOutCubic: function(t) {
  2149. if ((t /= 0.5) < 1) {
  2150. return 0.5 * t * t * t;
  2151. }
  2152. return 0.5 * ((t -= 2) * t * t + 2);
  2153. },
  2154. easeInQuart: function(t) {
  2155. return t * t * t * t;
  2156. },
  2157. easeOutQuart: function(t) {
  2158. return -((t = t - 1) * t * t * t - 1);
  2159. },
  2160. easeInOutQuart: function(t) {
  2161. if ((t /= 0.5) < 1) {
  2162. return 0.5 * t * t * t * t;
  2163. }
  2164. return -0.5 * ((t -= 2) * t * t * t - 2);
  2165. },
  2166. easeInQuint: function(t) {
  2167. return t * t * t * t * t;
  2168. },
  2169. easeOutQuint: function(t) {
  2170. return (t = t - 1) * t * t * t * t + 1;
  2171. },
  2172. easeInOutQuint: function(t) {
  2173. if ((t /= 0.5) < 1) {
  2174. return 0.5 * t * t * t * t * t;
  2175. }
  2176. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  2177. },
  2178. easeInSine: function(t) {
  2179. return -Math.cos(t * (Math.PI / 2)) + 1;
  2180. },
  2181. easeOutSine: function(t) {
  2182. return Math.sin(t * (Math.PI / 2));
  2183. },
  2184. easeInOutSine: function(t) {
  2185. return -0.5 * (Math.cos(Math.PI * t) - 1);
  2186. },
  2187. easeInExpo: function(t) {
  2188. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  2189. },
  2190. easeOutExpo: function(t) {
  2191. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  2192. },
  2193. easeInOutExpo: function(t) {
  2194. if (t === 0) {
  2195. return 0;
  2196. }
  2197. if (t === 1) {
  2198. return 1;
  2199. }
  2200. if ((t /= 0.5) < 1) {
  2201. return 0.5 * Math.pow(2, 10 * (t - 1));
  2202. }
  2203. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  2204. },
  2205. easeInCirc: function(t) {
  2206. if (t >= 1) {
  2207. return t;
  2208. }
  2209. return -(Math.sqrt(1 - t * t) - 1);
  2210. },
  2211. easeOutCirc: function(t) {
  2212. return Math.sqrt(1 - (t = t - 1) * t);
  2213. },
  2214. easeInOutCirc: function(t) {
  2215. if ((t /= 0.5) < 1) {
  2216. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  2217. }
  2218. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  2219. },
  2220. easeInElastic: function(t) {
  2221. var s = 1.70158;
  2222. var p = 0;
  2223. var a = 1;
  2224. if (t === 0) {
  2225. return 0;
  2226. }
  2227. if (t === 1) {
  2228. return 1;
  2229. }
  2230. if (!p) {
  2231. p = 0.3;
  2232. }
  2233. if (a < 1) {
  2234. a = 1;
  2235. s = p / 4;
  2236. } else {
  2237. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2238. }
  2239. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2240. },
  2241. easeOutElastic: function(t) {
  2242. var s = 1.70158;
  2243. var p = 0;
  2244. var a = 1;
  2245. if (t === 0) {
  2246. return 0;
  2247. }
  2248. if (t === 1) {
  2249. return 1;
  2250. }
  2251. if (!p) {
  2252. p = 0.3;
  2253. }
  2254. if (a < 1) {
  2255. a = 1;
  2256. s = p / 4;
  2257. } else {
  2258. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2259. }
  2260. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  2261. },
  2262. easeInOutElastic: function(t) {
  2263. var s = 1.70158;
  2264. var p = 0;
  2265. var a = 1;
  2266. if (t === 0) {
  2267. return 0;
  2268. }
  2269. if ((t /= 0.5) === 2) {
  2270. return 1;
  2271. }
  2272. if (!p) {
  2273. p = 0.45;
  2274. }
  2275. if (a < 1) {
  2276. a = 1;
  2277. s = p / 4;
  2278. } else {
  2279. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2280. }
  2281. if (t < 1) {
  2282. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2283. }
  2284. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2285. },
  2286. easeInBack: function(t) {
  2287. var s = 1.70158;
  2288. return t * t * ((s + 1) * t - s);
  2289. },
  2290. easeOutBack: function(t) {
  2291. var s = 1.70158;
  2292. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  2293. },
  2294. easeInOutBack: function(t) {
  2295. var s = 1.70158;
  2296. if ((t /= 0.5) < 1) {
  2297. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  2298. }
  2299. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  2300. },
  2301. easeInBounce: function(t) {
  2302. return 1 - effects.easeOutBounce(1 - t);
  2303. },
  2304. easeOutBounce: function(t) {
  2305. if (t < (1 / 2.75)) {
  2306. return 7.5625 * t * t;
  2307. }
  2308. if (t < (2 / 2.75)) {
  2309. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  2310. }
  2311. if (t < (2.5 / 2.75)) {
  2312. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  2313. }
  2314. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  2315. },
  2316. easeInOutBounce: function(t) {
  2317. if (t < 0.5) {
  2318. return effects.easeInBounce(t * 2) * 0.5;
  2319. }
  2320. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  2321. }
  2322. };
  2323. var helpers_easing = {
  2324. effects: effects
  2325. };
  2326. // DEPRECATIONS
  2327. /**
  2328. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  2329. * @function Chart.helpers.easingEffects
  2330. * @deprecated since version 2.7.0
  2331. * @todo remove at version 3
  2332. * @private
  2333. */
  2334. helpers_core.easingEffects = effects;
  2335. var PI = Math.PI;
  2336. var RAD_PER_DEG = PI / 180;
  2337. var DOUBLE_PI = PI * 2;
  2338. var HALF_PI = PI / 2;
  2339. var QUARTER_PI = PI / 4;
  2340. var TWO_THIRDS_PI = PI * 2 / 3;
  2341. /**
  2342. * @namespace Chart.helpers.canvas
  2343. */
  2344. var exports$1 = {
  2345. /**
  2346. * Clears the entire canvas associated to the given `chart`.
  2347. * @param {Chart} chart - The chart for which to clear the canvas.
  2348. */
  2349. clear: function(chart) {
  2350. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2351. },
  2352. /**
  2353. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2354. * given size (width, height) and the same `radius` for all corners.
  2355. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2356. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2357. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2358. * @param {number} width - The rectangle's width.
  2359. * @param {number} height - The rectangle's height.
  2360. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2361. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2362. */
  2363. roundedRect: function(ctx, x, y, width, height, radius) {
  2364. if (radius) {
  2365. var r = Math.min(radius, height / 2, width / 2);
  2366. var left = x + r;
  2367. var top = y + r;
  2368. var right = x + width - r;
  2369. var bottom = y + height - r;
  2370. ctx.moveTo(x, top);
  2371. if (left < right && top < bottom) {
  2372. ctx.arc(left, top, r, -PI, -HALF_PI);
  2373. ctx.arc(right, top, r, -HALF_PI, 0);
  2374. ctx.arc(right, bottom, r, 0, HALF_PI);
  2375. ctx.arc(left, bottom, r, HALF_PI, PI);
  2376. } else if (left < right) {
  2377. ctx.moveTo(left, y);
  2378. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2379. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2380. } else if (top < bottom) {
  2381. ctx.arc(left, top, r, -PI, 0);
  2382. ctx.arc(left, bottom, r, 0, PI);
  2383. } else {
  2384. ctx.arc(left, top, r, -PI, PI);
  2385. }
  2386. ctx.closePath();
  2387. ctx.moveTo(x, y);
  2388. } else {
  2389. ctx.rect(x, y, width, height);
  2390. }
  2391. },
  2392. drawPoint: function(ctx, style, radius, x, y, rotation) {
  2393. var type, xOffset, yOffset, size, cornerRadius;
  2394. var rad = (rotation || 0) * RAD_PER_DEG;
  2395. if (style && typeof style === 'object') {
  2396. type = style.toString();
  2397. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2398. ctx.save();
  2399. ctx.translate(x, y);
  2400. ctx.rotate(rad);
  2401. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  2402. ctx.restore();
  2403. return;
  2404. }
  2405. }
  2406. if (isNaN(radius) || radius <= 0) {
  2407. return;
  2408. }
  2409. ctx.beginPath();
  2410. switch (style) {
  2411. // Default includes circle
  2412. default:
  2413. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2414. ctx.closePath();
  2415. break;
  2416. case 'triangle':
  2417. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2418. rad += TWO_THIRDS_PI;
  2419. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2420. rad += TWO_THIRDS_PI;
  2421. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2422. ctx.closePath();
  2423. break;
  2424. case 'rectRounded':
  2425. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2426. // `quadraticCurveTo` since it generates better results when rect is
  2427. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2428. // closer proportion to the previous impl and it is inscribed in the
  2429. // circle with `radius`. For more details, see the following PRs:
  2430. // https://github.com/chartjs/Chart.js/issues/5597
  2431. // https://github.com/chartjs/Chart.js/issues/5858
  2432. cornerRadius = radius * 0.516;
  2433. size = radius - cornerRadius;
  2434. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2435. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2436. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2437. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2438. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2439. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2440. ctx.closePath();
  2441. break;
  2442. case 'rect':
  2443. if (!rotation) {
  2444. size = Math.SQRT1_2 * radius;
  2445. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2446. break;
  2447. }
  2448. rad += QUARTER_PI;
  2449. /* falls through */
  2450. case 'rectRot':
  2451. xOffset = Math.cos(rad) * radius;
  2452. yOffset = Math.sin(rad) * radius;
  2453. ctx.moveTo(x - xOffset, y - yOffset);
  2454. ctx.lineTo(x + yOffset, y - xOffset);
  2455. ctx.lineTo(x + xOffset, y + yOffset);
  2456. ctx.lineTo(x - yOffset, y + xOffset);
  2457. ctx.closePath();
  2458. break;
  2459. case 'crossRot':
  2460. rad += QUARTER_PI;
  2461. /* falls through */
  2462. case 'cross':
  2463. xOffset = Math.cos(rad) * radius;
  2464. yOffset = Math.sin(rad) * radius;
  2465. ctx.moveTo(x - xOffset, y - yOffset);
  2466. ctx.lineTo(x + xOffset, y + yOffset);
  2467. ctx.moveTo(x + yOffset, y - xOffset);
  2468. ctx.lineTo(x - yOffset, y + xOffset);
  2469. break;
  2470. case 'star':
  2471. xOffset = Math.cos(rad) * radius;
  2472. yOffset = Math.sin(rad) * radius;
  2473. ctx.moveTo(x - xOffset, y - yOffset);
  2474. ctx.lineTo(x + xOffset, y + yOffset);
  2475. ctx.moveTo(x + yOffset, y - xOffset);
  2476. ctx.lineTo(x - yOffset, y + xOffset);
  2477. rad += QUARTER_PI;
  2478. xOffset = Math.cos(rad) * radius;
  2479. yOffset = Math.sin(rad) * radius;
  2480. ctx.moveTo(x - xOffset, y - yOffset);
  2481. ctx.lineTo(x + xOffset, y + yOffset);
  2482. ctx.moveTo(x + yOffset, y - xOffset);
  2483. ctx.lineTo(x - yOffset, y + xOffset);
  2484. break;
  2485. case 'line':
  2486. xOffset = Math.cos(rad) * radius;
  2487. yOffset = Math.sin(rad) * radius;
  2488. ctx.moveTo(x - xOffset, y - yOffset);
  2489. ctx.lineTo(x + xOffset, y + yOffset);
  2490. break;
  2491. case 'dash':
  2492. ctx.moveTo(x, y);
  2493. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2494. break;
  2495. }
  2496. ctx.fill();
  2497. ctx.stroke();
  2498. },
  2499. /**
  2500. * Returns true if the point is inside the rectangle
  2501. * @param {object} point - The point to test
  2502. * @param {object} area - The rectangle
  2503. * @returns {boolean}
  2504. * @private
  2505. */
  2506. _isPointInArea: function(point, area) {
  2507. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2508. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2509. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2510. },
  2511. clipArea: function(ctx, area) {
  2512. ctx.save();
  2513. ctx.beginPath();
  2514. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2515. ctx.clip();
  2516. },
  2517. unclipArea: function(ctx) {
  2518. ctx.restore();
  2519. },
  2520. lineTo: function(ctx, previous, target, flip) {
  2521. var stepped = target.steppedLine;
  2522. if (stepped) {
  2523. if (stepped === 'middle') {
  2524. var midpoint = (previous.x + target.x) / 2.0;
  2525. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2526. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2527. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2528. ctx.lineTo(previous.x, target.y);
  2529. } else {
  2530. ctx.lineTo(target.x, previous.y);
  2531. }
  2532. ctx.lineTo(target.x, target.y);
  2533. return;
  2534. }
  2535. if (!target.tension) {
  2536. ctx.lineTo(target.x, target.y);
  2537. return;
  2538. }
  2539. ctx.bezierCurveTo(
  2540. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2541. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2542. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2543. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2544. target.x,
  2545. target.y);
  2546. }
  2547. };
  2548. var helpers_canvas = exports$1;
  2549. // DEPRECATIONS
  2550. /**
  2551. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2552. * @namespace Chart.helpers.clear
  2553. * @deprecated since version 2.7.0
  2554. * @todo remove at version 3
  2555. * @private
  2556. */
  2557. helpers_core.clear = exports$1.clear;
  2558. /**
  2559. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2560. * @namespace Chart.helpers.drawRoundedRectangle
  2561. * @deprecated since version 2.7.0
  2562. * @todo remove at version 3
  2563. * @private
  2564. */
  2565. helpers_core.drawRoundedRectangle = function(ctx) {
  2566. ctx.beginPath();
  2567. exports$1.roundedRect.apply(exports$1, arguments);
  2568. };
  2569. var defaults = {
  2570. /**
  2571. * @private
  2572. */
  2573. _set: function(scope, values) {
  2574. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2575. }
  2576. };
  2577. // TODO(v3): remove 'global' from namespace. all default are global and
  2578. // there's inconsistency around which options are under 'global'
  2579. defaults._set('global', {
  2580. defaultColor: 'rgba(0,0,0,0.1)',
  2581. defaultFontColor: '#666',
  2582. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2583. defaultFontSize: 12,
  2584. defaultFontStyle: 'normal',
  2585. defaultLineHeight: 1.2,
  2586. showLines: true
  2587. });
  2588. var core_defaults = defaults;
  2589. var valueOrDefault = helpers_core.valueOrDefault;
  2590. /**
  2591. * Converts the given font object into a CSS font string.
  2592. * @param {object} font - A font object.
  2593. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2594. * @private
  2595. */
  2596. function toFontString(font) {
  2597. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2598. return null;
  2599. }
  2600. return (font.style ? font.style + ' ' : '')
  2601. + (font.weight ? font.weight + ' ' : '')
  2602. + font.size + 'px '
  2603. + font.family;
  2604. }
  2605. /**
  2606. * @alias Chart.helpers.options
  2607. * @namespace
  2608. */
  2609. var helpers_options = {
  2610. /**
  2611. * Converts the given line height `value` in pixels for a specific font `size`.
  2612. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2613. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2614. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2615. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2616. * @since 2.7.0
  2617. */
  2618. toLineHeight: function(value, size) {
  2619. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2620. if (!matches || matches[1] === 'normal') {
  2621. return size * 1.2;
  2622. }
  2623. value = +matches[2];
  2624. switch (matches[3]) {
  2625. case 'px':
  2626. return value;
  2627. case '%':
  2628. value /= 100;
  2629. break;
  2630. }
  2631. return size * value;
  2632. },
  2633. /**
  2634. * Converts the given value into a padding object with pre-computed width/height.
  2635. * @param {number|object} value - If a number, set the value to all TRBL component,
  2636. * else, if and object, use defined properties and sets undefined ones to 0.
  2637. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2638. * @since 2.7.0
  2639. */
  2640. toPadding: function(value) {
  2641. var t, r, b, l;
  2642. if (helpers_core.isObject(value)) {
  2643. t = +value.top || 0;
  2644. r = +value.right || 0;
  2645. b = +value.bottom || 0;
  2646. l = +value.left || 0;
  2647. } else {
  2648. t = r = b = l = +value || 0;
  2649. }
  2650. return {
  2651. top: t,
  2652. right: r,
  2653. bottom: b,
  2654. left: l,
  2655. height: t + b,
  2656. width: l + r
  2657. };
  2658. },
  2659. /**
  2660. * Parses font options and returns the font object.
  2661. * @param {object} options - A object that contains font options to be parsed.
  2662. * @return {object} The font object.
  2663. * @todo Support font.* options and renamed to toFont().
  2664. * @private
  2665. */
  2666. _parseFont: function(options) {
  2667. var globalDefaults = core_defaults.global;
  2668. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2669. var font = {
  2670. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2671. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2672. size: size,
  2673. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2674. weight: null,
  2675. string: ''
  2676. };
  2677. font.string = toFontString(font);
  2678. return font;
  2679. },
  2680. /**
  2681. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2682. * @param {Array} inputs - An array of values, falling back to the last value.
  2683. * @param {object} [context] - If defined and the current value is a function, the value
  2684. * is called with `context` as first argument and the result becomes the new input.
  2685. * @param {number} [index] - If defined and the current value is an array, the value
  2686. * at `index` become the new input.
  2687. * @param {object} [info] - object to return information about resolution in
  2688. * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.
  2689. * @since 2.7.0
  2690. */
  2691. resolve: function(inputs, context, index, info) {
  2692. var cacheable = true;
  2693. var i, ilen, value;
  2694. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2695. value = inputs[i];
  2696. if (value === undefined) {
  2697. continue;
  2698. }
  2699. if (context !== undefined && typeof value === 'function') {
  2700. value = value(context);
  2701. cacheable = false;
  2702. }
  2703. if (index !== undefined && helpers_core.isArray(value)) {
  2704. value = value[index];
  2705. cacheable = false;
  2706. }
  2707. if (value !== undefined) {
  2708. if (info && !cacheable) {
  2709. info.cacheable = false;
  2710. }
  2711. return value;
  2712. }
  2713. }
  2714. }
  2715. };
  2716. /**
  2717. * @alias Chart.helpers.math
  2718. * @namespace
  2719. */
  2720. var exports$2 = {
  2721. /**
  2722. * Returns an array of factors sorted from 1 to sqrt(value)
  2723. * @private
  2724. */
  2725. _factorize: function(value) {
  2726. var result = [];
  2727. var sqrt = Math.sqrt(value);
  2728. var i;
  2729. for (i = 1; i < sqrt; i++) {
  2730. if (value % i === 0) {
  2731. result.push(i);
  2732. result.push(value / i);
  2733. }
  2734. }
  2735. if (sqrt === (sqrt | 0)) { // if value is a square number
  2736. result.push(sqrt);
  2737. }
  2738. result.sort(function(a, b) {
  2739. return a - b;
  2740. }).pop();
  2741. return result;
  2742. },
  2743. log10: Math.log10 || function(x) {
  2744. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  2745. // Check for whole powers of 10,
  2746. // which due to floating point rounding error should be corrected.
  2747. var powerOf10 = Math.round(exponent);
  2748. var isPowerOf10 = x === Math.pow(10, powerOf10);
  2749. return isPowerOf10 ? powerOf10 : exponent;
  2750. }
  2751. };
  2752. var helpers_math = exports$2;
  2753. // DEPRECATIONS
  2754. /**
  2755. * Provided for backward compatibility, use Chart.helpers.math.log10 instead.
  2756. * @namespace Chart.helpers.log10
  2757. * @deprecated since version 2.9.0
  2758. * @todo remove at version 3
  2759. * @private
  2760. */
  2761. helpers_core.log10 = exports$2.log10;
  2762. var getRtlAdapter = function(rectX, width) {
  2763. return {
  2764. x: function(x) {
  2765. return rectX + rectX + width - x;
  2766. },
  2767. setWidth: function(w) {
  2768. width = w;
  2769. },
  2770. textAlign: function(align) {
  2771. if (align === 'center') {
  2772. return align;
  2773. }
  2774. return align === 'right' ? 'left' : 'right';
  2775. },
  2776. xPlus: function(x, value) {
  2777. return x - value;
  2778. },
  2779. leftForLtr: function(x, itemWidth) {
  2780. return x - itemWidth;
  2781. },
  2782. };
  2783. };
  2784. var getLtrAdapter = function() {
  2785. return {
  2786. x: function(x) {
  2787. return x;
  2788. },
  2789. setWidth: function(w) { // eslint-disable-line no-unused-vars
  2790. },
  2791. textAlign: function(align) {
  2792. return align;
  2793. },
  2794. xPlus: function(x, value) {
  2795. return x + value;
  2796. },
  2797. leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars
  2798. return x;
  2799. },
  2800. };
  2801. };
  2802. var getAdapter = function(rtl, rectX, width) {
  2803. return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();
  2804. };
  2805. var overrideTextDirection = function(ctx, direction) {
  2806. var style, original;
  2807. if (direction === 'ltr' || direction === 'rtl') {
  2808. style = ctx.canvas.style;
  2809. original = [
  2810. style.getPropertyValue('direction'),
  2811. style.getPropertyPriority('direction'),
  2812. ];
  2813. style.setProperty('direction', direction, 'important');
  2814. ctx.prevTextDirection = original;
  2815. }
  2816. };
  2817. var restoreTextDirection = function(ctx) {
  2818. var original = ctx.prevTextDirection;
  2819. if (original !== undefined) {
  2820. delete ctx.prevTextDirection;
  2821. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  2822. }
  2823. };
  2824. var helpers_rtl = {
  2825. getRtlAdapter: getAdapter,
  2826. overrideTextDirection: overrideTextDirection,
  2827. restoreTextDirection: restoreTextDirection,
  2828. };
  2829. var helpers$1 = helpers_core;
  2830. var easing = helpers_easing;
  2831. var canvas = helpers_canvas;
  2832. var options = helpers_options;
  2833. var math = helpers_math;
  2834. var rtl = helpers_rtl;
  2835. helpers$1.easing = easing;
  2836. helpers$1.canvas = canvas;
  2837. helpers$1.options = options;
  2838. helpers$1.math = math;
  2839. helpers$1.rtl = rtl;
  2840. function interpolate(start, view, model, ease) {
  2841. var keys = Object.keys(model);
  2842. var i, ilen, key, actual, origin, target, type, c0, c1;
  2843. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2844. key = keys[i];
  2845. target = model[key];
  2846. // if a value is added to the model after pivot() has been called, the view
  2847. // doesn't contain it, so let's initialize the view to the target value.
  2848. if (!view.hasOwnProperty(key)) {
  2849. view[key] = target;
  2850. }
  2851. actual = view[key];
  2852. if (actual === target || key[0] === '_') {
  2853. continue;
  2854. }
  2855. if (!start.hasOwnProperty(key)) {
  2856. start[key] = actual;
  2857. }
  2858. origin = start[key];
  2859. type = typeof target;
  2860. if (type === typeof origin) {
  2861. if (type === 'string') {
  2862. c0 = chartjsColor(origin);
  2863. if (c0.valid) {
  2864. c1 = chartjsColor(target);
  2865. if (c1.valid) {
  2866. view[key] = c1.mix(c0, ease).rgbString();
  2867. continue;
  2868. }
  2869. }
  2870. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2871. view[key] = origin + (target - origin) * ease;
  2872. continue;
  2873. }
  2874. }
  2875. view[key] = target;
  2876. }
  2877. }
  2878. var Element = function(configuration) {
  2879. helpers$1.extend(this, configuration);
  2880. this.initialize.apply(this, arguments);
  2881. };
  2882. helpers$1.extend(Element.prototype, {
  2883. _type: undefined,
  2884. initialize: function() {
  2885. this.hidden = false;
  2886. },
  2887. pivot: function() {
  2888. var me = this;
  2889. if (!me._view) {
  2890. me._view = helpers$1.extend({}, me._model);
  2891. }
  2892. me._start = {};
  2893. return me;
  2894. },
  2895. transition: function(ease) {
  2896. var me = this;
  2897. var model = me._model;
  2898. var start = me._start;
  2899. var view = me._view;
  2900. // No animation -> No Transition
  2901. if (!model || ease === 1) {
  2902. me._view = helpers$1.extend({}, model);
  2903. me._start = null;
  2904. return me;
  2905. }
  2906. if (!view) {
  2907. view = me._view = {};
  2908. }
  2909. if (!start) {
  2910. start = me._start = {};
  2911. }
  2912. interpolate(start, view, model, ease);
  2913. return me;
  2914. },
  2915. tooltipPosition: function() {
  2916. return {
  2917. x: this._model.x,
  2918. y: this._model.y
  2919. };
  2920. },
  2921. hasValue: function() {
  2922. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2923. }
  2924. });
  2925. Element.extend = helpers$1.inherits;
  2926. var core_element = Element;
  2927. var exports$3 = core_element.extend({
  2928. chart: null, // the animation associated chart instance
  2929. currentStep: 0, // the current animation step
  2930. numSteps: 60, // default number of steps
  2931. easing: '', // the easing to use for this animation
  2932. render: null, // render function used by the animation service
  2933. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2934. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2935. });
  2936. var core_animation = exports$3;
  2937. // DEPRECATIONS
  2938. /**
  2939. * Provided for backward compatibility, use Chart.Animation instead
  2940. * @prop Chart.Animation#animationObject
  2941. * @deprecated since version 2.6.0
  2942. * @todo remove at version 3
  2943. */
  2944. Object.defineProperty(exports$3.prototype, 'animationObject', {
  2945. get: function() {
  2946. return this;
  2947. }
  2948. });
  2949. /**
  2950. * Provided for backward compatibility, use Chart.Animation#chart instead
  2951. * @prop Chart.Animation#chartInstance
  2952. * @deprecated since version 2.6.0
  2953. * @todo remove at version 3
  2954. */
  2955. Object.defineProperty(exports$3.prototype, 'chartInstance', {
  2956. get: function() {
  2957. return this.chart;
  2958. },
  2959. set: function(value) {
  2960. this.chart = value;
  2961. }
  2962. });
  2963. core_defaults._set('global', {
  2964. animation: {
  2965. duration: 1000,
  2966. easing: 'easeOutQuart',
  2967. onProgress: helpers$1.noop,
  2968. onComplete: helpers$1.noop
  2969. }
  2970. });
  2971. var core_animations = {
  2972. animations: [],
  2973. request: null,
  2974. /**
  2975. * @param {Chart} chart - The chart to animate.
  2976. * @param {Chart.Animation} animation - The animation that we will animate.
  2977. * @param {number} duration - The animation duration in ms.
  2978. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  2979. */
  2980. addAnimation: function(chart, animation, duration, lazy) {
  2981. var animations = this.animations;
  2982. var i, ilen;
  2983. animation.chart = chart;
  2984. animation.startTime = Date.now();
  2985. animation.duration = duration;
  2986. if (!lazy) {
  2987. chart.animating = true;
  2988. }
  2989. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  2990. if (animations[i].chart === chart) {
  2991. animations[i] = animation;
  2992. return;
  2993. }
  2994. }
  2995. animations.push(animation);
  2996. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  2997. if (animations.length === 1) {
  2998. this.requestAnimationFrame();
  2999. }
  3000. },
  3001. cancelAnimation: function(chart) {
  3002. var index = helpers$1.findIndex(this.animations, function(animation) {
  3003. return animation.chart === chart;
  3004. });
  3005. if (index !== -1) {
  3006. this.animations.splice(index, 1);
  3007. chart.animating = false;
  3008. }
  3009. },
  3010. requestAnimationFrame: function() {
  3011. var me = this;
  3012. if (me.request === null) {
  3013. // Skip animation frame requests until the active one is executed.
  3014. // This can happen when processing mouse events, e.g. 'mousemove'
  3015. // and 'mouseout' events will trigger multiple renders.
  3016. me.request = helpers$1.requestAnimFrame.call(window, function() {
  3017. me.request = null;
  3018. me.startDigest();
  3019. });
  3020. }
  3021. },
  3022. /**
  3023. * @private
  3024. */
  3025. startDigest: function() {
  3026. var me = this;
  3027. me.advance();
  3028. // Do we have more stuff to animate?
  3029. if (me.animations.length > 0) {
  3030. me.requestAnimationFrame();
  3031. }
  3032. },
  3033. /**
  3034. * @private
  3035. */
  3036. advance: function() {
  3037. var animations = this.animations;
  3038. var animation, chart, numSteps, nextStep;
  3039. var i = 0;
  3040. // 1 animation per chart, so we are looping charts here
  3041. while (i < animations.length) {
  3042. animation = animations[i];
  3043. chart = animation.chart;
  3044. numSteps = animation.numSteps;
  3045. // Make sure that currentStep starts at 1
  3046. // https://github.com/chartjs/Chart.js/issues/6104
  3047. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  3048. animation.currentStep = Math.min(nextStep, numSteps);
  3049. helpers$1.callback(animation.render, [chart, animation], chart);
  3050. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  3051. if (animation.currentStep >= numSteps) {
  3052. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  3053. chart.animating = false;
  3054. animations.splice(i, 1);
  3055. } else {
  3056. ++i;
  3057. }
  3058. }
  3059. }
  3060. };
  3061. var resolve = helpers$1.options.resolve;
  3062. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  3063. /**
  3064. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  3065. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  3066. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  3067. */
  3068. function listenArrayEvents(array, listener) {
  3069. if (array._chartjs) {
  3070. array._chartjs.listeners.push(listener);
  3071. return;
  3072. }
  3073. Object.defineProperty(array, '_chartjs', {
  3074. configurable: true,
  3075. enumerable: false,
  3076. value: {
  3077. listeners: [listener]
  3078. }
  3079. });
  3080. arrayEvents.forEach(function(key) {
  3081. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  3082. var base = array[key];
  3083. Object.defineProperty(array, key, {
  3084. configurable: true,
  3085. enumerable: false,
  3086. value: function() {
  3087. var args = Array.prototype.slice.call(arguments);
  3088. var res = base.apply(this, args);
  3089. helpers$1.each(array._chartjs.listeners, function(object) {
  3090. if (typeof object[method] === 'function') {
  3091. object[method].apply(object, args);
  3092. }
  3093. });
  3094. return res;
  3095. }
  3096. });
  3097. });
  3098. }
  3099. /**
  3100. * Removes the given array event listener and cleanup extra attached properties (such as
  3101. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  3102. */
  3103. function unlistenArrayEvents(array, listener) {
  3104. var stub = array._chartjs;
  3105. if (!stub) {
  3106. return;
  3107. }
  3108. var listeners = stub.listeners;
  3109. var index = listeners.indexOf(listener);
  3110. if (index !== -1) {
  3111. listeners.splice(index, 1);
  3112. }
  3113. if (listeners.length > 0) {
  3114. return;
  3115. }
  3116. arrayEvents.forEach(function(key) {
  3117. delete array[key];
  3118. });
  3119. delete array._chartjs;
  3120. }
  3121. // Base class for all dataset controllers (line, bar, etc)
  3122. var DatasetController = function(chart, datasetIndex) {
  3123. this.initialize(chart, datasetIndex);
  3124. };
  3125. helpers$1.extend(DatasetController.prototype, {
  3126. /**
  3127. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  3128. * @type {Chart.core.element}
  3129. */
  3130. datasetElementType: null,
  3131. /**
  3132. * Element type used to generate a meta data (e.g. Chart.element.Point).
  3133. * @type {Chart.core.element}
  3134. */
  3135. dataElementType: null,
  3136. /**
  3137. * Dataset element option keys to be resolved in _resolveDatasetElementOptions.
  3138. * A derived controller may override this to resolve controller-specific options.
  3139. * The keys defined here are for backward compatibility for legend styles.
  3140. * @private
  3141. */
  3142. _datasetElementOptions: [
  3143. 'backgroundColor',
  3144. 'borderCapStyle',
  3145. 'borderColor',
  3146. 'borderDash',
  3147. 'borderDashOffset',
  3148. 'borderJoinStyle',
  3149. 'borderWidth'
  3150. ],
  3151. /**
  3152. * Data element option keys to be resolved in _resolveDataElementOptions.
  3153. * A derived controller may override this to resolve controller-specific options.
  3154. * The keys defined here are for backward compatibility for legend styles.
  3155. * @private
  3156. */
  3157. _dataElementOptions: [
  3158. 'backgroundColor',
  3159. 'borderColor',
  3160. 'borderWidth',
  3161. 'pointStyle'
  3162. ],
  3163. initialize: function(chart, datasetIndex) {
  3164. var me = this;
  3165. me.chart = chart;
  3166. me.index = datasetIndex;
  3167. me.linkScales();
  3168. me.addElements();
  3169. me._type = me.getMeta().type;
  3170. },
  3171. updateIndex: function(datasetIndex) {
  3172. this.index = datasetIndex;
  3173. },
  3174. linkScales: function() {
  3175. var me = this;
  3176. var meta = me.getMeta();
  3177. var chart = me.chart;
  3178. var scales = chart.scales;
  3179. var dataset = me.getDataset();
  3180. var scalesOpts = chart.options.scales;
  3181. if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
  3182. meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
  3183. }
  3184. if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
  3185. meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
  3186. }
  3187. },
  3188. getDataset: function() {
  3189. return this.chart.data.datasets[this.index];
  3190. },
  3191. getMeta: function() {
  3192. return this.chart.getDatasetMeta(this.index);
  3193. },
  3194. getScaleForId: function(scaleID) {
  3195. return this.chart.scales[scaleID];
  3196. },
  3197. /**
  3198. * @private
  3199. */
  3200. _getValueScaleId: function() {
  3201. return this.getMeta().yAxisID;
  3202. },
  3203. /**
  3204. * @private
  3205. */
  3206. _getIndexScaleId: function() {
  3207. return this.getMeta().xAxisID;
  3208. },
  3209. /**
  3210. * @private
  3211. */
  3212. _getValueScale: function() {
  3213. return this.getScaleForId(this._getValueScaleId());
  3214. },
  3215. /**
  3216. * @private
  3217. */
  3218. _getIndexScale: function() {
  3219. return this.getScaleForId(this._getIndexScaleId());
  3220. },
  3221. reset: function() {
  3222. this._update(true);
  3223. },
  3224. /**
  3225. * @private
  3226. */
  3227. destroy: function() {
  3228. if (this._data) {
  3229. unlistenArrayEvents(this._data, this);
  3230. }
  3231. },
  3232. createMetaDataset: function() {
  3233. var me = this;
  3234. var type = me.datasetElementType;
  3235. return type && new type({
  3236. _chart: me.chart,
  3237. _datasetIndex: me.index
  3238. });
  3239. },
  3240. createMetaData: function(index) {
  3241. var me = this;
  3242. var type = me.dataElementType;
  3243. return type && new type({
  3244. _chart: me.chart,
  3245. _datasetIndex: me.index,
  3246. _index: index
  3247. });
  3248. },
  3249. addElements: function() {
  3250. var me = this;
  3251. var meta = me.getMeta();
  3252. var data = me.getDataset().data || [];
  3253. var metaData = meta.data;
  3254. var i, ilen;
  3255. for (i = 0, ilen = data.length; i < ilen; ++i) {
  3256. metaData[i] = metaData[i] || me.createMetaData(i);
  3257. }
  3258. meta.dataset = meta.dataset || me.createMetaDataset();
  3259. },
  3260. addElementAndReset: function(index) {
  3261. var element = this.createMetaData(index);
  3262. this.getMeta().data.splice(index, 0, element);
  3263. this.updateElement(element, index, true);
  3264. },
  3265. buildOrUpdateElements: function() {
  3266. var me = this;
  3267. var dataset = me.getDataset();
  3268. var data = dataset.data || (dataset.data = []);
  3269. // In order to correctly handle data addition/deletion animation (an thus simulate
  3270. // real-time charts), we need to monitor these data modifications and synchronize
  3271. // the internal meta data accordingly.
  3272. if (me._data !== data) {
  3273. if (me._data) {
  3274. // This case happens when the user replaced the data array instance.
  3275. unlistenArrayEvents(me._data, me);
  3276. }
  3277. if (data && Object.isExtensible(data)) {
  3278. listenArrayEvents(data, me);
  3279. }
  3280. me._data = data;
  3281. }
  3282. // Re-sync meta data in case the user replaced the data array or if we missed
  3283. // any updates and so make sure that we handle number of datapoints changing.
  3284. me.resyncElements();
  3285. },
  3286. /**
  3287. * Returns the merged user-supplied and default dataset-level options
  3288. * @private
  3289. */
  3290. _configure: function() {
  3291. var me = this;
  3292. me._config = helpers$1.merge({}, [
  3293. me.chart.options.datasets[me._type],
  3294. me.getDataset(),
  3295. ], {
  3296. merger: function(key, target, source) {
  3297. if (key !== '_meta' && key !== 'data') {
  3298. helpers$1._merger(key, target, source);
  3299. }
  3300. }
  3301. });
  3302. },
  3303. _update: function(reset) {
  3304. var me = this;
  3305. me._configure();
  3306. me._cachedDataOpts = null;
  3307. me.update(reset);
  3308. },
  3309. update: helpers$1.noop,
  3310. transition: function(easingValue) {
  3311. var meta = this.getMeta();
  3312. var elements = meta.data || [];
  3313. var ilen = elements.length;
  3314. var i = 0;
  3315. for (; i < ilen; ++i) {
  3316. elements[i].transition(easingValue);
  3317. }
  3318. if (meta.dataset) {
  3319. meta.dataset.transition(easingValue);
  3320. }
  3321. },
  3322. draw: function() {
  3323. var meta = this.getMeta();
  3324. var elements = meta.data || [];
  3325. var ilen = elements.length;
  3326. var i = 0;
  3327. if (meta.dataset) {
  3328. meta.dataset.draw();
  3329. }
  3330. for (; i < ilen; ++i) {
  3331. elements[i].draw();
  3332. }
  3333. },
  3334. /**
  3335. * Returns a set of predefined style properties that should be used to represent the dataset
  3336. * or the data if the index is specified
  3337. * @param {number} index - data index
  3338. * @return {IStyleInterface} style object
  3339. */
  3340. getStyle: function(index) {
  3341. var me = this;
  3342. var meta = me.getMeta();
  3343. var dataset = meta.dataset;
  3344. var style;
  3345. me._configure();
  3346. if (dataset && index === undefined) {
  3347. style = me._resolveDatasetElementOptions(dataset || {});
  3348. } else {
  3349. index = index || 0;
  3350. style = me._resolveDataElementOptions(meta.data[index] || {}, index);
  3351. }
  3352. if (style.fill === false || style.fill === null) {
  3353. style.backgroundColor = style.borderColor;
  3354. }
  3355. return style;
  3356. },
  3357. /**
  3358. * @private
  3359. */
  3360. _resolveDatasetElementOptions: function(element, hover) {
  3361. var me = this;
  3362. var chart = me.chart;
  3363. var datasetOpts = me._config;
  3364. var custom = element.custom || {};
  3365. var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
  3366. var elementOptions = me._datasetElementOptions;
  3367. var values = {};
  3368. var i, ilen, key, readKey;
  3369. // Scriptable options
  3370. var context = {
  3371. chart: chart,
  3372. dataset: me.getDataset(),
  3373. datasetIndex: me.index,
  3374. hover: hover
  3375. };
  3376. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3377. key = elementOptions[i];
  3378. readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
  3379. values[key] = resolve([
  3380. custom[readKey],
  3381. datasetOpts[readKey],
  3382. options[readKey]
  3383. ], context);
  3384. }
  3385. return values;
  3386. },
  3387. /**
  3388. * @private
  3389. */
  3390. _resolveDataElementOptions: function(element, index) {
  3391. var me = this;
  3392. var custom = element && element.custom;
  3393. var cached = me._cachedDataOpts;
  3394. if (cached && !custom) {
  3395. return cached;
  3396. }
  3397. var chart = me.chart;
  3398. var datasetOpts = me._config;
  3399. var options = chart.options.elements[me.dataElementType.prototype._type] || {};
  3400. var elementOptions = me._dataElementOptions;
  3401. var values = {};
  3402. // Scriptable options
  3403. var context = {
  3404. chart: chart,
  3405. dataIndex: index,
  3406. dataset: me.getDataset(),
  3407. datasetIndex: me.index
  3408. };
  3409. // `resolve` sets cacheable to `false` if any option is indexed or scripted
  3410. var info = {cacheable: !custom};
  3411. var keys, i, ilen, key;
  3412. custom = custom || {};
  3413. if (helpers$1.isArray(elementOptions)) {
  3414. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3415. key = elementOptions[i];
  3416. values[key] = resolve([
  3417. custom[key],
  3418. datasetOpts[key],
  3419. options[key]
  3420. ], context, index, info);
  3421. }
  3422. } else {
  3423. keys = Object.keys(elementOptions);
  3424. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3425. key = keys[i];
  3426. values[key] = resolve([
  3427. custom[key],
  3428. datasetOpts[elementOptions[key]],
  3429. datasetOpts[key],
  3430. options[key]
  3431. ], context, index, info);
  3432. }
  3433. }
  3434. if (info.cacheable) {
  3435. me._cachedDataOpts = Object.freeze(values);
  3436. }
  3437. return values;
  3438. },
  3439. removeHoverStyle: function(element) {
  3440. helpers$1.merge(element._model, element.$previousStyle || {});
  3441. delete element.$previousStyle;
  3442. },
  3443. setHoverStyle: function(element) {
  3444. var dataset = this.chart.data.datasets[element._datasetIndex];
  3445. var index = element._index;
  3446. var custom = element.custom || {};
  3447. var model = element._model;
  3448. var getHoverColor = helpers$1.getHoverColor;
  3449. element.$previousStyle = {
  3450. backgroundColor: model.backgroundColor,
  3451. borderColor: model.borderColor,
  3452. borderWidth: model.borderWidth
  3453. };
  3454. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  3455. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  3456. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  3457. },
  3458. /**
  3459. * @private
  3460. */
  3461. _removeDatasetHoverStyle: function() {
  3462. var element = this.getMeta().dataset;
  3463. if (element) {
  3464. this.removeHoverStyle(element);
  3465. }
  3466. },
  3467. /**
  3468. * @private
  3469. */
  3470. _setDatasetHoverStyle: function() {
  3471. var element = this.getMeta().dataset;
  3472. var prev = {};
  3473. var i, ilen, key, keys, hoverOptions, model;
  3474. if (!element) {
  3475. return;
  3476. }
  3477. model = element._model;
  3478. hoverOptions = this._resolveDatasetElementOptions(element, true);
  3479. keys = Object.keys(hoverOptions);
  3480. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3481. key = keys[i];
  3482. prev[key] = model[key];
  3483. model[key] = hoverOptions[key];
  3484. }
  3485. element.$previousStyle = prev;
  3486. },
  3487. /**
  3488. * @private
  3489. */
  3490. resyncElements: function() {
  3491. var me = this;
  3492. var meta = me.getMeta();
  3493. var data = me.getDataset().data;
  3494. var numMeta = meta.data.length;
  3495. var numData = data.length;
  3496. if (numData < numMeta) {
  3497. meta.data.splice(numData, numMeta - numData);
  3498. } else if (numData > numMeta) {
  3499. me.insertElements(numMeta, numData - numMeta);
  3500. }
  3501. },
  3502. /**
  3503. * @private
  3504. */
  3505. insertElements: function(start, count) {
  3506. for (var i = 0; i < count; ++i) {
  3507. this.addElementAndReset(start + i);
  3508. }
  3509. },
  3510. /**
  3511. * @private
  3512. */
  3513. onDataPush: function() {
  3514. var count = arguments.length;
  3515. this.insertElements(this.getDataset().data.length - count, count);
  3516. },
  3517. /**
  3518. * @private
  3519. */
  3520. onDataPop: function() {
  3521. this.getMeta().data.pop();
  3522. },
  3523. /**
  3524. * @private
  3525. */
  3526. onDataShift: function() {
  3527. this.getMeta().data.shift();
  3528. },
  3529. /**
  3530. * @private
  3531. */
  3532. onDataSplice: function(start, count) {
  3533. this.getMeta().data.splice(start, count);
  3534. this.insertElements(start, arguments.length - 2);
  3535. },
  3536. /**
  3537. * @private
  3538. */
  3539. onDataUnshift: function() {
  3540. this.insertElements(0, arguments.length);
  3541. }
  3542. });
  3543. DatasetController.extend = helpers$1.inherits;
  3544. var core_datasetController = DatasetController;
  3545. var TAU = Math.PI * 2;
  3546. core_defaults._set('global', {
  3547. elements: {
  3548. arc: {
  3549. backgroundColor: core_defaults.global.defaultColor,
  3550. borderColor: '#fff',
  3551. borderWidth: 2,
  3552. borderAlign: 'center'
  3553. }
  3554. }
  3555. });
  3556. function clipArc(ctx, arc) {
  3557. var startAngle = arc.startAngle;
  3558. var endAngle = arc.endAngle;
  3559. var pixelMargin = arc.pixelMargin;
  3560. var angleMargin = pixelMargin / arc.outerRadius;
  3561. var x = arc.x;
  3562. var y = arc.y;
  3563. // Draw an inner border by cliping the arc and drawing a double-width border
  3564. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  3565. ctx.beginPath();
  3566. ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  3567. if (arc.innerRadius > pixelMargin) {
  3568. angleMargin = pixelMargin / arc.innerRadius;
  3569. ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);
  3570. } else {
  3571. ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);
  3572. }
  3573. ctx.closePath();
  3574. ctx.clip();
  3575. }
  3576. function drawFullCircleBorders(ctx, vm, arc, inner) {
  3577. var endAngle = arc.endAngle;
  3578. var i;
  3579. if (inner) {
  3580. arc.endAngle = arc.startAngle + TAU;
  3581. clipArc(ctx, arc);
  3582. arc.endAngle = endAngle;
  3583. if (arc.endAngle === arc.startAngle && arc.fullCircles) {
  3584. arc.endAngle += TAU;
  3585. arc.fullCircles--;
  3586. }
  3587. }
  3588. ctx.beginPath();
  3589. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);
  3590. for (i = 0; i < arc.fullCircles; ++i) {
  3591. ctx.stroke();
  3592. }
  3593. ctx.beginPath();
  3594. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);
  3595. for (i = 0; i < arc.fullCircles; ++i) {
  3596. ctx.stroke();
  3597. }
  3598. }
  3599. function drawBorder(ctx, vm, arc) {
  3600. var inner = vm.borderAlign === 'inner';
  3601. if (inner) {
  3602. ctx.lineWidth = vm.borderWidth * 2;
  3603. ctx.lineJoin = 'round';
  3604. } else {
  3605. ctx.lineWidth = vm.borderWidth;
  3606. ctx.lineJoin = 'bevel';
  3607. }
  3608. if (arc.fullCircles) {
  3609. drawFullCircleBorders(ctx, vm, arc, inner);
  3610. }
  3611. if (inner) {
  3612. clipArc(ctx, arc);
  3613. }
  3614. ctx.beginPath();
  3615. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);
  3616. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3617. ctx.closePath();
  3618. ctx.stroke();
  3619. }
  3620. var element_arc = core_element.extend({
  3621. _type: 'arc',
  3622. inLabelRange: function(mouseX) {
  3623. var vm = this._view;
  3624. if (vm) {
  3625. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  3626. }
  3627. return false;
  3628. },
  3629. inRange: function(chartX, chartY) {
  3630. var vm = this._view;
  3631. if (vm) {
  3632. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  3633. var angle = pointRelativePosition.angle;
  3634. var distance = pointRelativePosition.distance;
  3635. // Sanitise angle range
  3636. var startAngle = vm.startAngle;
  3637. var endAngle = vm.endAngle;
  3638. while (endAngle < startAngle) {
  3639. endAngle += TAU;
  3640. }
  3641. while (angle > endAngle) {
  3642. angle -= TAU;
  3643. }
  3644. while (angle < startAngle) {
  3645. angle += TAU;
  3646. }
  3647. // Check if within the range of the open/close angle
  3648. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  3649. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  3650. return (betweenAngles && withinRadius);
  3651. }
  3652. return false;
  3653. },
  3654. getCenterPoint: function() {
  3655. var vm = this._view;
  3656. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  3657. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  3658. return {
  3659. x: vm.x + Math.cos(halfAngle) * halfRadius,
  3660. y: vm.y + Math.sin(halfAngle) * halfRadius
  3661. };
  3662. },
  3663. getArea: function() {
  3664. var vm = this._view;
  3665. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  3666. },
  3667. tooltipPosition: function() {
  3668. var vm = this._view;
  3669. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  3670. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  3671. return {
  3672. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  3673. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  3674. };
  3675. },
  3676. draw: function() {
  3677. var ctx = this._chart.ctx;
  3678. var vm = this._view;
  3679. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  3680. var arc = {
  3681. x: vm.x,
  3682. y: vm.y,
  3683. innerRadius: vm.innerRadius,
  3684. outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),
  3685. pixelMargin: pixelMargin,
  3686. startAngle: vm.startAngle,
  3687. endAngle: vm.endAngle,
  3688. fullCircles: Math.floor(vm.circumference / TAU)
  3689. };
  3690. var i;
  3691. ctx.save();
  3692. ctx.fillStyle = vm.backgroundColor;
  3693. ctx.strokeStyle = vm.borderColor;
  3694. if (arc.fullCircles) {
  3695. arc.endAngle = arc.startAngle + TAU;
  3696. ctx.beginPath();
  3697. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3698. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3699. ctx.closePath();
  3700. for (i = 0; i < arc.fullCircles; ++i) {
  3701. ctx.fill();
  3702. }
  3703. arc.endAngle = arc.startAngle + vm.circumference % TAU;
  3704. }
  3705. ctx.beginPath();
  3706. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3707. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3708. ctx.closePath();
  3709. ctx.fill();
  3710. if (vm.borderWidth) {
  3711. drawBorder(ctx, vm, arc);
  3712. }
  3713. ctx.restore();
  3714. }
  3715. });
  3716. var valueOrDefault$1 = helpers$1.valueOrDefault;
  3717. var defaultColor = core_defaults.global.defaultColor;
  3718. core_defaults._set('global', {
  3719. elements: {
  3720. line: {
  3721. tension: 0.4,
  3722. backgroundColor: defaultColor,
  3723. borderWidth: 3,
  3724. borderColor: defaultColor,
  3725. borderCapStyle: 'butt',
  3726. borderDash: [],
  3727. borderDashOffset: 0.0,
  3728. borderJoinStyle: 'miter',
  3729. capBezierPoints: true,
  3730. fill: true, // do we fill in the area between the line and its base axis
  3731. }
  3732. }
  3733. });
  3734. var element_line = core_element.extend({
  3735. _type: 'line',
  3736. draw: function() {
  3737. var me = this;
  3738. var vm = me._view;
  3739. var ctx = me._chart.ctx;
  3740. var spanGaps = vm.spanGaps;
  3741. var points = me._children.slice(); // clone array
  3742. var globalDefaults = core_defaults.global;
  3743. var globalOptionLineElements = globalDefaults.elements.line;
  3744. var lastDrawnIndex = -1;
  3745. var closePath = me._loop;
  3746. var index, previous, currentVM;
  3747. if (!points.length) {
  3748. return;
  3749. }
  3750. if (me._loop) {
  3751. for (index = 0; index < points.length; ++index) {
  3752. previous = helpers$1.previousItem(points, index);
  3753. // If the line has an open path, shift the point array
  3754. if (!points[index]._view.skip && previous._view.skip) {
  3755. points = points.slice(index).concat(points.slice(0, index));
  3756. closePath = spanGaps;
  3757. break;
  3758. }
  3759. }
  3760. // If the line has a close path, add the first point again
  3761. if (closePath) {
  3762. points.push(points[0]);
  3763. }
  3764. }
  3765. ctx.save();
  3766. // Stroke Line Options
  3767. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3768. // IE 9 and 10 do not support line dash
  3769. if (ctx.setLineDash) {
  3770. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3771. }
  3772. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3773. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3774. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3775. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3776. // Stroke Line
  3777. ctx.beginPath();
  3778. // First point moves to it's starting position no matter what
  3779. currentVM = points[0]._view;
  3780. if (!currentVM.skip) {
  3781. ctx.moveTo(currentVM.x, currentVM.y);
  3782. lastDrawnIndex = 0;
  3783. }
  3784. for (index = 1; index < points.length; ++index) {
  3785. currentVM = points[index]._view;
  3786. previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];
  3787. if (!currentVM.skip) {
  3788. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3789. // There was a gap and this is the first point after the gap
  3790. ctx.moveTo(currentVM.x, currentVM.y);
  3791. } else {
  3792. // Line to next point
  3793. helpers$1.canvas.lineTo(ctx, previous._view, currentVM);
  3794. }
  3795. lastDrawnIndex = index;
  3796. }
  3797. }
  3798. if (closePath) {
  3799. ctx.closePath();
  3800. }
  3801. ctx.stroke();
  3802. ctx.restore();
  3803. }
  3804. });
  3805. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3806. var defaultColor$1 = core_defaults.global.defaultColor;
  3807. core_defaults._set('global', {
  3808. elements: {
  3809. point: {
  3810. radius: 3,
  3811. pointStyle: 'circle',
  3812. backgroundColor: defaultColor$1,
  3813. borderColor: defaultColor$1,
  3814. borderWidth: 1,
  3815. // Hover
  3816. hitRadius: 1,
  3817. hoverRadius: 4,
  3818. hoverBorderWidth: 1
  3819. }
  3820. }
  3821. });
  3822. function xRange(mouseX) {
  3823. var vm = this._view;
  3824. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3825. }
  3826. function yRange(mouseY) {
  3827. var vm = this._view;
  3828. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3829. }
  3830. var element_point = core_element.extend({
  3831. _type: 'point',
  3832. inRange: function(mouseX, mouseY) {
  3833. var vm = this._view;
  3834. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3835. },
  3836. inLabelRange: xRange,
  3837. inXRange: xRange,
  3838. inYRange: yRange,
  3839. getCenterPoint: function() {
  3840. var vm = this._view;
  3841. return {
  3842. x: vm.x,
  3843. y: vm.y
  3844. };
  3845. },
  3846. getArea: function() {
  3847. return Math.PI * Math.pow(this._view.radius, 2);
  3848. },
  3849. tooltipPosition: function() {
  3850. var vm = this._view;
  3851. return {
  3852. x: vm.x,
  3853. y: vm.y,
  3854. padding: vm.radius + vm.borderWidth
  3855. };
  3856. },
  3857. draw: function(chartArea) {
  3858. var vm = this._view;
  3859. var ctx = this._chart.ctx;
  3860. var pointStyle = vm.pointStyle;
  3861. var rotation = vm.rotation;
  3862. var radius = vm.radius;
  3863. var x = vm.x;
  3864. var y = vm.y;
  3865. var globalDefaults = core_defaults.global;
  3866. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3867. if (vm.skip) {
  3868. return;
  3869. }
  3870. // Clipping for Points.
  3871. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3872. ctx.strokeStyle = vm.borderColor || defaultColor;
  3873. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3874. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3875. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3876. }
  3877. }
  3878. });
  3879. var defaultColor$2 = core_defaults.global.defaultColor;
  3880. core_defaults._set('global', {
  3881. elements: {
  3882. rectangle: {
  3883. backgroundColor: defaultColor$2,
  3884. borderColor: defaultColor$2,
  3885. borderSkipped: 'bottom',
  3886. borderWidth: 0
  3887. }
  3888. }
  3889. });
  3890. function isVertical(vm) {
  3891. return vm && vm.width !== undefined;
  3892. }
  3893. /**
  3894. * Helper function to get the bounds of the bar regardless of the orientation
  3895. * @param bar {Chart.Element.Rectangle} the bar
  3896. * @return {Bounds} bounds of the bar
  3897. * @private
  3898. */
  3899. function getBarBounds(vm) {
  3900. var x1, x2, y1, y2, half;
  3901. if (isVertical(vm)) {
  3902. half = vm.width / 2;
  3903. x1 = vm.x - half;
  3904. x2 = vm.x + half;
  3905. y1 = Math.min(vm.y, vm.base);
  3906. y2 = Math.max(vm.y, vm.base);
  3907. } else {
  3908. half = vm.height / 2;
  3909. x1 = Math.min(vm.x, vm.base);
  3910. x2 = Math.max(vm.x, vm.base);
  3911. y1 = vm.y - half;
  3912. y2 = vm.y + half;
  3913. }
  3914. return {
  3915. left: x1,
  3916. top: y1,
  3917. right: x2,
  3918. bottom: y2
  3919. };
  3920. }
  3921. function swap(orig, v1, v2) {
  3922. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3923. }
  3924. function parseBorderSkipped(vm) {
  3925. var edge = vm.borderSkipped;
  3926. var res = {};
  3927. if (!edge) {
  3928. return res;
  3929. }
  3930. if (vm.horizontal) {
  3931. if (vm.base > vm.x) {
  3932. edge = swap(edge, 'left', 'right');
  3933. }
  3934. } else if (vm.base < vm.y) {
  3935. edge = swap(edge, 'bottom', 'top');
  3936. }
  3937. res[edge] = true;
  3938. return res;
  3939. }
  3940. function parseBorderWidth(vm, maxW, maxH) {
  3941. var value = vm.borderWidth;
  3942. var skip = parseBorderSkipped(vm);
  3943. var t, r, b, l;
  3944. if (helpers$1.isObject(value)) {
  3945. t = +value.top || 0;
  3946. r = +value.right || 0;
  3947. b = +value.bottom || 0;
  3948. l = +value.left || 0;
  3949. } else {
  3950. t = r = b = l = +value || 0;
  3951. }
  3952. return {
  3953. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  3954. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  3955. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  3956. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  3957. };
  3958. }
  3959. function boundingRects(vm) {
  3960. var bounds = getBarBounds(vm);
  3961. var width = bounds.right - bounds.left;
  3962. var height = bounds.bottom - bounds.top;
  3963. var border = parseBorderWidth(vm, width / 2, height / 2);
  3964. return {
  3965. outer: {
  3966. x: bounds.left,
  3967. y: bounds.top,
  3968. w: width,
  3969. h: height
  3970. },
  3971. inner: {
  3972. x: bounds.left + border.l,
  3973. y: bounds.top + border.t,
  3974. w: width - border.l - border.r,
  3975. h: height - border.t - border.b
  3976. }
  3977. };
  3978. }
  3979. function inRange(vm, x, y) {
  3980. var skipX = x === null;
  3981. var skipY = y === null;
  3982. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  3983. return bounds
  3984. && (skipX || x >= bounds.left && x <= bounds.right)
  3985. && (skipY || y >= bounds.top && y <= bounds.bottom);
  3986. }
  3987. var element_rectangle = core_element.extend({
  3988. _type: 'rectangle',
  3989. draw: function() {
  3990. var ctx = this._chart.ctx;
  3991. var vm = this._view;
  3992. var rects = boundingRects(vm);
  3993. var outer = rects.outer;
  3994. var inner = rects.inner;
  3995. ctx.fillStyle = vm.backgroundColor;
  3996. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  3997. if (outer.w === inner.w && outer.h === inner.h) {
  3998. return;
  3999. }
  4000. ctx.save();
  4001. ctx.beginPath();
  4002. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  4003. ctx.clip();
  4004. ctx.fillStyle = vm.borderColor;
  4005. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  4006. ctx.fill('evenodd');
  4007. ctx.restore();
  4008. },
  4009. height: function() {
  4010. var vm = this._view;
  4011. return vm.base - vm.y;
  4012. },
  4013. inRange: function(mouseX, mouseY) {
  4014. return inRange(this._view, mouseX, mouseY);
  4015. },
  4016. inLabelRange: function(mouseX, mouseY) {
  4017. var vm = this._view;
  4018. return isVertical(vm)
  4019. ? inRange(vm, mouseX, null)
  4020. : inRange(vm, null, mouseY);
  4021. },
  4022. inXRange: function(mouseX) {
  4023. return inRange(this._view, mouseX, null);
  4024. },
  4025. inYRange: function(mouseY) {
  4026. return inRange(this._view, null, mouseY);
  4027. },
  4028. getCenterPoint: function() {
  4029. var vm = this._view;
  4030. var x, y;
  4031. if (isVertical(vm)) {
  4032. x = vm.x;
  4033. y = (vm.y + vm.base) / 2;
  4034. } else {
  4035. x = (vm.x + vm.base) / 2;
  4036. y = vm.y;
  4037. }
  4038. return {x: x, y: y};
  4039. },
  4040. getArea: function() {
  4041. var vm = this._view;
  4042. return isVertical(vm)
  4043. ? vm.width * Math.abs(vm.y - vm.base)
  4044. : vm.height * Math.abs(vm.x - vm.base);
  4045. },
  4046. tooltipPosition: function() {
  4047. var vm = this._view;
  4048. return {
  4049. x: vm.x,
  4050. y: vm.y
  4051. };
  4052. }
  4053. });
  4054. var elements = {};
  4055. var Arc = element_arc;
  4056. var Line = element_line;
  4057. var Point = element_point;
  4058. var Rectangle = element_rectangle;
  4059. elements.Arc = Arc;
  4060. elements.Line = Line;
  4061. elements.Point = Point;
  4062. elements.Rectangle = Rectangle;
  4063. var deprecated = helpers$1._deprecated;
  4064. var valueOrDefault$3 = helpers$1.valueOrDefault;
  4065. core_defaults._set('bar', {
  4066. hover: {
  4067. mode: 'label'
  4068. },
  4069. scales: {
  4070. xAxes: [{
  4071. type: 'category',
  4072. offset: true,
  4073. gridLines: {
  4074. offsetGridLines: true
  4075. }
  4076. }],
  4077. yAxes: [{
  4078. type: 'linear'
  4079. }]
  4080. }
  4081. });
  4082. core_defaults._set('global', {
  4083. datasets: {
  4084. bar: {
  4085. categoryPercentage: 0.8,
  4086. barPercentage: 0.9
  4087. }
  4088. }
  4089. });
  4090. /**
  4091. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  4092. * @private
  4093. */
  4094. function computeMinSampleSize(scale, pixels) {
  4095. var min = scale._length;
  4096. var prev, curr, i, ilen;
  4097. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  4098. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  4099. }
  4100. for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
  4101. curr = scale.getPixelForTick(i);
  4102. min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
  4103. prev = curr;
  4104. }
  4105. return min;
  4106. }
  4107. /**
  4108. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  4109. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  4110. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  4111. * @private
  4112. */
  4113. function computeFitCategoryTraits(index, ruler, options) {
  4114. var thickness = options.barThickness;
  4115. var count = ruler.stackCount;
  4116. var curr = ruler.pixels[index];
  4117. var min = helpers$1.isNullOrUndef(thickness)
  4118. ? computeMinSampleSize(ruler.scale, ruler.pixels)
  4119. : -1;
  4120. var size, ratio;
  4121. if (helpers$1.isNullOrUndef(thickness)) {
  4122. size = min * options.categoryPercentage;
  4123. ratio = options.barPercentage;
  4124. } else {
  4125. // When bar thickness is enforced, category and bar percentages are ignored.
  4126. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  4127. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  4128. size = thickness * count;
  4129. ratio = 1;
  4130. }
  4131. return {
  4132. chunk: size / count,
  4133. ratio: ratio,
  4134. start: curr - (size / 2)
  4135. };
  4136. }
  4137. /**
  4138. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  4139. * percentage options are 1), based on the previous and following categories. This mode
  4140. * generates bars with different widths when data are not evenly spaced.
  4141. * @private
  4142. */
  4143. function computeFlexCategoryTraits(index, ruler, options) {
  4144. var pixels = ruler.pixels;
  4145. var curr = pixels[index];
  4146. var prev = index > 0 ? pixels[index - 1] : null;
  4147. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  4148. var percent = options.categoryPercentage;
  4149. var start, size;
  4150. if (prev === null) {
  4151. // first data: its size is double based on the next point or,
  4152. // if it's also the last data, we use the scale size.
  4153. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  4154. }
  4155. if (next === null) {
  4156. // last data: its size is also double based on the previous point.
  4157. next = curr + curr - prev;
  4158. }
  4159. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  4160. size = Math.abs(next - prev) / 2 * percent;
  4161. return {
  4162. chunk: size / ruler.stackCount,
  4163. ratio: options.barPercentage,
  4164. start: start
  4165. };
  4166. }
  4167. var controller_bar = core_datasetController.extend({
  4168. dataElementType: elements.Rectangle,
  4169. /**
  4170. * @private
  4171. */
  4172. _dataElementOptions: [
  4173. 'backgroundColor',
  4174. 'borderColor',
  4175. 'borderSkipped',
  4176. 'borderWidth',
  4177. 'barPercentage',
  4178. 'barThickness',
  4179. 'categoryPercentage',
  4180. 'maxBarThickness',
  4181. 'minBarLength'
  4182. ],
  4183. initialize: function() {
  4184. var me = this;
  4185. var meta, scaleOpts;
  4186. core_datasetController.prototype.initialize.apply(me, arguments);
  4187. meta = me.getMeta();
  4188. meta.stack = me.getDataset().stack;
  4189. meta.bar = true;
  4190. scaleOpts = me._getIndexScale().options;
  4191. deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
  4192. deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
  4193. deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
  4194. deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
  4195. deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
  4196. },
  4197. update: function(reset) {
  4198. var me = this;
  4199. var rects = me.getMeta().data;
  4200. var i, ilen;
  4201. me._ruler = me.getRuler();
  4202. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  4203. me.updateElement(rects[i], i, reset);
  4204. }
  4205. },
  4206. updateElement: function(rectangle, index, reset) {
  4207. var me = this;
  4208. var meta = me.getMeta();
  4209. var dataset = me.getDataset();
  4210. var options = me._resolveDataElementOptions(rectangle, index);
  4211. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  4212. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  4213. rectangle._datasetIndex = me.index;
  4214. rectangle._index = index;
  4215. rectangle._model = {
  4216. backgroundColor: options.backgroundColor,
  4217. borderColor: options.borderColor,
  4218. borderSkipped: options.borderSkipped,
  4219. borderWidth: options.borderWidth,
  4220. datasetLabel: dataset.label,
  4221. label: me.chart.data.labels[index]
  4222. };
  4223. if (helpers$1.isArray(dataset.data[index])) {
  4224. rectangle._model.borderSkipped = null;
  4225. }
  4226. me._updateElementGeometry(rectangle, index, reset, options);
  4227. rectangle.pivot();
  4228. },
  4229. /**
  4230. * @private
  4231. */
  4232. _updateElementGeometry: function(rectangle, index, reset, options) {
  4233. var me = this;
  4234. var model = rectangle._model;
  4235. var vscale = me._getValueScale();
  4236. var base = vscale.getBasePixel();
  4237. var horizontal = vscale.isHorizontal();
  4238. var ruler = me._ruler || me.getRuler();
  4239. var vpixels = me.calculateBarValuePixels(me.index, index, options);
  4240. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
  4241. model.horizontal = horizontal;
  4242. model.base = reset ? base : vpixels.base;
  4243. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  4244. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  4245. model.height = horizontal ? ipixels.size : undefined;
  4246. model.width = horizontal ? undefined : ipixels.size;
  4247. },
  4248. /**
  4249. * Returns the stacks based on groups and bar visibility.
  4250. * @param {number} [last] - The dataset index
  4251. * @returns {string[]} The list of stack IDs
  4252. * @private
  4253. */
  4254. _getStacks: function(last) {
  4255. var me = this;
  4256. var scale = me._getIndexScale();
  4257. var metasets = scale._getMatchingVisibleMetas(me._type);
  4258. var stacked = scale.options.stacked;
  4259. var ilen = metasets.length;
  4260. var stacks = [];
  4261. var i, meta;
  4262. for (i = 0; i < ilen; ++i) {
  4263. meta = metasets[i];
  4264. // stacked | meta.stack
  4265. // | found | not found | undefined
  4266. // false | x | x | x
  4267. // true | | x |
  4268. // undefined | | x | x
  4269. if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
  4270. (stacked === undefined && meta.stack === undefined)) {
  4271. stacks.push(meta.stack);
  4272. }
  4273. if (meta.index === last) {
  4274. break;
  4275. }
  4276. }
  4277. return stacks;
  4278. },
  4279. /**
  4280. * Returns the effective number of stacks based on groups and bar visibility.
  4281. * @private
  4282. */
  4283. getStackCount: function() {
  4284. return this._getStacks().length;
  4285. },
  4286. /**
  4287. * Returns the stack index for the given dataset based on groups and bar visibility.
  4288. * @param {number} [datasetIndex] - The dataset index
  4289. * @param {string} [name] - The stack name to find
  4290. * @returns {number} The stack index
  4291. * @private
  4292. */
  4293. getStackIndex: function(datasetIndex, name) {
  4294. var stacks = this._getStacks(datasetIndex);
  4295. var index = (name !== undefined)
  4296. ? stacks.indexOf(name)
  4297. : -1; // indexOf returns -1 if element is not present
  4298. return (index === -1)
  4299. ? stacks.length - 1
  4300. : index;
  4301. },
  4302. /**
  4303. * @private
  4304. */
  4305. getRuler: function() {
  4306. var me = this;
  4307. var scale = me._getIndexScale();
  4308. var pixels = [];
  4309. var i, ilen;
  4310. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  4311. pixels.push(scale.getPixelForValue(null, i, me.index));
  4312. }
  4313. return {
  4314. pixels: pixels,
  4315. start: scale._startPixel,
  4316. end: scale._endPixel,
  4317. stackCount: me.getStackCount(),
  4318. scale: scale
  4319. };
  4320. },
  4321. /**
  4322. * Note: pixel values are not clamped to the scale area.
  4323. * @private
  4324. */
  4325. calculateBarValuePixels: function(datasetIndex, index, options) {
  4326. var me = this;
  4327. var chart = me.chart;
  4328. var scale = me._getValueScale();
  4329. var isHorizontal = scale.isHorizontal();
  4330. var datasets = chart.data.datasets;
  4331. var metasets = scale._getMatchingVisibleMetas(me._type);
  4332. var value = scale._parseValue(datasets[datasetIndex].data[index]);
  4333. var minBarLength = options.minBarLength;
  4334. var stacked = scale.options.stacked;
  4335. var stack = me.getMeta().stack;
  4336. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  4337. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  4338. var ilen = metasets.length;
  4339. var i, imeta, ivalue, base, head, size, stackLength;
  4340. if (stacked || (stacked === undefined && stack !== undefined)) {
  4341. for (i = 0; i < ilen; ++i) {
  4342. imeta = metasets[i];
  4343. if (imeta.index === datasetIndex) {
  4344. break;
  4345. }
  4346. if (imeta.stack === stack) {
  4347. stackLength = scale._parseValue(datasets[imeta.index].data[index]);
  4348. ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
  4349. if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
  4350. start += ivalue;
  4351. }
  4352. }
  4353. }
  4354. }
  4355. base = scale.getPixelForValue(start);
  4356. head = scale.getPixelForValue(start + length);
  4357. size = head - base;
  4358. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  4359. size = minBarLength;
  4360. if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
  4361. head = base - minBarLength;
  4362. } else {
  4363. head = base + minBarLength;
  4364. }
  4365. }
  4366. return {
  4367. size: size,
  4368. base: base,
  4369. head: head,
  4370. center: head + size / 2
  4371. };
  4372. },
  4373. /**
  4374. * @private
  4375. */
  4376. calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {
  4377. var me = this;
  4378. var range = options.barThickness === 'flex'
  4379. ? computeFlexCategoryTraits(index, ruler, options)
  4380. : computeFitCategoryTraits(index, ruler, options);
  4381. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  4382. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  4383. var size = Math.min(
  4384. valueOrDefault$3(options.maxBarThickness, Infinity),
  4385. range.chunk * range.ratio);
  4386. return {
  4387. base: center - size / 2,
  4388. head: center + size / 2,
  4389. center: center,
  4390. size: size
  4391. };
  4392. },
  4393. draw: function() {
  4394. var me = this;
  4395. var chart = me.chart;
  4396. var scale = me._getValueScale();
  4397. var rects = me.getMeta().data;
  4398. var dataset = me.getDataset();
  4399. var ilen = rects.length;
  4400. var i = 0;
  4401. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  4402. for (; i < ilen; ++i) {
  4403. var val = scale._parseValue(dataset.data[i]);
  4404. if (!isNaN(val.min) && !isNaN(val.max)) {
  4405. rects[i].draw();
  4406. }
  4407. }
  4408. helpers$1.canvas.unclipArea(chart.ctx);
  4409. },
  4410. /**
  4411. * @private
  4412. */
  4413. _resolveDataElementOptions: function() {
  4414. var me = this;
  4415. var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));
  4416. var indexOpts = me._getIndexScale().options;
  4417. var valueOpts = me._getValueScale().options;
  4418. values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);
  4419. values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);
  4420. values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);
  4421. values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);
  4422. values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);
  4423. return values;
  4424. }
  4425. });
  4426. var valueOrDefault$4 = helpers$1.valueOrDefault;
  4427. var resolve$1 = helpers$1.options.resolve;
  4428. core_defaults._set('bubble', {
  4429. hover: {
  4430. mode: 'single'
  4431. },
  4432. scales: {
  4433. xAxes: [{
  4434. type: 'linear', // bubble should probably use a linear scale by default
  4435. position: 'bottom',
  4436. id: 'x-axis-0' // need an ID so datasets can reference the scale
  4437. }],
  4438. yAxes: [{
  4439. type: 'linear',
  4440. position: 'left',
  4441. id: 'y-axis-0'
  4442. }]
  4443. },
  4444. tooltips: {
  4445. callbacks: {
  4446. title: function() {
  4447. // Title doesn't make sense for scatter since we format the data as a point
  4448. return '';
  4449. },
  4450. label: function(item, data) {
  4451. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  4452. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  4453. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  4454. }
  4455. }
  4456. }
  4457. });
  4458. var controller_bubble = core_datasetController.extend({
  4459. /**
  4460. * @protected
  4461. */
  4462. dataElementType: elements.Point,
  4463. /**
  4464. * @private
  4465. */
  4466. _dataElementOptions: [
  4467. 'backgroundColor',
  4468. 'borderColor',
  4469. 'borderWidth',
  4470. 'hoverBackgroundColor',
  4471. 'hoverBorderColor',
  4472. 'hoverBorderWidth',
  4473. 'hoverRadius',
  4474. 'hitRadius',
  4475. 'pointStyle',
  4476. 'rotation'
  4477. ],
  4478. /**
  4479. * @protected
  4480. */
  4481. update: function(reset) {
  4482. var me = this;
  4483. var meta = me.getMeta();
  4484. var points = meta.data;
  4485. // Update Points
  4486. helpers$1.each(points, function(point, index) {
  4487. me.updateElement(point, index, reset);
  4488. });
  4489. },
  4490. /**
  4491. * @protected
  4492. */
  4493. updateElement: function(point, index, reset) {
  4494. var me = this;
  4495. var meta = me.getMeta();
  4496. var custom = point.custom || {};
  4497. var xScale = me.getScaleForId(meta.xAxisID);
  4498. var yScale = me.getScaleForId(meta.yAxisID);
  4499. var options = me._resolveDataElementOptions(point, index);
  4500. var data = me.getDataset().data[index];
  4501. var dsIndex = me.index;
  4502. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  4503. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  4504. point._xScale = xScale;
  4505. point._yScale = yScale;
  4506. point._options = options;
  4507. point._datasetIndex = dsIndex;
  4508. point._index = index;
  4509. point._model = {
  4510. backgroundColor: options.backgroundColor,
  4511. borderColor: options.borderColor,
  4512. borderWidth: options.borderWidth,
  4513. hitRadius: options.hitRadius,
  4514. pointStyle: options.pointStyle,
  4515. rotation: options.rotation,
  4516. radius: reset ? 0 : options.radius,
  4517. skip: custom.skip || isNaN(x) || isNaN(y),
  4518. x: x,
  4519. y: y,
  4520. };
  4521. point.pivot();
  4522. },
  4523. /**
  4524. * @protected
  4525. */
  4526. setHoverStyle: function(point) {
  4527. var model = point._model;
  4528. var options = point._options;
  4529. var getHoverColor = helpers$1.getHoverColor;
  4530. point.$previousStyle = {
  4531. backgroundColor: model.backgroundColor,
  4532. borderColor: model.borderColor,
  4533. borderWidth: model.borderWidth,
  4534. radius: model.radius
  4535. };
  4536. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4537. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4538. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4539. model.radius = options.radius + options.hoverRadius;
  4540. },
  4541. /**
  4542. * @private
  4543. */
  4544. _resolveDataElementOptions: function(point, index) {
  4545. var me = this;
  4546. var chart = me.chart;
  4547. var dataset = me.getDataset();
  4548. var custom = point.custom || {};
  4549. var data = dataset.data[index] || {};
  4550. var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);
  4551. // Scriptable options
  4552. var context = {
  4553. chart: chart,
  4554. dataIndex: index,
  4555. dataset: dataset,
  4556. datasetIndex: me.index
  4557. };
  4558. // In case values were cached (and thus frozen), we need to clone the values
  4559. if (me._cachedDataOpts === values) {
  4560. values = helpers$1.extend({}, values);
  4561. }
  4562. // Custom radius resolution
  4563. values.radius = resolve$1([
  4564. custom.radius,
  4565. data.r,
  4566. me._config.radius,
  4567. chart.options.elements.point.radius
  4568. ], context, index);
  4569. return values;
  4570. }
  4571. });
  4572. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4573. var PI$1 = Math.PI;
  4574. var DOUBLE_PI$1 = PI$1 * 2;
  4575. var HALF_PI$1 = PI$1 / 2;
  4576. core_defaults._set('doughnut', {
  4577. animation: {
  4578. // Boolean - Whether we animate the rotation of the Doughnut
  4579. animateRotate: true,
  4580. // Boolean - Whether we animate scaling the Doughnut from the centre
  4581. animateScale: false
  4582. },
  4583. hover: {
  4584. mode: 'single'
  4585. },
  4586. legendCallback: function(chart) {
  4587. var list = document.createElement('ul');
  4588. var data = chart.data;
  4589. var datasets = data.datasets;
  4590. var labels = data.labels;
  4591. var i, ilen, listItem, listItemSpan;
  4592. list.setAttribute('class', chart.id + '-legend');
  4593. if (datasets.length) {
  4594. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  4595. listItem = list.appendChild(document.createElement('li'));
  4596. listItemSpan = listItem.appendChild(document.createElement('span'));
  4597. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  4598. if (labels[i]) {
  4599. listItem.appendChild(document.createTextNode(labels[i]));
  4600. }
  4601. }
  4602. }
  4603. return list.outerHTML;
  4604. },
  4605. legend: {
  4606. labels: {
  4607. generateLabels: function(chart) {
  4608. var data = chart.data;
  4609. if (data.labels.length && data.datasets.length) {
  4610. return data.labels.map(function(label, i) {
  4611. var meta = chart.getDatasetMeta(0);
  4612. var style = meta.controller.getStyle(i);
  4613. return {
  4614. text: label,
  4615. fillStyle: style.backgroundColor,
  4616. strokeStyle: style.borderColor,
  4617. lineWidth: style.borderWidth,
  4618. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  4619. // Extra data used for toggling the correct item
  4620. index: i
  4621. };
  4622. });
  4623. }
  4624. return [];
  4625. }
  4626. },
  4627. onClick: function(e, legendItem) {
  4628. var index = legendItem.index;
  4629. var chart = this.chart;
  4630. var i, ilen, meta;
  4631. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4632. meta = chart.getDatasetMeta(i);
  4633. // toggle visibility of index if exists
  4634. if (meta.data[index]) {
  4635. meta.data[index].hidden = !meta.data[index].hidden;
  4636. }
  4637. }
  4638. chart.update();
  4639. }
  4640. },
  4641. // The percentage of the chart that we cut out of the middle.
  4642. cutoutPercentage: 50,
  4643. // The rotation of the chart, where the first data arc begins.
  4644. rotation: -HALF_PI$1,
  4645. // The total circumference of the chart.
  4646. circumference: DOUBLE_PI$1,
  4647. // Need to override these to give a nice default
  4648. tooltips: {
  4649. callbacks: {
  4650. title: function() {
  4651. return '';
  4652. },
  4653. label: function(tooltipItem, data) {
  4654. var dataLabel = data.labels[tooltipItem.index];
  4655. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  4656. if (helpers$1.isArray(dataLabel)) {
  4657. // show value on first line of multiline label
  4658. // need to clone because we are changing the value
  4659. dataLabel = dataLabel.slice();
  4660. dataLabel[0] += value;
  4661. } else {
  4662. dataLabel += value;
  4663. }
  4664. return dataLabel;
  4665. }
  4666. }
  4667. }
  4668. });
  4669. var controller_doughnut = core_datasetController.extend({
  4670. dataElementType: elements.Arc,
  4671. linkScales: helpers$1.noop,
  4672. /**
  4673. * @private
  4674. */
  4675. _dataElementOptions: [
  4676. 'backgroundColor',
  4677. 'borderColor',
  4678. 'borderWidth',
  4679. 'borderAlign',
  4680. 'hoverBackgroundColor',
  4681. 'hoverBorderColor',
  4682. 'hoverBorderWidth',
  4683. ],
  4684. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  4685. getRingIndex: function(datasetIndex) {
  4686. var ringIndex = 0;
  4687. for (var j = 0; j < datasetIndex; ++j) {
  4688. if (this.chart.isDatasetVisible(j)) {
  4689. ++ringIndex;
  4690. }
  4691. }
  4692. return ringIndex;
  4693. },
  4694. update: function(reset) {
  4695. var me = this;
  4696. var chart = me.chart;
  4697. var chartArea = chart.chartArea;
  4698. var opts = chart.options;
  4699. var ratioX = 1;
  4700. var ratioY = 1;
  4701. var offsetX = 0;
  4702. var offsetY = 0;
  4703. var meta = me.getMeta();
  4704. var arcs = meta.data;
  4705. var cutout = opts.cutoutPercentage / 100 || 0;
  4706. var circumference = opts.circumference;
  4707. var chartWeight = me._getRingWeight(me.index);
  4708. var maxWidth, maxHeight, i, ilen;
  4709. // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
  4710. if (circumference < DOUBLE_PI$1) {
  4711. var startAngle = opts.rotation % DOUBLE_PI$1;
  4712. startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;
  4713. var endAngle = startAngle + circumference;
  4714. var startX = Math.cos(startAngle);
  4715. var startY = Math.sin(startAngle);
  4716. var endX = Math.cos(endAngle);
  4717. var endY = Math.sin(endAngle);
  4718. var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;
  4719. var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;
  4720. var contains180 = startAngle === -PI$1 || endAngle >= PI$1;
  4721. var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;
  4722. var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
  4723. var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
  4724. var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
  4725. var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
  4726. ratioX = (maxX - minX) / 2;
  4727. ratioY = (maxY - minY) / 2;
  4728. offsetX = -(maxX + minX) / 2;
  4729. offsetY = -(maxY + minY) / 2;
  4730. }
  4731. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4732. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  4733. }
  4734. chart.borderWidth = me.getMaxBorderWidth();
  4735. maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
  4736. maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
  4737. chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  4738. chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
  4739. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  4740. chart.offsetX = offsetX * chart.outerRadius;
  4741. chart.offsetY = offsetY * chart.outerRadius;
  4742. meta.total = me.calculateTotal();
  4743. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  4744. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  4745. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4746. me.updateElement(arcs[i], i, reset);
  4747. }
  4748. },
  4749. updateElement: function(arc, index, reset) {
  4750. var me = this;
  4751. var chart = me.chart;
  4752. var chartArea = chart.chartArea;
  4753. var opts = chart.options;
  4754. var animationOpts = opts.animation;
  4755. var centerX = (chartArea.left + chartArea.right) / 2;
  4756. var centerY = (chartArea.top + chartArea.bottom) / 2;
  4757. var startAngle = opts.rotation; // non reset case handled later
  4758. var endAngle = opts.rotation; // non reset case handled later
  4759. var dataset = me.getDataset();
  4760. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1);
  4761. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  4762. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  4763. var options = arc._options || {};
  4764. helpers$1.extend(arc, {
  4765. // Utility
  4766. _datasetIndex: me.index,
  4767. _index: index,
  4768. // Desired view properties
  4769. _model: {
  4770. backgroundColor: options.backgroundColor,
  4771. borderColor: options.borderColor,
  4772. borderWidth: options.borderWidth,
  4773. borderAlign: options.borderAlign,
  4774. x: centerX + chart.offsetX,
  4775. y: centerY + chart.offsetY,
  4776. startAngle: startAngle,
  4777. endAngle: endAngle,
  4778. circumference: circumference,
  4779. outerRadius: outerRadius,
  4780. innerRadius: innerRadius,
  4781. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4782. }
  4783. });
  4784. var model = arc._model;
  4785. // Set correct angles if not resetting
  4786. if (!reset || !animationOpts.animateRotate) {
  4787. if (index === 0) {
  4788. model.startAngle = opts.rotation;
  4789. } else {
  4790. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4791. }
  4792. model.endAngle = model.startAngle + model.circumference;
  4793. }
  4794. arc.pivot();
  4795. },
  4796. calculateTotal: function() {
  4797. var dataset = this.getDataset();
  4798. var meta = this.getMeta();
  4799. var total = 0;
  4800. var value;
  4801. helpers$1.each(meta.data, function(element, index) {
  4802. value = dataset.data[index];
  4803. if (!isNaN(value) && !element.hidden) {
  4804. total += Math.abs(value);
  4805. }
  4806. });
  4807. /* if (total === 0) {
  4808. total = NaN;
  4809. }*/
  4810. return total;
  4811. },
  4812. calculateCircumference: function(value) {
  4813. var total = this.getMeta().total;
  4814. if (total > 0 && !isNaN(value)) {
  4815. return DOUBLE_PI$1 * (Math.abs(value) / total);
  4816. }
  4817. return 0;
  4818. },
  4819. // gets the max border or hover width to properly scale pie charts
  4820. getMaxBorderWidth: function(arcs) {
  4821. var me = this;
  4822. var max = 0;
  4823. var chart = me.chart;
  4824. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4825. if (!arcs) {
  4826. // Find the outmost visible dataset
  4827. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4828. if (chart.isDatasetVisible(i)) {
  4829. meta = chart.getDatasetMeta(i);
  4830. arcs = meta.data;
  4831. if (i !== me.index) {
  4832. controller = meta.controller;
  4833. }
  4834. break;
  4835. }
  4836. }
  4837. }
  4838. if (!arcs) {
  4839. return 0;
  4840. }
  4841. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4842. arc = arcs[i];
  4843. if (controller) {
  4844. controller._configure();
  4845. options = controller._resolveDataElementOptions(arc, i);
  4846. } else {
  4847. options = arc._options;
  4848. }
  4849. if (options.borderAlign !== 'inner') {
  4850. borderWidth = options.borderWidth;
  4851. hoverWidth = options.hoverBorderWidth;
  4852. max = borderWidth > max ? borderWidth : max;
  4853. max = hoverWidth > max ? hoverWidth : max;
  4854. }
  4855. }
  4856. return max;
  4857. },
  4858. /**
  4859. * @protected
  4860. */
  4861. setHoverStyle: function(arc) {
  4862. var model = arc._model;
  4863. var options = arc._options;
  4864. var getHoverColor = helpers$1.getHoverColor;
  4865. arc.$previousStyle = {
  4866. backgroundColor: model.backgroundColor,
  4867. borderColor: model.borderColor,
  4868. borderWidth: model.borderWidth,
  4869. };
  4870. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4871. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4872. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4873. },
  4874. /**
  4875. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4876. * @private
  4877. */
  4878. _getRingWeightOffset: function(datasetIndex) {
  4879. var ringWeightOffset = 0;
  4880. for (var i = 0; i < datasetIndex; ++i) {
  4881. if (this.chart.isDatasetVisible(i)) {
  4882. ringWeightOffset += this._getRingWeight(i);
  4883. }
  4884. }
  4885. return ringWeightOffset;
  4886. },
  4887. /**
  4888. * @private
  4889. */
  4890. _getRingWeight: function(dataSetIndex) {
  4891. return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4892. },
  4893. /**
  4894. * Returns the sum of all visibile data set weights. This value can be 0.
  4895. * @private
  4896. */
  4897. _getVisibleDatasetWeightTotal: function() {
  4898. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4899. }
  4900. });
  4901. core_defaults._set('horizontalBar', {
  4902. hover: {
  4903. mode: 'index',
  4904. axis: 'y'
  4905. },
  4906. scales: {
  4907. xAxes: [{
  4908. type: 'linear',
  4909. position: 'bottom'
  4910. }],
  4911. yAxes: [{
  4912. type: 'category',
  4913. position: 'left',
  4914. offset: true,
  4915. gridLines: {
  4916. offsetGridLines: true
  4917. }
  4918. }]
  4919. },
  4920. elements: {
  4921. rectangle: {
  4922. borderSkipped: 'left'
  4923. }
  4924. },
  4925. tooltips: {
  4926. mode: 'index',
  4927. axis: 'y'
  4928. }
  4929. });
  4930. core_defaults._set('global', {
  4931. datasets: {
  4932. horizontalBar: {
  4933. categoryPercentage: 0.8,
  4934. barPercentage: 0.9
  4935. }
  4936. }
  4937. });
  4938. var controller_horizontalBar = controller_bar.extend({
  4939. /**
  4940. * @private
  4941. */
  4942. _getValueScaleId: function() {
  4943. return this.getMeta().xAxisID;
  4944. },
  4945. /**
  4946. * @private
  4947. */
  4948. _getIndexScaleId: function() {
  4949. return this.getMeta().yAxisID;
  4950. }
  4951. });
  4952. var valueOrDefault$6 = helpers$1.valueOrDefault;
  4953. var resolve$2 = helpers$1.options.resolve;
  4954. var isPointInArea = helpers$1.canvas._isPointInArea;
  4955. core_defaults._set('line', {
  4956. showLines: true,
  4957. spanGaps: false,
  4958. hover: {
  4959. mode: 'label'
  4960. },
  4961. scales: {
  4962. xAxes: [{
  4963. type: 'category',
  4964. id: 'x-axis-0'
  4965. }],
  4966. yAxes: [{
  4967. type: 'linear',
  4968. id: 'y-axis-0'
  4969. }]
  4970. }
  4971. });
  4972. function scaleClip(scale, halfBorderWidth) {
  4973. var tickOpts = scale && scale.options.ticks || {};
  4974. var reverse = tickOpts.reverse;
  4975. var min = tickOpts.min === undefined ? halfBorderWidth : 0;
  4976. var max = tickOpts.max === undefined ? halfBorderWidth : 0;
  4977. return {
  4978. start: reverse ? max : min,
  4979. end: reverse ? min : max
  4980. };
  4981. }
  4982. function defaultClip(xScale, yScale, borderWidth) {
  4983. var halfBorderWidth = borderWidth / 2;
  4984. var x = scaleClip(xScale, halfBorderWidth);
  4985. var y = scaleClip(yScale, halfBorderWidth);
  4986. return {
  4987. top: y.end,
  4988. right: x.end,
  4989. bottom: y.start,
  4990. left: x.start
  4991. };
  4992. }
  4993. function toClip(value) {
  4994. var t, r, b, l;
  4995. if (helpers$1.isObject(value)) {
  4996. t = value.top;
  4997. r = value.right;
  4998. b = value.bottom;
  4999. l = value.left;
  5000. } else {
  5001. t = r = b = l = value;
  5002. }
  5003. return {
  5004. top: t,
  5005. right: r,
  5006. bottom: b,
  5007. left: l
  5008. };
  5009. }
  5010. var controller_line = core_datasetController.extend({
  5011. datasetElementType: elements.Line,
  5012. dataElementType: elements.Point,
  5013. /**
  5014. * @private
  5015. */
  5016. _datasetElementOptions: [
  5017. 'backgroundColor',
  5018. 'borderCapStyle',
  5019. 'borderColor',
  5020. 'borderDash',
  5021. 'borderDashOffset',
  5022. 'borderJoinStyle',
  5023. 'borderWidth',
  5024. 'cubicInterpolationMode',
  5025. 'fill'
  5026. ],
  5027. /**
  5028. * @private
  5029. */
  5030. _dataElementOptions: {
  5031. backgroundColor: 'pointBackgroundColor',
  5032. borderColor: 'pointBorderColor',
  5033. borderWidth: 'pointBorderWidth',
  5034. hitRadius: 'pointHitRadius',
  5035. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5036. hoverBorderColor: 'pointHoverBorderColor',
  5037. hoverBorderWidth: 'pointHoverBorderWidth',
  5038. hoverRadius: 'pointHoverRadius',
  5039. pointStyle: 'pointStyle',
  5040. radius: 'pointRadius',
  5041. rotation: 'pointRotation'
  5042. },
  5043. update: function(reset) {
  5044. var me = this;
  5045. var meta = me.getMeta();
  5046. var line = meta.dataset;
  5047. var points = meta.data || [];
  5048. var options = me.chart.options;
  5049. var config = me._config;
  5050. var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);
  5051. var i, ilen;
  5052. me._xScale = me.getScaleForId(meta.xAxisID);
  5053. me._yScale = me.getScaleForId(meta.yAxisID);
  5054. // Update Line
  5055. if (showLine) {
  5056. // Compatibility: If the properties are defined with only the old name, use those values
  5057. if (config.tension !== undefined && config.lineTension === undefined) {
  5058. config.lineTension = config.tension;
  5059. }
  5060. // Utility
  5061. line._scale = me._yScale;
  5062. line._datasetIndex = me.index;
  5063. // Data
  5064. line._children = points;
  5065. // Model
  5066. line._model = me._resolveDatasetElementOptions(line);
  5067. line.pivot();
  5068. }
  5069. // Update Points
  5070. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5071. me.updateElement(points[i], i, reset);
  5072. }
  5073. if (showLine && line._model.tension !== 0) {
  5074. me.updateBezierControlPoints();
  5075. }
  5076. // Now pivot the point for animation
  5077. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5078. points[i].pivot();
  5079. }
  5080. },
  5081. updateElement: function(point, index, reset) {
  5082. var me = this;
  5083. var meta = me.getMeta();
  5084. var custom = point.custom || {};
  5085. var dataset = me.getDataset();
  5086. var datasetIndex = me.index;
  5087. var value = dataset.data[index];
  5088. var xScale = me._xScale;
  5089. var yScale = me._yScale;
  5090. var lineModel = meta.dataset._model;
  5091. var x, y;
  5092. var options = me._resolveDataElementOptions(point, index);
  5093. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  5094. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  5095. // Utility
  5096. point._xScale = xScale;
  5097. point._yScale = yScale;
  5098. point._options = options;
  5099. point._datasetIndex = datasetIndex;
  5100. point._index = index;
  5101. // Desired view properties
  5102. point._model = {
  5103. x: x,
  5104. y: y,
  5105. skip: custom.skip || isNaN(x) || isNaN(y),
  5106. // Appearance
  5107. radius: options.radius,
  5108. pointStyle: options.pointStyle,
  5109. rotation: options.rotation,
  5110. backgroundColor: options.backgroundColor,
  5111. borderColor: options.borderColor,
  5112. borderWidth: options.borderWidth,
  5113. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  5114. steppedLine: lineModel ? lineModel.steppedLine : false,
  5115. // Tooltip
  5116. hitRadius: options.hitRadius
  5117. };
  5118. },
  5119. /**
  5120. * @private
  5121. */
  5122. _resolveDatasetElementOptions: function(element) {
  5123. var me = this;
  5124. var config = me._config;
  5125. var custom = element.custom || {};
  5126. var options = me.chart.options;
  5127. var lineOptions = options.elements.line;
  5128. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5129. // The default behavior of lines is to break at null values, according
  5130. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  5131. // This option gives lines the ability to span gaps
  5132. values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps);
  5133. values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);
  5134. values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
  5135. values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
  5136. return values;
  5137. },
  5138. calculatePointY: function(value, index, datasetIndex) {
  5139. var me = this;
  5140. var chart = me.chart;
  5141. var yScale = me._yScale;
  5142. var sumPos = 0;
  5143. var sumNeg = 0;
  5144. var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
  5145. if (yScale.options.stacked) {
  5146. rightValue = +yScale.getRightValue(value);
  5147. metasets = chart._getSortedVisibleDatasetMetas();
  5148. ilen = metasets.length;
  5149. for (i = 0; i < ilen; ++i) {
  5150. dsMeta = metasets[i];
  5151. if (dsMeta.index === datasetIndex) {
  5152. break;
  5153. }
  5154. ds = chart.data.datasets[dsMeta.index];
  5155. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
  5156. stackedRightValue = +yScale.getRightValue(ds.data[index]);
  5157. if (stackedRightValue < 0) {
  5158. sumNeg += stackedRightValue || 0;
  5159. } else {
  5160. sumPos += stackedRightValue || 0;
  5161. }
  5162. }
  5163. }
  5164. if (rightValue < 0) {
  5165. return yScale.getPixelForValue(sumNeg + rightValue);
  5166. }
  5167. return yScale.getPixelForValue(sumPos + rightValue);
  5168. }
  5169. return yScale.getPixelForValue(value);
  5170. },
  5171. updateBezierControlPoints: function() {
  5172. var me = this;
  5173. var chart = me.chart;
  5174. var meta = me.getMeta();
  5175. var lineModel = meta.dataset._model;
  5176. var area = chart.chartArea;
  5177. var points = meta.data || [];
  5178. var i, ilen, model, controlPoints;
  5179. // Only consider points that are drawn in case the spanGaps option is used
  5180. if (lineModel.spanGaps) {
  5181. points = points.filter(function(pt) {
  5182. return !pt._model.skip;
  5183. });
  5184. }
  5185. function capControlPoint(pt, min, max) {
  5186. return Math.max(Math.min(pt, max), min);
  5187. }
  5188. if (lineModel.cubicInterpolationMode === 'monotone') {
  5189. helpers$1.splineCurveMonotone(points);
  5190. } else {
  5191. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5192. model = points[i]._model;
  5193. controlPoints = helpers$1.splineCurve(
  5194. helpers$1.previousItem(points, i)._model,
  5195. model,
  5196. helpers$1.nextItem(points, i)._model,
  5197. lineModel.tension
  5198. );
  5199. model.controlPointPreviousX = controlPoints.previous.x;
  5200. model.controlPointPreviousY = controlPoints.previous.y;
  5201. model.controlPointNextX = controlPoints.next.x;
  5202. model.controlPointNextY = controlPoints.next.y;
  5203. }
  5204. }
  5205. if (chart.options.elements.line.capBezierPoints) {
  5206. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5207. model = points[i]._model;
  5208. if (isPointInArea(model, area)) {
  5209. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  5210. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  5211. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  5212. }
  5213. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  5214. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  5215. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  5216. }
  5217. }
  5218. }
  5219. }
  5220. },
  5221. draw: function() {
  5222. var me = this;
  5223. var chart = me.chart;
  5224. var meta = me.getMeta();
  5225. var points = meta.data || [];
  5226. var area = chart.chartArea;
  5227. var canvas = chart.canvas;
  5228. var i = 0;
  5229. var ilen = points.length;
  5230. var clip;
  5231. if (me._showLine) {
  5232. clip = meta.dataset._model.clip;
  5233. helpers$1.canvas.clipArea(chart.ctx, {
  5234. left: clip.left === false ? 0 : area.left - clip.left,
  5235. right: clip.right === false ? canvas.width : area.right + clip.right,
  5236. top: clip.top === false ? 0 : area.top - clip.top,
  5237. bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
  5238. });
  5239. meta.dataset.draw();
  5240. helpers$1.canvas.unclipArea(chart.ctx);
  5241. }
  5242. // Draw the points
  5243. for (; i < ilen; ++i) {
  5244. points[i].draw(area);
  5245. }
  5246. },
  5247. /**
  5248. * @protected
  5249. */
  5250. setHoverStyle: function(point) {
  5251. var model = point._model;
  5252. var options = point._options;
  5253. var getHoverColor = helpers$1.getHoverColor;
  5254. point.$previousStyle = {
  5255. backgroundColor: model.backgroundColor,
  5256. borderColor: model.borderColor,
  5257. borderWidth: model.borderWidth,
  5258. radius: model.radius
  5259. };
  5260. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5261. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  5262. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  5263. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  5264. },
  5265. });
  5266. var resolve$3 = helpers$1.options.resolve;
  5267. core_defaults._set('polarArea', {
  5268. scale: {
  5269. type: 'radialLinear',
  5270. angleLines: {
  5271. display: false
  5272. },
  5273. gridLines: {
  5274. circular: true
  5275. },
  5276. pointLabels: {
  5277. display: false
  5278. },
  5279. ticks: {
  5280. beginAtZero: true
  5281. }
  5282. },
  5283. // Boolean - Whether to animate the rotation of the chart
  5284. animation: {
  5285. animateRotate: true,
  5286. animateScale: true
  5287. },
  5288. startAngle: -0.5 * Math.PI,
  5289. legendCallback: function(chart) {
  5290. var list = document.createElement('ul');
  5291. var data = chart.data;
  5292. var datasets = data.datasets;
  5293. var labels = data.labels;
  5294. var i, ilen, listItem, listItemSpan;
  5295. list.setAttribute('class', chart.id + '-legend');
  5296. if (datasets.length) {
  5297. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  5298. listItem = list.appendChild(document.createElement('li'));
  5299. listItemSpan = listItem.appendChild(document.createElement('span'));
  5300. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  5301. if (labels[i]) {
  5302. listItem.appendChild(document.createTextNode(labels[i]));
  5303. }
  5304. }
  5305. }
  5306. return list.outerHTML;
  5307. },
  5308. legend: {
  5309. labels: {
  5310. generateLabels: function(chart) {
  5311. var data = chart.data;
  5312. if (data.labels.length && data.datasets.length) {
  5313. return data.labels.map(function(label, i) {
  5314. var meta = chart.getDatasetMeta(0);
  5315. var style = meta.controller.getStyle(i);
  5316. return {
  5317. text: label,
  5318. fillStyle: style.backgroundColor,
  5319. strokeStyle: style.borderColor,
  5320. lineWidth: style.borderWidth,
  5321. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  5322. // Extra data used for toggling the correct item
  5323. index: i
  5324. };
  5325. });
  5326. }
  5327. return [];
  5328. }
  5329. },
  5330. onClick: function(e, legendItem) {
  5331. var index = legendItem.index;
  5332. var chart = this.chart;
  5333. var i, ilen, meta;
  5334. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  5335. meta = chart.getDatasetMeta(i);
  5336. meta.data[index].hidden = !meta.data[index].hidden;
  5337. }
  5338. chart.update();
  5339. }
  5340. },
  5341. // Need to override these to give a nice default
  5342. tooltips: {
  5343. callbacks: {
  5344. title: function() {
  5345. return '';
  5346. },
  5347. label: function(item, data) {
  5348. return data.labels[item.index] + ': ' + item.yLabel;
  5349. }
  5350. }
  5351. }
  5352. });
  5353. var controller_polarArea = core_datasetController.extend({
  5354. dataElementType: elements.Arc,
  5355. linkScales: helpers$1.noop,
  5356. /**
  5357. * @private
  5358. */
  5359. _dataElementOptions: [
  5360. 'backgroundColor',
  5361. 'borderColor',
  5362. 'borderWidth',
  5363. 'borderAlign',
  5364. 'hoverBackgroundColor',
  5365. 'hoverBorderColor',
  5366. 'hoverBorderWidth',
  5367. ],
  5368. /**
  5369. * @private
  5370. */
  5371. _getIndexScaleId: function() {
  5372. return this.chart.scale.id;
  5373. },
  5374. /**
  5375. * @private
  5376. */
  5377. _getValueScaleId: function() {
  5378. return this.chart.scale.id;
  5379. },
  5380. update: function(reset) {
  5381. var me = this;
  5382. var dataset = me.getDataset();
  5383. var meta = me.getMeta();
  5384. var start = me.chart.options.startAngle || 0;
  5385. var starts = me._starts = [];
  5386. var angles = me._angles = [];
  5387. var arcs = meta.data;
  5388. var i, ilen, angle;
  5389. me._updateRadius();
  5390. meta.count = me.countVisibleElements();
  5391. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  5392. starts[i] = start;
  5393. angle = me._computeAngle(i);
  5394. angles[i] = angle;
  5395. start += angle;
  5396. }
  5397. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  5398. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  5399. me.updateElement(arcs[i], i, reset);
  5400. }
  5401. },
  5402. /**
  5403. * @private
  5404. */
  5405. _updateRadius: function() {
  5406. var me = this;
  5407. var chart = me.chart;
  5408. var chartArea = chart.chartArea;
  5409. var opts = chart.options;
  5410. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  5411. chart.outerRadius = Math.max(minSize / 2, 0);
  5412. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  5413. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  5414. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  5415. me.innerRadius = me.outerRadius - chart.radiusLength;
  5416. },
  5417. updateElement: function(arc, index, reset) {
  5418. var me = this;
  5419. var chart = me.chart;
  5420. var dataset = me.getDataset();
  5421. var opts = chart.options;
  5422. var animationOpts = opts.animation;
  5423. var scale = chart.scale;
  5424. var labels = chart.data.labels;
  5425. var centerX = scale.xCenter;
  5426. var centerY = scale.yCenter;
  5427. // var negHalfPI = -0.5 * Math.PI;
  5428. var datasetStartAngle = opts.startAngle;
  5429. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5430. var startAngle = me._starts[index];
  5431. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  5432. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5433. var options = arc._options || {};
  5434. helpers$1.extend(arc, {
  5435. // Utility
  5436. _datasetIndex: me.index,
  5437. _index: index,
  5438. _scale: scale,
  5439. // Desired view properties
  5440. _model: {
  5441. backgroundColor: options.backgroundColor,
  5442. borderColor: options.borderColor,
  5443. borderWidth: options.borderWidth,
  5444. borderAlign: options.borderAlign,
  5445. x: centerX,
  5446. y: centerY,
  5447. innerRadius: 0,
  5448. outerRadius: reset ? resetRadius : distance,
  5449. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  5450. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  5451. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  5452. }
  5453. });
  5454. arc.pivot();
  5455. },
  5456. countVisibleElements: function() {
  5457. var dataset = this.getDataset();
  5458. var meta = this.getMeta();
  5459. var count = 0;
  5460. helpers$1.each(meta.data, function(element, index) {
  5461. if (!isNaN(dataset.data[index]) && !element.hidden) {
  5462. count++;
  5463. }
  5464. });
  5465. return count;
  5466. },
  5467. /**
  5468. * @protected
  5469. */
  5470. setHoverStyle: function(arc) {
  5471. var model = arc._model;
  5472. var options = arc._options;
  5473. var getHoverColor = helpers$1.getHoverColor;
  5474. var valueOrDefault = helpers$1.valueOrDefault;
  5475. arc.$previousStyle = {
  5476. backgroundColor: model.backgroundColor,
  5477. borderColor: model.borderColor,
  5478. borderWidth: model.borderWidth,
  5479. };
  5480. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5481. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  5482. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  5483. },
  5484. /**
  5485. * @private
  5486. */
  5487. _computeAngle: function(index) {
  5488. var me = this;
  5489. var count = this.getMeta().count;
  5490. var dataset = me.getDataset();
  5491. var meta = me.getMeta();
  5492. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  5493. return 0;
  5494. }
  5495. // Scriptable options
  5496. var context = {
  5497. chart: me.chart,
  5498. dataIndex: index,
  5499. dataset: dataset,
  5500. datasetIndex: me.index
  5501. };
  5502. return resolve$3([
  5503. me.chart.options.elements.arc.angle,
  5504. (2 * Math.PI) / count
  5505. ], context, index);
  5506. }
  5507. });
  5508. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  5509. core_defaults._set('pie', {
  5510. cutoutPercentage: 0
  5511. });
  5512. // Pie charts are Doughnut chart with different defaults
  5513. var controller_pie = controller_doughnut;
  5514. var valueOrDefault$7 = helpers$1.valueOrDefault;
  5515. core_defaults._set('radar', {
  5516. spanGaps: false,
  5517. scale: {
  5518. type: 'radialLinear'
  5519. },
  5520. elements: {
  5521. line: {
  5522. fill: 'start',
  5523. tension: 0 // no bezier in radar
  5524. }
  5525. }
  5526. });
  5527. var controller_radar = core_datasetController.extend({
  5528. datasetElementType: elements.Line,
  5529. dataElementType: elements.Point,
  5530. linkScales: helpers$1.noop,
  5531. /**
  5532. * @private
  5533. */
  5534. _datasetElementOptions: [
  5535. 'backgroundColor',
  5536. 'borderWidth',
  5537. 'borderColor',
  5538. 'borderCapStyle',
  5539. 'borderDash',
  5540. 'borderDashOffset',
  5541. 'borderJoinStyle',
  5542. 'fill'
  5543. ],
  5544. /**
  5545. * @private
  5546. */
  5547. _dataElementOptions: {
  5548. backgroundColor: 'pointBackgroundColor',
  5549. borderColor: 'pointBorderColor',
  5550. borderWidth: 'pointBorderWidth',
  5551. hitRadius: 'pointHitRadius',
  5552. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5553. hoverBorderColor: 'pointHoverBorderColor',
  5554. hoverBorderWidth: 'pointHoverBorderWidth',
  5555. hoverRadius: 'pointHoverRadius',
  5556. pointStyle: 'pointStyle',
  5557. radius: 'pointRadius',
  5558. rotation: 'pointRotation'
  5559. },
  5560. /**
  5561. * @private
  5562. */
  5563. _getIndexScaleId: function() {
  5564. return this.chart.scale.id;
  5565. },
  5566. /**
  5567. * @private
  5568. */
  5569. _getValueScaleId: function() {
  5570. return this.chart.scale.id;
  5571. },
  5572. update: function(reset) {
  5573. var me = this;
  5574. var meta = me.getMeta();
  5575. var line = meta.dataset;
  5576. var points = meta.data || [];
  5577. var scale = me.chart.scale;
  5578. var config = me._config;
  5579. var i, ilen;
  5580. // Compatibility: If the properties are defined with only the old name, use those values
  5581. if (config.tension !== undefined && config.lineTension === undefined) {
  5582. config.lineTension = config.tension;
  5583. }
  5584. // Utility
  5585. line._scale = scale;
  5586. line._datasetIndex = me.index;
  5587. // Data
  5588. line._children = points;
  5589. line._loop = true;
  5590. // Model
  5591. line._model = me._resolveDatasetElementOptions(line);
  5592. line.pivot();
  5593. // Update Points
  5594. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5595. me.updateElement(points[i], i, reset);
  5596. }
  5597. // Update bezier control points
  5598. me.updateBezierControlPoints();
  5599. // Now pivot the point for animation
  5600. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5601. points[i].pivot();
  5602. }
  5603. },
  5604. updateElement: function(point, index, reset) {
  5605. var me = this;
  5606. var custom = point.custom || {};
  5607. var dataset = me.getDataset();
  5608. var scale = me.chart.scale;
  5609. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  5610. var options = me._resolveDataElementOptions(point, index);
  5611. var lineModel = me.getMeta().dataset._model;
  5612. var x = reset ? scale.xCenter : pointPosition.x;
  5613. var y = reset ? scale.yCenter : pointPosition.y;
  5614. // Utility
  5615. point._scale = scale;
  5616. point._options = options;
  5617. point._datasetIndex = me.index;
  5618. point._index = index;
  5619. // Desired view properties
  5620. point._model = {
  5621. x: x, // value not used in dataset scale, but we want a consistent API between scales
  5622. y: y,
  5623. skip: custom.skip || isNaN(x) || isNaN(y),
  5624. // Appearance
  5625. radius: options.radius,
  5626. pointStyle: options.pointStyle,
  5627. rotation: options.rotation,
  5628. backgroundColor: options.backgroundColor,
  5629. borderColor: options.borderColor,
  5630. borderWidth: options.borderWidth,
  5631. tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0),
  5632. // Tooltip
  5633. hitRadius: options.hitRadius
  5634. };
  5635. },
  5636. /**
  5637. * @private
  5638. */
  5639. _resolveDatasetElementOptions: function() {
  5640. var me = this;
  5641. var config = me._config;
  5642. var options = me.chart.options;
  5643. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5644. values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);
  5645. values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);
  5646. return values;
  5647. },
  5648. updateBezierControlPoints: function() {
  5649. var me = this;
  5650. var meta = me.getMeta();
  5651. var area = me.chart.chartArea;
  5652. var points = meta.data || [];
  5653. var i, ilen, model, controlPoints;
  5654. // Only consider points that are drawn in case the spanGaps option is used
  5655. if (meta.dataset._model.spanGaps) {
  5656. points = points.filter(function(pt) {
  5657. return !pt._model.skip;
  5658. });
  5659. }
  5660. function capControlPoint(pt, min, max) {
  5661. return Math.max(Math.min(pt, max), min);
  5662. }
  5663. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5664. model = points[i]._model;
  5665. controlPoints = helpers$1.splineCurve(
  5666. helpers$1.previousItem(points, i, true)._model,
  5667. model,
  5668. helpers$1.nextItem(points, i, true)._model,
  5669. model.tension
  5670. );
  5671. // Prevent the bezier going outside of the bounds of the graph
  5672. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  5673. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  5674. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  5675. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  5676. }
  5677. },
  5678. setHoverStyle: function(point) {
  5679. var model = point._model;
  5680. var options = point._options;
  5681. var getHoverColor = helpers$1.getHoverColor;
  5682. point.$previousStyle = {
  5683. backgroundColor: model.backgroundColor,
  5684. borderColor: model.borderColor,
  5685. borderWidth: model.borderWidth,
  5686. radius: model.radius
  5687. };
  5688. model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5689. model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));
  5690. model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);
  5691. model.radius = valueOrDefault$7(options.hoverRadius, options.radius);
  5692. }
  5693. });
  5694. core_defaults._set('scatter', {
  5695. hover: {
  5696. mode: 'single'
  5697. },
  5698. scales: {
  5699. xAxes: [{
  5700. id: 'x-axis-1', // need an ID so datasets can reference the scale
  5701. type: 'linear', // scatter should not use a category axis
  5702. position: 'bottom'
  5703. }],
  5704. yAxes: [{
  5705. id: 'y-axis-1',
  5706. type: 'linear',
  5707. position: 'left'
  5708. }]
  5709. },
  5710. tooltips: {
  5711. callbacks: {
  5712. title: function() {
  5713. return ''; // doesn't make sense for scatter since data are formatted as a point
  5714. },
  5715. label: function(item) {
  5716. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  5717. }
  5718. }
  5719. }
  5720. });
  5721. core_defaults._set('global', {
  5722. datasets: {
  5723. scatter: {
  5724. showLine: false
  5725. }
  5726. }
  5727. });
  5728. // Scatter charts use line controllers
  5729. var controller_scatter = controller_line;
  5730. // NOTE export a map in which the key represents the controller type, not
  5731. // the class, and so must be CamelCase in order to be correctly retrieved
  5732. // by the controller in core.controller.js (`controllers[meta.type]`).
  5733. var controllers = {
  5734. bar: controller_bar,
  5735. bubble: controller_bubble,
  5736. doughnut: controller_doughnut,
  5737. horizontalBar: controller_horizontalBar,
  5738. line: controller_line,
  5739. polarArea: controller_polarArea,
  5740. pie: controller_pie,
  5741. radar: controller_radar,
  5742. scatter: controller_scatter
  5743. };
  5744. /**
  5745. * Helper function to get relative position for an event
  5746. * @param {Event|IEvent} event - The event to get the position for
  5747. * @param {Chart} chart - The chart
  5748. * @returns {object} the event position
  5749. */
  5750. function getRelativePosition(e, chart) {
  5751. if (e.native) {
  5752. return {
  5753. x: e.x,
  5754. y: e.y
  5755. };
  5756. }
  5757. return helpers$1.getRelativePosition(e, chart);
  5758. }
  5759. /**
  5760. * Helper function to traverse all of the visible elements in the chart
  5761. * @param {Chart} chart - the chart
  5762. * @param {function} handler - the callback to execute for each visible item
  5763. */
  5764. function parseVisibleItems(chart, handler) {
  5765. var metasets = chart._getSortedVisibleDatasetMetas();
  5766. var metadata, i, j, ilen, jlen, element;
  5767. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  5768. metadata = metasets[i].data;
  5769. for (j = 0, jlen = metadata.length; j < jlen; ++j) {
  5770. element = metadata[j];
  5771. if (!element._view.skip) {
  5772. handler(element);
  5773. }
  5774. }
  5775. }
  5776. }
  5777. /**
  5778. * Helper function to get the items that intersect the event position
  5779. * @param {ChartElement[]} items - elements to filter
  5780. * @param {object} position - the point to be nearest to
  5781. * @return {ChartElement[]} the nearest items
  5782. */
  5783. function getIntersectItems(chart, position) {
  5784. var elements = [];
  5785. parseVisibleItems(chart, function(element) {
  5786. if (element.inRange(position.x, position.y)) {
  5787. elements.push(element);
  5788. }
  5789. });
  5790. return elements;
  5791. }
  5792. /**
  5793. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5794. * @param {Chart} chart - the chart to look at elements from
  5795. * @param {object} position - the point to be nearest to
  5796. * @param {boolean} intersect - if true, only consider items that intersect the position
  5797. * @param {function} distanceMetric - function to provide the distance between points
  5798. * @return {ChartElement[]} the nearest items
  5799. */
  5800. function getNearestItems(chart, position, intersect, distanceMetric) {
  5801. var minDistance = Number.POSITIVE_INFINITY;
  5802. var nearestItems = [];
  5803. parseVisibleItems(chart, function(element) {
  5804. if (intersect && !element.inRange(position.x, position.y)) {
  5805. return;
  5806. }
  5807. var center = element.getCenterPoint();
  5808. var distance = distanceMetric(position, center);
  5809. if (distance < minDistance) {
  5810. nearestItems = [element];
  5811. minDistance = distance;
  5812. } else if (distance === minDistance) {
  5813. // Can have multiple items at the same distance in which case we sort by size
  5814. nearestItems.push(element);
  5815. }
  5816. });
  5817. return nearestItems;
  5818. }
  5819. /**
  5820. * Get a distance metric function for two points based on the
  5821. * axis mode setting
  5822. * @param {string} axis - the axis mode. x|y|xy
  5823. */
  5824. function getDistanceMetricForAxis(axis) {
  5825. var useX = axis.indexOf('x') !== -1;
  5826. var useY = axis.indexOf('y') !== -1;
  5827. return function(pt1, pt2) {
  5828. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5829. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5830. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5831. };
  5832. }
  5833. function indexMode(chart, e, options) {
  5834. var position = getRelativePosition(e, chart);
  5835. // Default axis for index mode is 'x' to match old behaviour
  5836. options.axis = options.axis || 'x';
  5837. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5838. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5839. var elements = [];
  5840. if (!items.length) {
  5841. return [];
  5842. }
  5843. chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
  5844. var element = meta.data[items[0]._index];
  5845. // don't count items that are skipped (null data)
  5846. if (element && !element._view.skip) {
  5847. elements.push(element);
  5848. }
  5849. });
  5850. return elements;
  5851. }
  5852. /**
  5853. * @interface IInteractionOptions
  5854. */
  5855. /**
  5856. * If true, only consider items that intersect the point
  5857. * @name IInterfaceOptions#boolean
  5858. * @type Boolean
  5859. */
  5860. /**
  5861. * Contains interaction related functions
  5862. * @namespace Chart.Interaction
  5863. */
  5864. var core_interaction = {
  5865. // Helper function for different modes
  5866. modes: {
  5867. single: function(chart, e) {
  5868. var position = getRelativePosition(e, chart);
  5869. var elements = [];
  5870. parseVisibleItems(chart, function(element) {
  5871. if (element.inRange(position.x, position.y)) {
  5872. elements.push(element);
  5873. return elements;
  5874. }
  5875. });
  5876. return elements.slice(0, 1);
  5877. },
  5878. /**
  5879. * @function Chart.Interaction.modes.label
  5880. * @deprecated since version 2.4.0
  5881. * @todo remove at version 3
  5882. * @private
  5883. */
  5884. label: indexMode,
  5885. /**
  5886. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5887. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5888. * @function Chart.Interaction.modes.index
  5889. * @since v2.4.0
  5890. * @param {Chart} chart - the chart we are returning items from
  5891. * @param {Event} e - the event we are find things at
  5892. * @param {IInteractionOptions} options - options to use during interaction
  5893. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5894. */
  5895. index: indexMode,
  5896. /**
  5897. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5898. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5899. * @function Chart.Interaction.modes.dataset
  5900. * @param {Chart} chart - the chart we are returning items from
  5901. * @param {Event} e - the event we are find things at
  5902. * @param {IInteractionOptions} options - options to use during interaction
  5903. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5904. */
  5905. dataset: function(chart, e, options) {
  5906. var position = getRelativePosition(e, chart);
  5907. options.axis = options.axis || 'xy';
  5908. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5909. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5910. if (items.length > 0) {
  5911. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5912. }
  5913. return items;
  5914. },
  5915. /**
  5916. * @function Chart.Interaction.modes.x-axis
  5917. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5918. * @todo remove at version 3
  5919. * @private
  5920. */
  5921. 'x-axis': function(chart, e) {
  5922. return indexMode(chart, e, {intersect: false});
  5923. },
  5924. /**
  5925. * Point mode returns all elements that hit test based on the event position
  5926. * of the event
  5927. * @function Chart.Interaction.modes.intersect
  5928. * @param {Chart} chart - the chart we are returning items from
  5929. * @param {Event} e - the event we are find things at
  5930. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5931. */
  5932. point: function(chart, e) {
  5933. var position = getRelativePosition(e, chart);
  5934. return getIntersectItems(chart, position);
  5935. },
  5936. /**
  5937. * nearest mode returns the element closest to the point
  5938. * @function Chart.Interaction.modes.intersect
  5939. * @param {Chart} chart - the chart we are returning items from
  5940. * @param {Event} e - the event we are find things at
  5941. * @param {IInteractionOptions} options - options to use
  5942. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5943. */
  5944. nearest: function(chart, e, options) {
  5945. var position = getRelativePosition(e, chart);
  5946. options.axis = options.axis || 'xy';
  5947. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5948. return getNearestItems(chart, position, options.intersect, distanceMetric);
  5949. },
  5950. /**
  5951. * x mode returns the elements that hit-test at the current x coordinate
  5952. * @function Chart.Interaction.modes.x
  5953. * @param {Chart} chart - the chart we are returning items from
  5954. * @param {Event} e - the event we are find things at
  5955. * @param {IInteractionOptions} options - options to use
  5956. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5957. */
  5958. x: function(chart, e, options) {
  5959. var position = getRelativePosition(e, chart);
  5960. var items = [];
  5961. var intersectsItem = false;
  5962. parseVisibleItems(chart, function(element) {
  5963. if (element.inXRange(position.x)) {
  5964. items.push(element);
  5965. }
  5966. if (element.inRange(position.x, position.y)) {
  5967. intersectsItem = true;
  5968. }
  5969. });
  5970. // If we want to trigger on an intersect and we don't have any items
  5971. // that intersect the position, return nothing
  5972. if (options.intersect && !intersectsItem) {
  5973. items = [];
  5974. }
  5975. return items;
  5976. },
  5977. /**
  5978. * y mode returns the elements that hit-test at the current y coordinate
  5979. * @function Chart.Interaction.modes.y
  5980. * @param {Chart} chart - the chart we are returning items from
  5981. * @param {Event} e - the event we are find things at
  5982. * @param {IInteractionOptions} options - options to use
  5983. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5984. */
  5985. y: function(chart, e, options) {
  5986. var position = getRelativePosition(e, chart);
  5987. var items = [];
  5988. var intersectsItem = false;
  5989. parseVisibleItems(chart, function(element) {
  5990. if (element.inYRange(position.y)) {
  5991. items.push(element);
  5992. }
  5993. if (element.inRange(position.x, position.y)) {
  5994. intersectsItem = true;
  5995. }
  5996. });
  5997. // If we want to trigger on an intersect and we don't have any items
  5998. // that intersect the position, return nothing
  5999. if (options.intersect && !intersectsItem) {
  6000. items = [];
  6001. }
  6002. return items;
  6003. }
  6004. }
  6005. };
  6006. var extend = helpers$1.extend;
  6007. function filterByPosition(array, position) {
  6008. return helpers$1.where(array, function(v) {
  6009. return v.pos === position;
  6010. });
  6011. }
  6012. function sortByWeight(array, reverse) {
  6013. return array.sort(function(a, b) {
  6014. var v0 = reverse ? b : a;
  6015. var v1 = reverse ? a : b;
  6016. return v0.weight === v1.weight ?
  6017. v0.index - v1.index :
  6018. v0.weight - v1.weight;
  6019. });
  6020. }
  6021. function wrapBoxes(boxes) {
  6022. var layoutBoxes = [];
  6023. var i, ilen, box;
  6024. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  6025. box = boxes[i];
  6026. layoutBoxes.push({
  6027. index: i,
  6028. box: box,
  6029. pos: box.position,
  6030. horizontal: box.isHorizontal(),
  6031. weight: box.weight
  6032. });
  6033. }
  6034. return layoutBoxes;
  6035. }
  6036. function setLayoutDims(layouts, params) {
  6037. var i, ilen, layout;
  6038. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  6039. layout = layouts[i];
  6040. // store width used instead of chartArea.w in fitBoxes
  6041. layout.width = layout.horizontal
  6042. ? layout.box.fullWidth && params.availableWidth
  6043. : params.vBoxMaxWidth;
  6044. // store height used instead of chartArea.h in fitBoxes
  6045. layout.height = layout.horizontal && params.hBoxMaxHeight;
  6046. }
  6047. }
  6048. function buildLayoutBoxes(boxes) {
  6049. var layoutBoxes = wrapBoxes(boxes);
  6050. var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  6051. var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  6052. var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  6053. var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  6054. return {
  6055. leftAndTop: left.concat(top),
  6056. rightAndBottom: right.concat(bottom),
  6057. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  6058. vertical: left.concat(right),
  6059. horizontal: top.concat(bottom)
  6060. };
  6061. }
  6062. function getCombinedMax(maxPadding, chartArea, a, b) {
  6063. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  6064. }
  6065. function updateDims(chartArea, params, layout) {
  6066. var box = layout.box;
  6067. var maxPadding = chartArea.maxPadding;
  6068. var newWidth, newHeight;
  6069. if (layout.size) {
  6070. // this layout was already counted for, lets first reduce old size
  6071. chartArea[layout.pos] -= layout.size;
  6072. }
  6073. layout.size = layout.horizontal ? box.height : box.width;
  6074. chartArea[layout.pos] += layout.size;
  6075. if (box.getPadding) {
  6076. var boxPadding = box.getPadding();
  6077. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  6078. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  6079. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  6080. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  6081. }
  6082. newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
  6083. newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
  6084. if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
  6085. chartArea.w = newWidth;
  6086. chartArea.h = newHeight;
  6087. // return true if chart area changed in layout's direction
  6088. return layout.horizontal ? newWidth !== chartArea.w : newHeight !== chartArea.h;
  6089. }
  6090. }
  6091. function handleMaxPadding(chartArea) {
  6092. var maxPadding = chartArea.maxPadding;
  6093. function updatePos(pos) {
  6094. var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  6095. chartArea[pos] += change;
  6096. return change;
  6097. }
  6098. chartArea.y += updatePos('top');
  6099. chartArea.x += updatePos('left');
  6100. updatePos('right');
  6101. updatePos('bottom');
  6102. }
  6103. function getMargins(horizontal, chartArea) {
  6104. var maxPadding = chartArea.maxPadding;
  6105. function marginForPositions(positions) {
  6106. var margin = {left: 0, top: 0, right: 0, bottom: 0};
  6107. positions.forEach(function(pos) {
  6108. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  6109. });
  6110. return margin;
  6111. }
  6112. return horizontal
  6113. ? marginForPositions(['left', 'right'])
  6114. : marginForPositions(['top', 'bottom']);
  6115. }
  6116. function fitBoxes(boxes, chartArea, params) {
  6117. var refitBoxes = [];
  6118. var i, ilen, layout, box, refit, changed;
  6119. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6120. layout = boxes[i];
  6121. box = layout.box;
  6122. box.update(
  6123. layout.width || chartArea.w,
  6124. layout.height || chartArea.h,
  6125. getMargins(layout.horizontal, chartArea)
  6126. );
  6127. if (updateDims(chartArea, params, layout)) {
  6128. changed = true;
  6129. if (refitBoxes.length) {
  6130. // Dimensions changed and there were non full width boxes before this
  6131. // -> we have to refit those
  6132. refit = true;
  6133. }
  6134. }
  6135. if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case
  6136. refitBoxes.push(layout);
  6137. }
  6138. }
  6139. return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;
  6140. }
  6141. function placeBoxes(boxes, chartArea, params) {
  6142. var userPadding = params.padding;
  6143. var x = chartArea.x;
  6144. var y = chartArea.y;
  6145. var i, ilen, layout, box;
  6146. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6147. layout = boxes[i];
  6148. box = layout.box;
  6149. if (layout.horizontal) {
  6150. box.left = box.fullWidth ? userPadding.left : chartArea.left;
  6151. box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  6152. box.top = y;
  6153. box.bottom = y + box.height;
  6154. box.width = box.right - box.left;
  6155. y = box.bottom;
  6156. } else {
  6157. box.left = x;
  6158. box.right = x + box.width;
  6159. box.top = chartArea.top;
  6160. box.bottom = chartArea.top + chartArea.h;
  6161. box.height = box.bottom - box.top;
  6162. x = box.right;
  6163. }
  6164. }
  6165. chartArea.x = x;
  6166. chartArea.y = y;
  6167. }
  6168. core_defaults._set('global', {
  6169. layout: {
  6170. padding: {
  6171. top: 0,
  6172. right: 0,
  6173. bottom: 0,
  6174. left: 0
  6175. }
  6176. }
  6177. });
  6178. /**
  6179. * @interface ILayoutItem
  6180. * @prop {string} position - The position of the item in the chart layout. Possible values are
  6181. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  6182. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  6183. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  6184. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  6185. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  6186. * @prop {function} getPadding - Returns an object with padding on the edges
  6187. * @prop {number} width - Width of item. Must be valid after update()
  6188. * @prop {number} height - Height of item. Must be valid after update()
  6189. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  6190. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  6191. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  6192. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  6193. */
  6194. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  6195. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  6196. // It is this service's responsibility of carrying out that layout.
  6197. var core_layouts = {
  6198. defaults: {},
  6199. /**
  6200. * Register a box to a chart.
  6201. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  6202. * @param {Chart} chart - the chart to use
  6203. * @param {ILayoutItem} item - the item to add to be layed out
  6204. */
  6205. addBox: function(chart, item) {
  6206. if (!chart.boxes) {
  6207. chart.boxes = [];
  6208. }
  6209. // initialize item with default values
  6210. item.fullWidth = item.fullWidth || false;
  6211. item.position = item.position || 'top';
  6212. item.weight = item.weight || 0;
  6213. item._layers = item._layers || function() {
  6214. return [{
  6215. z: 0,
  6216. draw: function() {
  6217. item.draw.apply(item, arguments);
  6218. }
  6219. }];
  6220. };
  6221. chart.boxes.push(item);
  6222. },
  6223. /**
  6224. * Remove a layoutItem from a chart
  6225. * @param {Chart} chart - the chart to remove the box from
  6226. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  6227. */
  6228. removeBox: function(chart, layoutItem) {
  6229. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  6230. if (index !== -1) {
  6231. chart.boxes.splice(index, 1);
  6232. }
  6233. },
  6234. /**
  6235. * Sets (or updates) options on the given `item`.
  6236. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  6237. * @param {ILayoutItem} item - the item to configure with the given options
  6238. * @param {object} options - the new item options.
  6239. */
  6240. configure: function(chart, item, options) {
  6241. var props = ['fullWidth', 'position', 'weight'];
  6242. var ilen = props.length;
  6243. var i = 0;
  6244. var prop;
  6245. for (; i < ilen; ++i) {
  6246. prop = props[i];
  6247. if (options.hasOwnProperty(prop)) {
  6248. item[prop] = options[prop];
  6249. }
  6250. }
  6251. },
  6252. /**
  6253. * Fits boxes of the given chart into the given size by having each box measure itself
  6254. * then running a fitting algorithm
  6255. * @param {Chart} chart - the chart
  6256. * @param {number} width - the width to fit into
  6257. * @param {number} height - the height to fit into
  6258. */
  6259. update: function(chart, width, height) {
  6260. if (!chart) {
  6261. return;
  6262. }
  6263. var layoutOptions = chart.options.layout || {};
  6264. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  6265. var availableWidth = width - padding.width;
  6266. var availableHeight = height - padding.height;
  6267. var boxes = buildLayoutBoxes(chart.boxes);
  6268. var verticalBoxes = boxes.vertical;
  6269. var horizontalBoxes = boxes.horizontal;
  6270. // Essentially we now have any number of boxes on each of the 4 sides.
  6271. // Our canvas looks like the following.
  6272. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  6273. // B1 is the bottom axis
  6274. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  6275. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  6276. // an error will be thrown.
  6277. //
  6278. // |----------------------------------------------------|
  6279. // | T1 (Full Width) |
  6280. // |----------------------------------------------------|
  6281. // | | | T2 | |
  6282. // | |----|-------------------------------------|----|
  6283. // | | | C1 | | C2 | |
  6284. // | | |----| |----| |
  6285. // | | | | |
  6286. // | L1 | L2 | ChartArea (C0) | R1 |
  6287. // | | | | |
  6288. // | | |----| |----| |
  6289. // | | | C3 | | C4 | |
  6290. // | |----|-------------------------------------|----|
  6291. // | | | B1 | |
  6292. // |----------------------------------------------------|
  6293. // | B2 (Full Width) |
  6294. // |----------------------------------------------------|
  6295. //
  6296. var params = Object.freeze({
  6297. outerWidth: width,
  6298. outerHeight: height,
  6299. padding: padding,
  6300. availableWidth: availableWidth,
  6301. vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
  6302. hBoxMaxHeight: availableHeight / 2
  6303. });
  6304. var chartArea = extend({
  6305. maxPadding: extend({}, padding),
  6306. w: availableWidth,
  6307. h: availableHeight,
  6308. x: padding.left,
  6309. y: padding.top
  6310. }, padding);
  6311. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  6312. // First fit vertical boxes
  6313. fitBoxes(verticalBoxes, chartArea, params);
  6314. // Then fit horizontal boxes
  6315. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  6316. // if the area changed, re-fit vertical boxes
  6317. fitBoxes(verticalBoxes, chartArea, params);
  6318. }
  6319. handleMaxPadding(chartArea);
  6320. // Finally place the boxes to correct coordinates
  6321. placeBoxes(boxes.leftAndTop, chartArea, params);
  6322. // Move to opposite side of chart
  6323. chartArea.x += chartArea.w;
  6324. chartArea.y += chartArea.h;
  6325. placeBoxes(boxes.rightAndBottom, chartArea, params);
  6326. chart.chartArea = {
  6327. left: chartArea.left,
  6328. top: chartArea.top,
  6329. right: chartArea.left + chartArea.w,
  6330. bottom: chartArea.top + chartArea.h
  6331. };
  6332. // Finally update boxes in chartArea (radial scale for example)
  6333. helpers$1.each(boxes.chartArea, function(layout) {
  6334. var box = layout.box;
  6335. extend(box, chart.chartArea);
  6336. box.update(chartArea.w, chartArea.h);
  6337. });
  6338. }
  6339. };
  6340. /**
  6341. * Platform fallback implementation (minimal).
  6342. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  6343. */
  6344. var platform_basic = {
  6345. acquireContext: function(item) {
  6346. if (item && item.canvas) {
  6347. // Support for any object associated to a canvas (including a context2d)
  6348. item = item.canvas;
  6349. }
  6350. return item && item.getContext('2d') || null;
  6351. }
  6352. };
  6353. 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";
  6354. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  6355. __proto__: null,
  6356. 'default': platform_dom
  6357. });
  6358. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  6359. var EXPANDO_KEY = '$chartjs';
  6360. var CSS_PREFIX = 'chartjs-';
  6361. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  6362. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  6363. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  6364. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  6365. /**
  6366. * DOM event types -> Chart.js event types.
  6367. * Note: only events with different types are mapped.
  6368. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  6369. */
  6370. var EVENT_TYPES = {
  6371. touchstart: 'mousedown',
  6372. touchmove: 'mousemove',
  6373. touchend: 'mouseup',
  6374. pointerenter: 'mouseenter',
  6375. pointerdown: 'mousedown',
  6376. pointermove: 'mousemove',
  6377. pointerup: 'mouseup',
  6378. pointerleave: 'mouseout',
  6379. pointerout: 'mouseout'
  6380. };
  6381. /**
  6382. * The "used" size is the final value of a dimension property after all calculations have
  6383. * been performed. This method uses the computed style of `element` but returns undefined
  6384. * if the computed style is not expressed in pixels. That can happen in some cases where
  6385. * `element` has a size relative to its parent and this last one is not yet displayed,
  6386. * for example because of `display: none` on a parent node.
  6387. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  6388. * @returns {number} Size in pixels or undefined if unknown.
  6389. */
  6390. function readUsedSize(element, property) {
  6391. var value = helpers$1.getStyle(element, property);
  6392. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  6393. return matches ? Number(matches[1]) : undefined;
  6394. }
  6395. /**
  6396. * Initializes the canvas style and render size without modifying the canvas display size,
  6397. * since responsiveness is handled by the controller.resize() method. The config is used
  6398. * to determine the aspect ratio to apply in case no explicit height has been specified.
  6399. */
  6400. function initCanvas(canvas, config) {
  6401. var style = canvas.style;
  6402. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  6403. // returns null or '' if no explicit value has been set to the canvas attribute.
  6404. var renderHeight = canvas.getAttribute('height');
  6405. var renderWidth = canvas.getAttribute('width');
  6406. // Chart.js modifies some canvas values that we want to restore on destroy
  6407. canvas[EXPANDO_KEY] = {
  6408. initial: {
  6409. height: renderHeight,
  6410. width: renderWidth,
  6411. style: {
  6412. display: style.display,
  6413. height: style.height,
  6414. width: style.width
  6415. }
  6416. }
  6417. };
  6418. // Force canvas to display as block to avoid extra space caused by inline
  6419. // elements, which would interfere with the responsive resize process.
  6420. // https://github.com/chartjs/Chart.js/issues/2538
  6421. style.display = style.display || 'block';
  6422. if (renderWidth === null || renderWidth === '') {
  6423. var displayWidth = readUsedSize(canvas, 'width');
  6424. if (displayWidth !== undefined) {
  6425. canvas.width = displayWidth;
  6426. }
  6427. }
  6428. if (renderHeight === null || renderHeight === '') {
  6429. if (canvas.style.height === '') {
  6430. // If no explicit render height and style height, let's apply the aspect ratio,
  6431. // which one can be specified by the user but also by charts as default option
  6432. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  6433. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  6434. } else {
  6435. var displayHeight = readUsedSize(canvas, 'height');
  6436. if (displayWidth !== undefined) {
  6437. canvas.height = displayHeight;
  6438. }
  6439. }
  6440. }
  6441. return canvas;
  6442. }
  6443. /**
  6444. * Detects support for options object argument in addEventListener.
  6445. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  6446. * @private
  6447. */
  6448. var supportsEventListenerOptions = (function() {
  6449. var supports = false;
  6450. try {
  6451. var options = Object.defineProperty({}, 'passive', {
  6452. // eslint-disable-next-line getter-return
  6453. get: function() {
  6454. supports = true;
  6455. }
  6456. });
  6457. window.addEventListener('e', null, options);
  6458. } catch (e) {
  6459. // continue regardless of error
  6460. }
  6461. return supports;
  6462. }());
  6463. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  6464. // https://github.com/chartjs/Chart.js/issues/4287
  6465. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  6466. function addListener(node, type, listener) {
  6467. node.addEventListener(type, listener, eventListenerOptions);
  6468. }
  6469. function removeListener(node, type, listener) {
  6470. node.removeEventListener(type, listener, eventListenerOptions);
  6471. }
  6472. function createEvent(type, chart, x, y, nativeEvent) {
  6473. return {
  6474. type: type,
  6475. chart: chart,
  6476. native: nativeEvent || null,
  6477. x: x !== undefined ? x : null,
  6478. y: y !== undefined ? y : null,
  6479. };
  6480. }
  6481. function fromNativeEvent(event, chart) {
  6482. var type = EVENT_TYPES[event.type] || event.type;
  6483. var pos = helpers$1.getRelativePosition(event, chart);
  6484. return createEvent(type, chart, pos.x, pos.y, event);
  6485. }
  6486. function throttled(fn, thisArg) {
  6487. var ticking = false;
  6488. var args = [];
  6489. return function() {
  6490. args = Array.prototype.slice.call(arguments);
  6491. thisArg = thisArg || this;
  6492. if (!ticking) {
  6493. ticking = true;
  6494. helpers$1.requestAnimFrame.call(window, function() {
  6495. ticking = false;
  6496. fn.apply(thisArg, args);
  6497. });
  6498. }
  6499. };
  6500. }
  6501. function createDiv(cls) {
  6502. var el = document.createElement('div');
  6503. el.className = cls || '';
  6504. return el;
  6505. }
  6506. // Implementation based on https://github.com/marcj/css-element-queries
  6507. function createResizer(handler) {
  6508. var maxSize = 1000000;
  6509. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  6510. // https://github.com/chartjs/Chart.js/issues/5902
  6511. var resizer = createDiv(CSS_SIZE_MONITOR);
  6512. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  6513. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  6514. expand.appendChild(createDiv());
  6515. shrink.appendChild(createDiv());
  6516. resizer.appendChild(expand);
  6517. resizer.appendChild(shrink);
  6518. resizer._reset = function() {
  6519. expand.scrollLeft = maxSize;
  6520. expand.scrollTop = maxSize;
  6521. shrink.scrollLeft = maxSize;
  6522. shrink.scrollTop = maxSize;
  6523. };
  6524. var onScroll = function() {
  6525. resizer._reset();
  6526. handler();
  6527. };
  6528. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  6529. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  6530. return resizer;
  6531. }
  6532. // https://davidwalsh.name/detect-node-insertion
  6533. function watchForRender(node, handler) {
  6534. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6535. var proxy = expando.renderProxy = function(e) {
  6536. if (e.animationName === CSS_RENDER_ANIMATION) {
  6537. handler();
  6538. }
  6539. };
  6540. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6541. addListener(node, type, proxy);
  6542. });
  6543. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  6544. // is removed then added back immediately (same animation frame?). Accessing the
  6545. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  6546. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  6547. // https://github.com/chartjs/Chart.js/issues/4737
  6548. expando.reflow = !!node.offsetParent;
  6549. node.classList.add(CSS_RENDER_MONITOR);
  6550. }
  6551. function unwatchForRender(node) {
  6552. var expando = node[EXPANDO_KEY] || {};
  6553. var proxy = expando.renderProxy;
  6554. if (proxy) {
  6555. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6556. removeListener(node, type, proxy);
  6557. });
  6558. delete expando.renderProxy;
  6559. }
  6560. node.classList.remove(CSS_RENDER_MONITOR);
  6561. }
  6562. function addResizeListener(node, listener, chart) {
  6563. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6564. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  6565. var resizer = expando.resizer = createResizer(throttled(function() {
  6566. if (expando.resizer) {
  6567. var container = chart.options.maintainAspectRatio && node.parentNode;
  6568. var w = container ? container.clientWidth : 0;
  6569. listener(createEvent('resize', chart));
  6570. if (container && container.clientWidth < w && chart.canvas) {
  6571. // If the container size shrank during chart resize, let's assume
  6572. // scrollbar appeared. So we resize again with the scrollbar visible -
  6573. // effectively making chart smaller and the scrollbar hidden again.
  6574. // Because we are inside `throttled`, and currently `ticking`, scroll
  6575. // events are ignored during this whole 2 resize process.
  6576. // If we assumed wrong and something else happened, we are resizing
  6577. // twice in a frame (potential performance issue)
  6578. listener(createEvent('resize', chart));
  6579. }
  6580. }
  6581. }));
  6582. // The resizer needs to be attached to the node parent, so we first need to be
  6583. // sure that `node` is attached to the DOM before injecting the resizer element.
  6584. watchForRender(node, function() {
  6585. if (expando.resizer) {
  6586. var container = node.parentNode;
  6587. if (container && container !== resizer.parentNode) {
  6588. container.insertBefore(resizer, container.firstChild);
  6589. }
  6590. // The container size might have changed, let's reset the resizer state.
  6591. resizer._reset();
  6592. }
  6593. });
  6594. }
  6595. function removeResizeListener(node) {
  6596. var expando = node[EXPANDO_KEY] || {};
  6597. var resizer = expando.resizer;
  6598. delete expando.resizer;
  6599. unwatchForRender(node);
  6600. if (resizer && resizer.parentNode) {
  6601. resizer.parentNode.removeChild(resizer);
  6602. }
  6603. }
  6604. /**
  6605. * Injects CSS styles inline if the styles are not already present.
  6606. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.
  6607. * @param {string} css - the CSS to be injected.
  6608. */
  6609. function injectCSS(rootNode, css) {
  6610. // https://stackoverflow.com/q/3922139
  6611. var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});
  6612. if (!expando.containsStyles) {
  6613. expando.containsStyles = true;
  6614. css = '/* Chart.js */\n' + css;
  6615. var style = document.createElement('style');
  6616. style.setAttribute('type', 'text/css');
  6617. style.appendChild(document.createTextNode(css));
  6618. rootNode.appendChild(style);
  6619. }
  6620. }
  6621. var platform_dom$2 = {
  6622. /**
  6623. * When `true`, prevents the automatic injection of the stylesheet required to
  6624. * correctly detect when the chart is added to the DOM and then resized. This
  6625. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  6626. * to be manually imported to make this library compatible with any CSP.
  6627. * See https://github.com/chartjs/Chart.js/issues/5208
  6628. */
  6629. disableCSSInjection: false,
  6630. /**
  6631. * This property holds whether this platform is enabled for the current environment.
  6632. * Currently used by platform.js to select the proper implementation.
  6633. * @private
  6634. */
  6635. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  6636. /**
  6637. * Initializes resources that depend on platform options.
  6638. * @param {HTMLCanvasElement} canvas - The Canvas element.
  6639. * @private
  6640. */
  6641. _ensureLoaded: function(canvas) {
  6642. if (!this.disableCSSInjection) {
  6643. // If the canvas is in a shadow DOM, then the styles must also be inserted
  6644. // into the same shadow DOM.
  6645. // https://github.com/chartjs/Chart.js/issues/5763
  6646. var root = canvas.getRootNode ? canvas.getRootNode() : document;
  6647. var targetNode = root.host ? root : document.head;
  6648. injectCSS(targetNode, stylesheet);
  6649. }
  6650. },
  6651. acquireContext: function(item, config) {
  6652. if (typeof item === 'string') {
  6653. item = document.getElementById(item);
  6654. } else if (item.length) {
  6655. // Support for array based queries (such as jQuery)
  6656. item = item[0];
  6657. }
  6658. if (item && item.canvas) {
  6659. // Support for any object associated to a canvas (including a context2d)
  6660. item = item.canvas;
  6661. }
  6662. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  6663. // method, for example: https://github.com/kkapsner/CanvasBlocker
  6664. // https://github.com/chartjs/Chart.js/issues/2807
  6665. var context = item && item.getContext && item.getContext('2d');
  6666. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  6667. // inside an iframe or when running in a protected environment. We could guess the
  6668. // types from their toString() value but let's keep things flexible and assume it's
  6669. // a sufficient condition if the item has a context2D which has item as `canvas`.
  6670. // https://github.com/chartjs/Chart.js/issues/3887
  6671. // https://github.com/chartjs/Chart.js/issues/4102
  6672. // https://github.com/chartjs/Chart.js/issues/4152
  6673. if (context && context.canvas === item) {
  6674. // Load platform resources on first chart creation, to make it possible to
  6675. // import the library before setting platform options.
  6676. this._ensureLoaded(item);
  6677. initCanvas(item, config);
  6678. return context;
  6679. }
  6680. return null;
  6681. },
  6682. releaseContext: function(context) {
  6683. var canvas = context.canvas;
  6684. if (!canvas[EXPANDO_KEY]) {
  6685. return;
  6686. }
  6687. var initial = canvas[EXPANDO_KEY].initial;
  6688. ['height', 'width'].forEach(function(prop) {
  6689. var value = initial[prop];
  6690. if (helpers$1.isNullOrUndef(value)) {
  6691. canvas.removeAttribute(prop);
  6692. } else {
  6693. canvas.setAttribute(prop, value);
  6694. }
  6695. });
  6696. helpers$1.each(initial.style || {}, function(value, key) {
  6697. canvas.style[key] = value;
  6698. });
  6699. // The canvas render size might have been changed (and thus the state stack discarded),
  6700. // we can't use save() and restore() to restore the initial state. So make sure that at
  6701. // least the canvas context is reset to the default state by setting the canvas width.
  6702. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  6703. // eslint-disable-next-line no-self-assign
  6704. canvas.width = canvas.width;
  6705. delete canvas[EXPANDO_KEY];
  6706. },
  6707. addEventListener: function(chart, type, listener) {
  6708. var canvas = chart.canvas;
  6709. if (type === 'resize') {
  6710. // Note: the resize event is not supported on all browsers.
  6711. addResizeListener(canvas, listener, chart);
  6712. return;
  6713. }
  6714. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  6715. var proxies = expando.proxies || (expando.proxies = {});
  6716. var proxy = proxies[chart.id + '_' + type] = function(event) {
  6717. listener(fromNativeEvent(event, chart));
  6718. };
  6719. addListener(canvas, type, proxy);
  6720. },
  6721. removeEventListener: function(chart, type, listener) {
  6722. var canvas = chart.canvas;
  6723. if (type === 'resize') {
  6724. // Note: the resize event is not supported on all browsers.
  6725. removeResizeListener(canvas);
  6726. return;
  6727. }
  6728. var expando = listener[EXPANDO_KEY] || {};
  6729. var proxies = expando.proxies || {};
  6730. var proxy = proxies[chart.id + '_' + type];
  6731. if (!proxy) {
  6732. return;
  6733. }
  6734. removeListener(canvas, type, proxy);
  6735. }
  6736. };
  6737. // DEPRECATIONS
  6738. /**
  6739. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6740. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6741. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6742. * @function Chart.helpers.addEvent
  6743. * @deprecated since version 2.7.0
  6744. * @todo remove at version 3
  6745. * @private
  6746. */
  6747. helpers$1.addEvent = addListener;
  6748. /**
  6749. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6750. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6751. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6752. * @function Chart.helpers.removeEvent
  6753. * @deprecated since version 2.7.0
  6754. * @todo remove at version 3
  6755. * @private
  6756. */
  6757. helpers$1.removeEvent = removeListener;
  6758. // @TODO Make possible to select another platform at build time.
  6759. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6760. /**
  6761. * @namespace Chart.platform
  6762. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6763. * @since 2.4.0
  6764. */
  6765. var platform = helpers$1.extend({
  6766. /**
  6767. * @since 2.7.0
  6768. */
  6769. initialize: function() {},
  6770. /**
  6771. * Called at chart construction time, returns a context2d instance implementing
  6772. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6773. * @param {*} item - The native item from which to acquire context (platform specific)
  6774. * @param {object} options - The chart options
  6775. * @returns {CanvasRenderingContext2D} context2d instance
  6776. */
  6777. acquireContext: function() {},
  6778. /**
  6779. * Called at chart destruction time, releases any resources associated to the context
  6780. * previously returned by the acquireContext() method.
  6781. * @param {CanvasRenderingContext2D} context - The context2d instance
  6782. * @returns {boolean} true if the method succeeded, else false
  6783. */
  6784. releaseContext: function() {},
  6785. /**
  6786. * Registers the specified listener on the given chart.
  6787. * @param {Chart} chart - Chart from which to listen for event
  6788. * @param {string} type - The ({@link IEvent}) type to listen for
  6789. * @param {function} listener - Receives a notification (an object that implements
  6790. * the {@link IEvent} interface) when an event of the specified type occurs.
  6791. */
  6792. addEventListener: function() {},
  6793. /**
  6794. * Removes the specified listener previously registered with addEventListener.
  6795. * @param {Chart} chart - Chart from which to remove the listener
  6796. * @param {string} type - The ({@link IEvent}) type to remove
  6797. * @param {function} listener - The listener function to remove from the event target.
  6798. */
  6799. removeEventListener: function() {}
  6800. }, implementation);
  6801. core_defaults._set('global', {
  6802. plugins: {}
  6803. });
  6804. /**
  6805. * The plugin service singleton
  6806. * @namespace Chart.plugins
  6807. * @since 2.1.0
  6808. */
  6809. var core_plugins = {
  6810. /**
  6811. * Globally registered plugins.
  6812. * @private
  6813. */
  6814. _plugins: [],
  6815. /**
  6816. * This identifier is used to invalidate the descriptors cache attached to each chart
  6817. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6818. * incremented and descriptors are regenerated during following API calls.
  6819. * @private
  6820. */
  6821. _cacheId: 0,
  6822. /**
  6823. * Registers the given plugin(s) if not already registered.
  6824. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6825. */
  6826. register: function(plugins) {
  6827. var p = this._plugins;
  6828. ([]).concat(plugins).forEach(function(plugin) {
  6829. if (p.indexOf(plugin) === -1) {
  6830. p.push(plugin);
  6831. }
  6832. });
  6833. this._cacheId++;
  6834. },
  6835. /**
  6836. * Unregisters the given plugin(s) only if registered.
  6837. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6838. */
  6839. unregister: function(plugins) {
  6840. var p = this._plugins;
  6841. ([]).concat(plugins).forEach(function(plugin) {
  6842. var idx = p.indexOf(plugin);
  6843. if (idx !== -1) {
  6844. p.splice(idx, 1);
  6845. }
  6846. });
  6847. this._cacheId++;
  6848. },
  6849. /**
  6850. * Remove all registered plugins.
  6851. * @since 2.1.5
  6852. */
  6853. clear: function() {
  6854. this._plugins = [];
  6855. this._cacheId++;
  6856. },
  6857. /**
  6858. * Returns the number of registered plugins?
  6859. * @returns {number}
  6860. * @since 2.1.5
  6861. */
  6862. count: function() {
  6863. return this._plugins.length;
  6864. },
  6865. /**
  6866. * Returns all registered plugin instances.
  6867. * @returns {IPlugin[]} array of plugin objects.
  6868. * @since 2.1.5
  6869. */
  6870. getAll: function() {
  6871. return this._plugins;
  6872. },
  6873. /**
  6874. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6875. * This method immediately returns as soon as a plugin explicitly returns false. The
  6876. * returned value can be used, for instance, to interrupt the current action.
  6877. * @param {Chart} chart - The chart instance for which plugins should be called.
  6878. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6879. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6880. * @returns {boolean} false if any of the plugins return false, else returns true.
  6881. */
  6882. notify: function(chart, hook, args) {
  6883. var descriptors = this.descriptors(chart);
  6884. var ilen = descriptors.length;
  6885. var i, descriptor, plugin, params, method;
  6886. for (i = 0; i < ilen; ++i) {
  6887. descriptor = descriptors[i];
  6888. plugin = descriptor.plugin;
  6889. method = plugin[hook];
  6890. if (typeof method === 'function') {
  6891. params = [chart].concat(args || []);
  6892. params.push(descriptor.options);
  6893. if (method.apply(plugin, params) === false) {
  6894. return false;
  6895. }
  6896. }
  6897. }
  6898. return true;
  6899. },
  6900. /**
  6901. * Returns descriptors of enabled plugins for the given chart.
  6902. * @returns {object[]} [{ plugin, options }]
  6903. * @private
  6904. */
  6905. descriptors: function(chart) {
  6906. var cache = chart.$plugins || (chart.$plugins = {});
  6907. if (cache.id === this._cacheId) {
  6908. return cache.descriptors;
  6909. }
  6910. var plugins = [];
  6911. var descriptors = [];
  6912. var config = (chart && chart.config) || {};
  6913. var options = (config.options && config.options.plugins) || {};
  6914. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  6915. var idx = plugins.indexOf(plugin);
  6916. if (idx !== -1) {
  6917. return;
  6918. }
  6919. var id = plugin.id;
  6920. var opts = options[id];
  6921. if (opts === false) {
  6922. return;
  6923. }
  6924. if (opts === true) {
  6925. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6926. }
  6927. plugins.push(plugin);
  6928. descriptors.push({
  6929. plugin: plugin,
  6930. options: opts || {}
  6931. });
  6932. });
  6933. cache.descriptors = descriptors;
  6934. cache.id = this._cacheId;
  6935. return descriptors;
  6936. },
  6937. /**
  6938. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  6939. * but in some cases, this reference can be changed by the user when updating options.
  6940. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  6941. * @private
  6942. */
  6943. _invalidate: function(chart) {
  6944. delete chart.$plugins;
  6945. }
  6946. };
  6947. var core_scaleService = {
  6948. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  6949. // use the new chart options to grab the correct scale
  6950. constructors: {},
  6951. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  6952. // old browsers
  6953. // Scale config defaults
  6954. defaults: {},
  6955. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  6956. this.constructors[type] = scaleConstructor;
  6957. this.defaults[type] = helpers$1.clone(scaleDefaults);
  6958. },
  6959. getScaleConstructor: function(type) {
  6960. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  6961. },
  6962. getScaleDefaults: function(type) {
  6963. // Return the scale defaults merged with the global settings so that we always use the latest ones
  6964. return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {};
  6965. },
  6966. updateScaleDefaults: function(type, additions) {
  6967. var me = this;
  6968. if (me.defaults.hasOwnProperty(type)) {
  6969. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  6970. }
  6971. },
  6972. addScalesToLayout: function(chart) {
  6973. // Adds each scale to the chart.boxes array to be sized accordingly
  6974. helpers$1.each(chart.scales, function(scale) {
  6975. // Set ILayoutItem parameters for backwards compatibility
  6976. scale.fullWidth = scale.options.fullWidth;
  6977. scale.position = scale.options.position;
  6978. scale.weight = scale.options.weight;
  6979. core_layouts.addBox(chart, scale);
  6980. });
  6981. }
  6982. };
  6983. var valueOrDefault$8 = helpers$1.valueOrDefault;
  6984. var getRtlHelper = helpers$1.rtl.getRtlAdapter;
  6985. core_defaults._set('global', {
  6986. tooltips: {
  6987. enabled: true,
  6988. custom: null,
  6989. mode: 'nearest',
  6990. position: 'average',
  6991. intersect: true,
  6992. backgroundColor: 'rgba(0,0,0,0.8)',
  6993. titleFontStyle: 'bold',
  6994. titleSpacing: 2,
  6995. titleMarginBottom: 6,
  6996. titleFontColor: '#fff',
  6997. titleAlign: 'left',
  6998. bodySpacing: 2,
  6999. bodyFontColor: '#fff',
  7000. bodyAlign: 'left',
  7001. footerFontStyle: 'bold',
  7002. footerSpacing: 2,
  7003. footerMarginTop: 6,
  7004. footerFontColor: '#fff',
  7005. footerAlign: 'left',
  7006. yPadding: 6,
  7007. xPadding: 6,
  7008. caretPadding: 2,
  7009. caretSize: 5,
  7010. cornerRadius: 6,
  7011. multiKeyBackground: '#fff',
  7012. displayColors: true,
  7013. borderColor: 'rgba(0,0,0,0)',
  7014. borderWidth: 0,
  7015. callbacks: {
  7016. // Args are: (tooltipItems, data)
  7017. beforeTitle: helpers$1.noop,
  7018. title: function(tooltipItems, data) {
  7019. var title = '';
  7020. var labels = data.labels;
  7021. var labelCount = labels ? labels.length : 0;
  7022. if (tooltipItems.length > 0) {
  7023. var item = tooltipItems[0];
  7024. if (item.label) {
  7025. title = item.label;
  7026. } else if (item.xLabel) {
  7027. title = item.xLabel;
  7028. } else if (labelCount > 0 && item.index < labelCount) {
  7029. title = labels[item.index];
  7030. }
  7031. }
  7032. return title;
  7033. },
  7034. afterTitle: helpers$1.noop,
  7035. // Args are: (tooltipItems, data)
  7036. beforeBody: helpers$1.noop,
  7037. // Args are: (tooltipItem, data)
  7038. beforeLabel: helpers$1.noop,
  7039. label: function(tooltipItem, data) {
  7040. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  7041. if (label) {
  7042. label += ': ';
  7043. }
  7044. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  7045. label += tooltipItem.value;
  7046. } else {
  7047. label += tooltipItem.yLabel;
  7048. }
  7049. return label;
  7050. },
  7051. labelColor: function(tooltipItem, chart) {
  7052. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  7053. var activeElement = meta.data[tooltipItem.index];
  7054. var view = activeElement._view;
  7055. return {
  7056. borderColor: view.borderColor,
  7057. backgroundColor: view.backgroundColor
  7058. };
  7059. },
  7060. labelTextColor: function() {
  7061. return this._options.bodyFontColor;
  7062. },
  7063. afterLabel: helpers$1.noop,
  7064. // Args are: (tooltipItems, data)
  7065. afterBody: helpers$1.noop,
  7066. // Args are: (tooltipItems, data)
  7067. beforeFooter: helpers$1.noop,
  7068. footer: helpers$1.noop,
  7069. afterFooter: helpers$1.noop
  7070. }
  7071. }
  7072. });
  7073. var positioners = {
  7074. /**
  7075. * Average mode places the tooltip at the average position of the elements shown
  7076. * @function Chart.Tooltip.positioners.average
  7077. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  7078. * @returns {object} tooltip position
  7079. */
  7080. average: function(elements) {
  7081. if (!elements.length) {
  7082. return false;
  7083. }
  7084. var i, len;
  7085. var x = 0;
  7086. var y = 0;
  7087. var count = 0;
  7088. for (i = 0, len = elements.length; i < len; ++i) {
  7089. var el = elements[i];
  7090. if (el && el.hasValue()) {
  7091. var pos = el.tooltipPosition();
  7092. x += pos.x;
  7093. y += pos.y;
  7094. ++count;
  7095. }
  7096. }
  7097. return {
  7098. x: x / count,
  7099. y: y / count
  7100. };
  7101. },
  7102. /**
  7103. * Gets the tooltip position nearest of the item nearest to the event position
  7104. * @function Chart.Tooltip.positioners.nearest
  7105. * @param elements {Chart.Element[]} the tooltip elements
  7106. * @param eventPosition {object} the position of the event in canvas coordinates
  7107. * @returns {object} the tooltip position
  7108. */
  7109. nearest: function(elements, eventPosition) {
  7110. var x = eventPosition.x;
  7111. var y = eventPosition.y;
  7112. var minDistance = Number.POSITIVE_INFINITY;
  7113. var i, len, nearestElement;
  7114. for (i = 0, len = elements.length; i < len; ++i) {
  7115. var el = elements[i];
  7116. if (el && el.hasValue()) {
  7117. var center = el.getCenterPoint();
  7118. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  7119. if (d < minDistance) {
  7120. minDistance = d;
  7121. nearestElement = el;
  7122. }
  7123. }
  7124. }
  7125. if (nearestElement) {
  7126. var tp = nearestElement.tooltipPosition();
  7127. x = tp.x;
  7128. y = tp.y;
  7129. }
  7130. return {
  7131. x: x,
  7132. y: y
  7133. };
  7134. }
  7135. };
  7136. // Helper to push or concat based on if the 2nd parameter is an array or not
  7137. function pushOrConcat(base, toPush) {
  7138. if (toPush) {
  7139. if (helpers$1.isArray(toPush)) {
  7140. // base = base.concat(toPush);
  7141. Array.prototype.push.apply(base, toPush);
  7142. } else {
  7143. base.push(toPush);
  7144. }
  7145. }
  7146. return base;
  7147. }
  7148. /**
  7149. * Returns array of strings split by newline
  7150. * @param {string} value - The value to split by newline.
  7151. * @returns {string[]} value if newline present - Returned from String split() method
  7152. * @function
  7153. */
  7154. function splitNewlines(str) {
  7155. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  7156. return str.split('\n');
  7157. }
  7158. return str;
  7159. }
  7160. /**
  7161. * Private helper to create a tooltip item model
  7162. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  7163. * @return new tooltip item
  7164. */
  7165. function createTooltipItem(element) {
  7166. var xScale = element._xScale;
  7167. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  7168. var index = element._index;
  7169. var datasetIndex = element._datasetIndex;
  7170. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  7171. var indexScale = controller._getIndexScale();
  7172. var valueScale = controller._getValueScale();
  7173. return {
  7174. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  7175. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  7176. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  7177. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  7178. index: index,
  7179. datasetIndex: datasetIndex,
  7180. x: element._model.x,
  7181. y: element._model.y
  7182. };
  7183. }
  7184. /**
  7185. * Helper to get the reset model for the tooltip
  7186. * @param tooltipOpts {object} the tooltip options
  7187. */
  7188. function getBaseModel(tooltipOpts) {
  7189. var globalDefaults = core_defaults.global;
  7190. return {
  7191. // Positioning
  7192. xPadding: tooltipOpts.xPadding,
  7193. yPadding: tooltipOpts.yPadding,
  7194. xAlign: tooltipOpts.xAlign,
  7195. yAlign: tooltipOpts.yAlign,
  7196. // Drawing direction and text direction
  7197. rtl: tooltipOpts.rtl,
  7198. textDirection: tooltipOpts.textDirection,
  7199. // Body
  7200. bodyFontColor: tooltipOpts.bodyFontColor,
  7201. _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  7202. _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  7203. _bodyAlign: tooltipOpts.bodyAlign,
  7204. bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  7205. bodySpacing: tooltipOpts.bodySpacing,
  7206. // Title
  7207. titleFontColor: tooltipOpts.titleFontColor,
  7208. _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  7209. _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  7210. titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  7211. _titleAlign: tooltipOpts.titleAlign,
  7212. titleSpacing: tooltipOpts.titleSpacing,
  7213. titleMarginBottom: tooltipOpts.titleMarginBottom,
  7214. // Footer
  7215. footerFontColor: tooltipOpts.footerFontColor,
  7216. _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  7217. _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  7218. footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  7219. _footerAlign: tooltipOpts.footerAlign,
  7220. footerSpacing: tooltipOpts.footerSpacing,
  7221. footerMarginTop: tooltipOpts.footerMarginTop,
  7222. // Appearance
  7223. caretSize: tooltipOpts.caretSize,
  7224. cornerRadius: tooltipOpts.cornerRadius,
  7225. backgroundColor: tooltipOpts.backgroundColor,
  7226. opacity: 0,
  7227. legendColorBackground: tooltipOpts.multiKeyBackground,
  7228. displayColors: tooltipOpts.displayColors,
  7229. borderColor: tooltipOpts.borderColor,
  7230. borderWidth: tooltipOpts.borderWidth
  7231. };
  7232. }
  7233. /**
  7234. * Get the size of the tooltip
  7235. */
  7236. function getTooltipSize(tooltip, model) {
  7237. var ctx = tooltip._chart.ctx;
  7238. var height = model.yPadding * 2; // Tooltip Padding
  7239. var width = 0;
  7240. // Count of all lines in the body
  7241. var body = model.body;
  7242. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  7243. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  7244. }, 0);
  7245. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  7246. var titleLineCount = model.title.length;
  7247. var footerLineCount = model.footer.length;
  7248. var titleFontSize = model.titleFontSize;
  7249. var bodyFontSize = model.bodyFontSize;
  7250. var footerFontSize = model.footerFontSize;
  7251. height += titleLineCount * titleFontSize; // Title Lines
  7252. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  7253. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  7254. height += combinedBodyLength * bodyFontSize; // Body Lines
  7255. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  7256. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  7257. height += footerLineCount * (footerFontSize); // Footer Lines
  7258. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  7259. // Title width
  7260. var widthPadding = 0;
  7261. var maxLineWidth = function(line) {
  7262. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  7263. };
  7264. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  7265. helpers$1.each(model.title, maxLineWidth);
  7266. // Body width
  7267. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  7268. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  7269. // Body lines may include some extra width due to the color box
  7270. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  7271. helpers$1.each(body, function(bodyItem) {
  7272. helpers$1.each(bodyItem.before, maxLineWidth);
  7273. helpers$1.each(bodyItem.lines, maxLineWidth);
  7274. helpers$1.each(bodyItem.after, maxLineWidth);
  7275. });
  7276. // Reset back to 0
  7277. widthPadding = 0;
  7278. // Footer width
  7279. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  7280. helpers$1.each(model.footer, maxLineWidth);
  7281. // Add padding
  7282. width += 2 * model.xPadding;
  7283. return {
  7284. width: width,
  7285. height: height
  7286. };
  7287. }
  7288. /**
  7289. * Helper to get the alignment of a tooltip given the size
  7290. */
  7291. function determineAlignment(tooltip, size) {
  7292. var model = tooltip._model;
  7293. var chart = tooltip._chart;
  7294. var chartArea = tooltip._chart.chartArea;
  7295. var xAlign = 'center';
  7296. var yAlign = 'center';
  7297. if (model.y < size.height) {
  7298. yAlign = 'top';
  7299. } else if (model.y > (chart.height - size.height)) {
  7300. yAlign = 'bottom';
  7301. }
  7302. var lf, rf; // functions to determine left, right alignment
  7303. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  7304. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  7305. var midX = (chartArea.left + chartArea.right) / 2;
  7306. var midY = (chartArea.top + chartArea.bottom) / 2;
  7307. if (yAlign === 'center') {
  7308. lf = function(x) {
  7309. return x <= midX;
  7310. };
  7311. rf = function(x) {
  7312. return x > midX;
  7313. };
  7314. } else {
  7315. lf = function(x) {
  7316. return x <= (size.width / 2);
  7317. };
  7318. rf = function(x) {
  7319. return x >= (chart.width - (size.width / 2));
  7320. };
  7321. }
  7322. olf = function(x) {
  7323. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  7324. };
  7325. orf = function(x) {
  7326. return x - size.width - model.caretSize - model.caretPadding < 0;
  7327. };
  7328. yf = function(y) {
  7329. return y <= midY ? 'top' : 'bottom';
  7330. };
  7331. if (lf(model.x)) {
  7332. xAlign = 'left';
  7333. // Is tooltip too wide and goes over the right side of the chart.?
  7334. if (olf(model.x)) {
  7335. xAlign = 'center';
  7336. yAlign = yf(model.y);
  7337. }
  7338. } else if (rf(model.x)) {
  7339. xAlign = 'right';
  7340. // Is tooltip too wide and goes outside left edge of canvas?
  7341. if (orf(model.x)) {
  7342. xAlign = 'center';
  7343. yAlign = yf(model.y);
  7344. }
  7345. }
  7346. var opts = tooltip._options;
  7347. return {
  7348. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  7349. yAlign: opts.yAlign ? opts.yAlign : yAlign
  7350. };
  7351. }
  7352. /**
  7353. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  7354. */
  7355. function getBackgroundPoint(vm, size, alignment, chart) {
  7356. // Background Position
  7357. var x = vm.x;
  7358. var y = vm.y;
  7359. var caretSize = vm.caretSize;
  7360. var caretPadding = vm.caretPadding;
  7361. var cornerRadius = vm.cornerRadius;
  7362. var xAlign = alignment.xAlign;
  7363. var yAlign = alignment.yAlign;
  7364. var paddingAndSize = caretSize + caretPadding;
  7365. var radiusAndPadding = cornerRadius + caretPadding;
  7366. if (xAlign === 'right') {
  7367. x -= size.width;
  7368. } else if (xAlign === 'center') {
  7369. x -= (size.width / 2);
  7370. if (x + size.width > chart.width) {
  7371. x = chart.width - size.width;
  7372. }
  7373. if (x < 0) {
  7374. x = 0;
  7375. }
  7376. }
  7377. if (yAlign === 'top') {
  7378. y += paddingAndSize;
  7379. } else if (yAlign === 'bottom') {
  7380. y -= size.height + paddingAndSize;
  7381. } else {
  7382. y -= (size.height / 2);
  7383. }
  7384. if (yAlign === 'center') {
  7385. if (xAlign === 'left') {
  7386. x += paddingAndSize;
  7387. } else if (xAlign === 'right') {
  7388. x -= paddingAndSize;
  7389. }
  7390. } else if (xAlign === 'left') {
  7391. x -= radiusAndPadding;
  7392. } else if (xAlign === 'right') {
  7393. x += radiusAndPadding;
  7394. }
  7395. return {
  7396. x: x,
  7397. y: y
  7398. };
  7399. }
  7400. function getAlignedX(vm, align) {
  7401. return align === 'center'
  7402. ? vm.x + vm.width / 2
  7403. : align === 'right'
  7404. ? vm.x + vm.width - vm.xPadding
  7405. : vm.x + vm.xPadding;
  7406. }
  7407. /**
  7408. * Helper to build before and after body lines
  7409. */
  7410. function getBeforeAfterBodyLines(callback) {
  7411. return pushOrConcat([], splitNewlines(callback));
  7412. }
  7413. var exports$4 = core_element.extend({
  7414. initialize: function() {
  7415. this._model = getBaseModel(this._options);
  7416. this._lastActive = [];
  7417. },
  7418. // Get the title
  7419. // Args are: (tooltipItem, data)
  7420. getTitle: function() {
  7421. var me = this;
  7422. var opts = me._options;
  7423. var callbacks = opts.callbacks;
  7424. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  7425. var title = callbacks.title.apply(me, arguments);
  7426. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  7427. var lines = [];
  7428. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  7429. lines = pushOrConcat(lines, splitNewlines(title));
  7430. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  7431. return lines;
  7432. },
  7433. // Args are: (tooltipItem, data)
  7434. getBeforeBody: function() {
  7435. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  7436. },
  7437. // Args are: (tooltipItem, data)
  7438. getBody: function(tooltipItems, data) {
  7439. var me = this;
  7440. var callbacks = me._options.callbacks;
  7441. var bodyItems = [];
  7442. helpers$1.each(tooltipItems, function(tooltipItem) {
  7443. var bodyItem = {
  7444. before: [],
  7445. lines: [],
  7446. after: []
  7447. };
  7448. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  7449. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  7450. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  7451. bodyItems.push(bodyItem);
  7452. });
  7453. return bodyItems;
  7454. },
  7455. // Args are: (tooltipItem, data)
  7456. getAfterBody: function() {
  7457. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  7458. },
  7459. // Get the footer and beforeFooter and afterFooter lines
  7460. // Args are: (tooltipItem, data)
  7461. getFooter: function() {
  7462. var me = this;
  7463. var callbacks = me._options.callbacks;
  7464. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  7465. var footer = callbacks.footer.apply(me, arguments);
  7466. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  7467. var lines = [];
  7468. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  7469. lines = pushOrConcat(lines, splitNewlines(footer));
  7470. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  7471. return lines;
  7472. },
  7473. update: function(changed) {
  7474. var me = this;
  7475. var opts = me._options;
  7476. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  7477. // 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
  7478. // which breaks any animations.
  7479. var existingModel = me._model;
  7480. var model = me._model = getBaseModel(opts);
  7481. var active = me._active;
  7482. var data = me._data;
  7483. // In the case where active.length === 0 we need to keep these at existing values for good animations
  7484. var alignment = {
  7485. xAlign: existingModel.xAlign,
  7486. yAlign: existingModel.yAlign
  7487. };
  7488. var backgroundPoint = {
  7489. x: existingModel.x,
  7490. y: existingModel.y
  7491. };
  7492. var tooltipSize = {
  7493. width: existingModel.width,
  7494. height: existingModel.height
  7495. };
  7496. var tooltipPosition = {
  7497. x: existingModel.caretX,
  7498. y: existingModel.caretY
  7499. };
  7500. var i, len;
  7501. if (active.length) {
  7502. model.opacity = 1;
  7503. var labelColors = [];
  7504. var labelTextColors = [];
  7505. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  7506. var tooltipItems = [];
  7507. for (i = 0, len = active.length; i < len; ++i) {
  7508. tooltipItems.push(createTooltipItem(active[i]));
  7509. }
  7510. // If the user provided a filter function, use it to modify the tooltip items
  7511. if (opts.filter) {
  7512. tooltipItems = tooltipItems.filter(function(a) {
  7513. return opts.filter(a, data);
  7514. });
  7515. }
  7516. // If the user provided a sorting function, use it to modify the tooltip items
  7517. if (opts.itemSort) {
  7518. tooltipItems = tooltipItems.sort(function(a, b) {
  7519. return opts.itemSort(a, b, data);
  7520. });
  7521. }
  7522. // Determine colors for boxes
  7523. helpers$1.each(tooltipItems, function(tooltipItem) {
  7524. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  7525. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  7526. });
  7527. // Build the Text Lines
  7528. model.title = me.getTitle(tooltipItems, data);
  7529. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  7530. model.body = me.getBody(tooltipItems, data);
  7531. model.afterBody = me.getAfterBody(tooltipItems, data);
  7532. model.footer = me.getFooter(tooltipItems, data);
  7533. // Initial positioning and colors
  7534. model.x = tooltipPosition.x;
  7535. model.y = tooltipPosition.y;
  7536. model.caretPadding = opts.caretPadding;
  7537. model.labelColors = labelColors;
  7538. model.labelTextColors = labelTextColors;
  7539. // data points
  7540. model.dataPoints = tooltipItems;
  7541. // We need to determine alignment of the tooltip
  7542. tooltipSize = getTooltipSize(this, model);
  7543. alignment = determineAlignment(this, tooltipSize);
  7544. // Final Size and Position
  7545. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  7546. } else {
  7547. model.opacity = 0;
  7548. }
  7549. model.xAlign = alignment.xAlign;
  7550. model.yAlign = alignment.yAlign;
  7551. model.x = backgroundPoint.x;
  7552. model.y = backgroundPoint.y;
  7553. model.width = tooltipSize.width;
  7554. model.height = tooltipSize.height;
  7555. // Point where the caret on the tooltip points to
  7556. model.caretX = tooltipPosition.x;
  7557. model.caretY = tooltipPosition.y;
  7558. me._model = model;
  7559. if (changed && opts.custom) {
  7560. opts.custom.call(me, model);
  7561. }
  7562. return me;
  7563. },
  7564. drawCaret: function(tooltipPoint, size) {
  7565. var ctx = this._chart.ctx;
  7566. var vm = this._view;
  7567. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  7568. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  7569. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  7570. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  7571. },
  7572. getCaretPosition: function(tooltipPoint, size, vm) {
  7573. var x1, x2, x3, y1, y2, y3;
  7574. var caretSize = vm.caretSize;
  7575. var cornerRadius = vm.cornerRadius;
  7576. var xAlign = vm.xAlign;
  7577. var yAlign = vm.yAlign;
  7578. var ptX = tooltipPoint.x;
  7579. var ptY = tooltipPoint.y;
  7580. var width = size.width;
  7581. var height = size.height;
  7582. if (yAlign === 'center') {
  7583. y2 = ptY + (height / 2);
  7584. if (xAlign === 'left') {
  7585. x1 = ptX;
  7586. x2 = x1 - caretSize;
  7587. x3 = x1;
  7588. y1 = y2 + caretSize;
  7589. y3 = y2 - caretSize;
  7590. } else {
  7591. x1 = ptX + width;
  7592. x2 = x1 + caretSize;
  7593. x3 = x1;
  7594. y1 = y2 - caretSize;
  7595. y3 = y2 + caretSize;
  7596. }
  7597. } else {
  7598. if (xAlign === 'left') {
  7599. x2 = ptX + cornerRadius + (caretSize);
  7600. x1 = x2 - caretSize;
  7601. x3 = x2 + caretSize;
  7602. } else if (xAlign === 'right') {
  7603. x2 = ptX + width - cornerRadius - caretSize;
  7604. x1 = x2 - caretSize;
  7605. x3 = x2 + caretSize;
  7606. } else {
  7607. x2 = vm.caretX;
  7608. x1 = x2 - caretSize;
  7609. x3 = x2 + caretSize;
  7610. }
  7611. if (yAlign === 'top') {
  7612. y1 = ptY;
  7613. y2 = y1 - caretSize;
  7614. y3 = y1;
  7615. } else {
  7616. y1 = ptY + height;
  7617. y2 = y1 + caretSize;
  7618. y3 = y1;
  7619. // invert drawing order
  7620. var tmp = x3;
  7621. x3 = x1;
  7622. x1 = tmp;
  7623. }
  7624. }
  7625. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  7626. },
  7627. drawTitle: function(pt, vm, ctx) {
  7628. var title = vm.title;
  7629. var length = title.length;
  7630. var titleFontSize, titleSpacing, i;
  7631. if (length) {
  7632. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7633. pt.x = getAlignedX(vm, vm._titleAlign);
  7634. ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);
  7635. ctx.textBaseline = 'middle';
  7636. titleFontSize = vm.titleFontSize;
  7637. titleSpacing = vm.titleSpacing;
  7638. ctx.fillStyle = vm.titleFontColor;
  7639. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  7640. for (i = 0; i < length; ++i) {
  7641. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);
  7642. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  7643. if (i + 1 === length) {
  7644. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  7645. }
  7646. }
  7647. }
  7648. },
  7649. drawBody: function(pt, vm, ctx) {
  7650. var bodyFontSize = vm.bodyFontSize;
  7651. var bodySpacing = vm.bodySpacing;
  7652. var bodyAlign = vm._bodyAlign;
  7653. var body = vm.body;
  7654. var drawColorBoxes = vm.displayColors;
  7655. var xLinePadding = 0;
  7656. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  7657. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7658. var fillLineOfText = function(line) {
  7659. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
  7660. pt.y += bodyFontSize + bodySpacing;
  7661. };
  7662. var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;
  7663. var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  7664. ctx.textAlign = bodyAlign;
  7665. ctx.textBaseline = 'middle';
  7666. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  7667. pt.x = getAlignedX(vm, bodyAlignForCalculation);
  7668. // Before body lines
  7669. ctx.fillStyle = vm.bodyFontColor;
  7670. helpers$1.each(vm.beforeBody, fillLineOfText);
  7671. xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'
  7672. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  7673. : 0;
  7674. // Draw body lines now
  7675. for (i = 0, ilen = body.length; i < ilen; ++i) {
  7676. bodyItem = body[i];
  7677. textColor = vm.labelTextColors[i];
  7678. labelColors = vm.labelColors[i];
  7679. ctx.fillStyle = textColor;
  7680. helpers$1.each(bodyItem.before, fillLineOfText);
  7681. lines = bodyItem.lines;
  7682. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  7683. // Draw Legend-like boxes if needed
  7684. if (drawColorBoxes) {
  7685. var rtlColorX = rtlHelper.x(colorX);
  7686. // Fill a white rect so that colours merge nicely if the opacity is < 1
  7687. ctx.fillStyle = vm.legendColorBackground;
  7688. ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7689. // Border
  7690. ctx.lineWidth = 1;
  7691. ctx.strokeStyle = labelColors.borderColor;
  7692. ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7693. // Inner square
  7694. ctx.fillStyle = labelColors.backgroundColor;
  7695. ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  7696. ctx.fillStyle = textColor;
  7697. }
  7698. fillLineOfText(lines[j]);
  7699. }
  7700. helpers$1.each(bodyItem.after, fillLineOfText);
  7701. }
  7702. // Reset back to 0 for after body
  7703. xLinePadding = 0;
  7704. // After body lines
  7705. helpers$1.each(vm.afterBody, fillLineOfText);
  7706. pt.y -= bodySpacing; // Remove last body spacing
  7707. },
  7708. drawFooter: function(pt, vm, ctx) {
  7709. var footer = vm.footer;
  7710. var length = footer.length;
  7711. var footerFontSize, i;
  7712. if (length) {
  7713. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7714. pt.x = getAlignedX(vm, vm._footerAlign);
  7715. pt.y += vm.footerMarginTop;
  7716. ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);
  7717. ctx.textBaseline = 'middle';
  7718. footerFontSize = vm.footerFontSize;
  7719. ctx.fillStyle = vm.footerFontColor;
  7720. ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  7721. for (i = 0; i < length; ++i) {
  7722. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);
  7723. pt.y += footerFontSize + vm.footerSpacing;
  7724. }
  7725. }
  7726. },
  7727. drawBackground: function(pt, vm, ctx, tooltipSize) {
  7728. ctx.fillStyle = vm.backgroundColor;
  7729. ctx.strokeStyle = vm.borderColor;
  7730. ctx.lineWidth = vm.borderWidth;
  7731. var xAlign = vm.xAlign;
  7732. var yAlign = vm.yAlign;
  7733. var x = pt.x;
  7734. var y = pt.y;
  7735. var width = tooltipSize.width;
  7736. var height = tooltipSize.height;
  7737. var radius = vm.cornerRadius;
  7738. ctx.beginPath();
  7739. ctx.moveTo(x + radius, y);
  7740. if (yAlign === 'top') {
  7741. this.drawCaret(pt, tooltipSize);
  7742. }
  7743. ctx.lineTo(x + width - radius, y);
  7744. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7745. if (yAlign === 'center' && xAlign === 'right') {
  7746. this.drawCaret(pt, tooltipSize);
  7747. }
  7748. ctx.lineTo(x + width, y + height - radius);
  7749. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7750. if (yAlign === 'bottom') {
  7751. this.drawCaret(pt, tooltipSize);
  7752. }
  7753. ctx.lineTo(x + radius, y + height);
  7754. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7755. if (yAlign === 'center' && xAlign === 'left') {
  7756. this.drawCaret(pt, tooltipSize);
  7757. }
  7758. ctx.lineTo(x, y + radius);
  7759. ctx.quadraticCurveTo(x, y, x + radius, y);
  7760. ctx.closePath();
  7761. ctx.fill();
  7762. if (vm.borderWidth > 0) {
  7763. ctx.stroke();
  7764. }
  7765. },
  7766. draw: function() {
  7767. var ctx = this._chart.ctx;
  7768. var vm = this._view;
  7769. if (vm.opacity === 0) {
  7770. return;
  7771. }
  7772. var tooltipSize = {
  7773. width: vm.width,
  7774. height: vm.height
  7775. };
  7776. var pt = {
  7777. x: vm.x,
  7778. y: vm.y
  7779. };
  7780. // IE11/Edge does not like very small opacities, so snap to 0
  7781. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7782. // Truthy/falsey value for empty tooltip
  7783. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7784. if (this._options.enabled && hasTooltipContent) {
  7785. ctx.save();
  7786. ctx.globalAlpha = opacity;
  7787. // Draw Background
  7788. this.drawBackground(pt, vm, ctx, tooltipSize);
  7789. // Draw Title, Body, and Footer
  7790. pt.y += vm.yPadding;
  7791. helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);
  7792. // Titles
  7793. this.drawTitle(pt, vm, ctx);
  7794. // Body
  7795. this.drawBody(pt, vm, ctx);
  7796. // Footer
  7797. this.drawFooter(pt, vm, ctx);
  7798. helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);
  7799. ctx.restore();
  7800. }
  7801. },
  7802. /**
  7803. * Handle an event
  7804. * @private
  7805. * @param {IEvent} event - The event to handle
  7806. * @returns {boolean} true if the tooltip changed
  7807. */
  7808. handleEvent: function(e) {
  7809. var me = this;
  7810. var options = me._options;
  7811. var changed = false;
  7812. me._lastActive = me._lastActive || [];
  7813. // Find Active Elements for tooltips
  7814. if (e.type === 'mouseout') {
  7815. me._active = [];
  7816. } else {
  7817. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7818. if (options.reverse) {
  7819. me._active.reverse();
  7820. }
  7821. }
  7822. // Remember Last Actives
  7823. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7824. // Only handle target event on tooltip change
  7825. if (changed) {
  7826. me._lastActive = me._active;
  7827. if (options.enabled || options.custom) {
  7828. me._eventPosition = {
  7829. x: e.x,
  7830. y: e.y
  7831. };
  7832. me.update(true);
  7833. me.pivot();
  7834. }
  7835. }
  7836. return changed;
  7837. }
  7838. });
  7839. /**
  7840. * @namespace Chart.Tooltip.positioners
  7841. */
  7842. var positioners_1 = positioners;
  7843. var core_tooltip = exports$4;
  7844. core_tooltip.positioners = positioners_1;
  7845. var valueOrDefault$9 = helpers$1.valueOrDefault;
  7846. core_defaults._set('global', {
  7847. elements: {},
  7848. events: [
  7849. 'mousemove',
  7850. 'mouseout',
  7851. 'click',
  7852. 'touchstart',
  7853. 'touchmove'
  7854. ],
  7855. hover: {
  7856. onHover: null,
  7857. mode: 'nearest',
  7858. intersect: true,
  7859. animationDuration: 400
  7860. },
  7861. onClick: null,
  7862. maintainAspectRatio: true,
  7863. responsive: true,
  7864. responsiveAnimationDuration: 0
  7865. });
  7866. /**
  7867. * Recursively merge the given config objects representing the `scales` option
  7868. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7869. * returns a deep copy of the result, thus doesn't alter inputs.
  7870. */
  7871. function mergeScaleConfig(/* config objects ... */) {
  7872. return helpers$1.merge({}, [].slice.call(arguments), {
  7873. merger: function(key, target, source, options) {
  7874. if (key === 'xAxes' || key === 'yAxes') {
  7875. var slen = source[key].length;
  7876. var i, type, scale;
  7877. if (!target[key]) {
  7878. target[key] = [];
  7879. }
  7880. for (i = 0; i < slen; ++i) {
  7881. scale = source[key][i];
  7882. type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7883. if (i >= target[key].length) {
  7884. target[key].push({});
  7885. }
  7886. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7887. // new/untyped scale or type changed: let's apply the new defaults
  7888. // then merge source scale to correctly overwrite the defaults.
  7889. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7890. } else {
  7891. // scales type are the same
  7892. helpers$1.merge(target[key][i], scale);
  7893. }
  7894. }
  7895. } else {
  7896. helpers$1._merger(key, target, source, options);
  7897. }
  7898. }
  7899. });
  7900. }
  7901. /**
  7902. * Recursively merge the given config objects as the root options by handling
  7903. * default scale options for the `scales` and `scale` properties, then returns
  7904. * a deep copy of the result, thus doesn't alter inputs.
  7905. */
  7906. function mergeConfig(/* config objects ... */) {
  7907. return helpers$1.merge({}, [].slice.call(arguments), {
  7908. merger: function(key, target, source, options) {
  7909. var tval = target[key] || {};
  7910. var sval = source[key];
  7911. if (key === 'scales') {
  7912. // scale config merging is complex. Add our own function here for that
  7913. target[key] = mergeScaleConfig(tval, sval);
  7914. } else if (key === 'scale') {
  7915. // used in polar area & radar charts since there is only one scale
  7916. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7917. } else {
  7918. helpers$1._merger(key, target, source, options);
  7919. }
  7920. }
  7921. });
  7922. }
  7923. function initConfig(config) {
  7924. config = config || {};
  7925. // Do NOT use mergeConfig for the data object because this method merges arrays
  7926. // and so would change references to labels and datasets, preventing data updates.
  7927. var data = config.data = config.data || {};
  7928. data.datasets = data.datasets || [];
  7929. data.labels = data.labels || [];
  7930. config.options = mergeConfig(
  7931. core_defaults.global,
  7932. core_defaults[config.type],
  7933. config.options || {});
  7934. return config;
  7935. }
  7936. function updateConfig(chart) {
  7937. var newOptions = chart.options;
  7938. helpers$1.each(chart.scales, function(scale) {
  7939. core_layouts.removeBox(chart, scale);
  7940. });
  7941. newOptions = mergeConfig(
  7942. core_defaults.global,
  7943. core_defaults[chart.config.type],
  7944. newOptions);
  7945. chart.options = chart.config.options = newOptions;
  7946. chart.ensureScalesHaveIDs();
  7947. chart.buildOrUpdateScales();
  7948. // Tooltip
  7949. chart.tooltip._options = newOptions.tooltips;
  7950. chart.tooltip.initialize();
  7951. }
  7952. function nextAvailableScaleId(axesOpts, prefix, index) {
  7953. var id;
  7954. var hasId = function(obj) {
  7955. return obj.id === id;
  7956. };
  7957. do {
  7958. id = prefix + index++;
  7959. } while (helpers$1.findIndex(axesOpts, hasId) >= 0);
  7960. return id;
  7961. }
  7962. function positionIsHorizontal(position) {
  7963. return position === 'top' || position === 'bottom';
  7964. }
  7965. function compare2Level(l1, l2) {
  7966. return function(a, b) {
  7967. return a[l1] === b[l1]
  7968. ? a[l2] - b[l2]
  7969. : a[l1] - b[l1];
  7970. };
  7971. }
  7972. var Chart = function(item, config) {
  7973. this.construct(item, config);
  7974. return this;
  7975. };
  7976. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  7977. /**
  7978. * @private
  7979. */
  7980. construct: function(item, config) {
  7981. var me = this;
  7982. config = initConfig(config);
  7983. var context = platform.acquireContext(item, config);
  7984. var canvas = context && context.canvas;
  7985. var height = canvas && canvas.height;
  7986. var width = canvas && canvas.width;
  7987. me.id = helpers$1.uid();
  7988. me.ctx = context;
  7989. me.canvas = canvas;
  7990. me.config = config;
  7991. me.width = width;
  7992. me.height = height;
  7993. me.aspectRatio = height ? width / height : null;
  7994. me.options = config.options;
  7995. me._bufferedRender = false;
  7996. me._layers = [];
  7997. /**
  7998. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  7999. * the "instance" still need to be defined since it might be called from plugins.
  8000. * @prop Chart#chart
  8001. * @deprecated since version 2.6.0
  8002. * @todo remove at version 3
  8003. * @private
  8004. */
  8005. me.chart = me;
  8006. me.controller = me; // chart.chart.controller #inception
  8007. // Add the chart instance to the global namespace
  8008. Chart.instances[me.id] = me;
  8009. // Define alias to the config data: `chart.data === chart.config.data`
  8010. Object.defineProperty(me, 'data', {
  8011. get: function() {
  8012. return me.config.data;
  8013. },
  8014. set: function(value) {
  8015. me.config.data = value;
  8016. }
  8017. });
  8018. if (!context || !canvas) {
  8019. // The given item is not a compatible context2d element, let's return before finalizing
  8020. // the chart initialization but after setting basic chart / controller properties that
  8021. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  8022. // https://github.com/chartjs/Chart.js/issues/2807
  8023. console.error("Failed to create chart: can't acquire context from the given item");
  8024. return;
  8025. }
  8026. me.initialize();
  8027. me.update();
  8028. },
  8029. /**
  8030. * @private
  8031. */
  8032. initialize: function() {
  8033. var me = this;
  8034. // Before init plugin notification
  8035. core_plugins.notify(me, 'beforeInit');
  8036. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  8037. me.bindEvents();
  8038. if (me.options.responsive) {
  8039. // Initial resize before chart draws (must be silent to preserve initial animations).
  8040. me.resize(true);
  8041. }
  8042. me.initToolTip();
  8043. // After init plugin notification
  8044. core_plugins.notify(me, 'afterInit');
  8045. return me;
  8046. },
  8047. clear: function() {
  8048. helpers$1.canvas.clear(this);
  8049. return this;
  8050. },
  8051. stop: function() {
  8052. // Stops any current animation loop occurring
  8053. core_animations.cancelAnimation(this);
  8054. return this;
  8055. },
  8056. resize: function(silent) {
  8057. var me = this;
  8058. var options = me.options;
  8059. var canvas = me.canvas;
  8060. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  8061. // the canvas render width and height will be casted to integers so make sure that
  8062. // the canvas display style uses the same integer values to avoid blurring effect.
  8063. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  8064. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  8065. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  8066. if (me.width === newWidth && me.height === newHeight) {
  8067. return;
  8068. }
  8069. canvas.width = me.width = newWidth;
  8070. canvas.height = me.height = newHeight;
  8071. canvas.style.width = newWidth + 'px';
  8072. canvas.style.height = newHeight + 'px';
  8073. helpers$1.retinaScale(me, options.devicePixelRatio);
  8074. if (!silent) {
  8075. // Notify any plugins about the resize
  8076. var newSize = {width: newWidth, height: newHeight};
  8077. core_plugins.notify(me, 'resize', [newSize]);
  8078. // Notify of resize
  8079. if (options.onResize) {
  8080. options.onResize(me, newSize);
  8081. }
  8082. me.stop();
  8083. me.update({
  8084. duration: options.responsiveAnimationDuration
  8085. });
  8086. }
  8087. },
  8088. ensureScalesHaveIDs: function() {
  8089. var options = this.options;
  8090. var scalesOptions = options.scales || {};
  8091. var scaleOptions = options.scale;
  8092. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  8093. if (!xAxisOptions.id) {
  8094. xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);
  8095. }
  8096. });
  8097. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  8098. if (!yAxisOptions.id) {
  8099. yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);
  8100. }
  8101. });
  8102. if (scaleOptions) {
  8103. scaleOptions.id = scaleOptions.id || 'scale';
  8104. }
  8105. },
  8106. /**
  8107. * Builds a map of scale ID to scale object for future lookup.
  8108. */
  8109. buildOrUpdateScales: function() {
  8110. var me = this;
  8111. var options = me.options;
  8112. var scales = me.scales || {};
  8113. var items = [];
  8114. var updated = Object.keys(scales).reduce(function(obj, id) {
  8115. obj[id] = false;
  8116. return obj;
  8117. }, {});
  8118. if (options.scales) {
  8119. items = items.concat(
  8120. (options.scales.xAxes || []).map(function(xAxisOptions) {
  8121. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  8122. }),
  8123. (options.scales.yAxes || []).map(function(yAxisOptions) {
  8124. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  8125. })
  8126. );
  8127. }
  8128. if (options.scale) {
  8129. items.push({
  8130. options: options.scale,
  8131. dtype: 'radialLinear',
  8132. isDefault: true,
  8133. dposition: 'chartArea'
  8134. });
  8135. }
  8136. helpers$1.each(items, function(item) {
  8137. var scaleOptions = item.options;
  8138. var id = scaleOptions.id;
  8139. var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);
  8140. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  8141. scaleOptions.position = item.dposition;
  8142. }
  8143. updated[id] = true;
  8144. var scale = null;
  8145. if (id in scales && scales[id].type === scaleType) {
  8146. scale = scales[id];
  8147. scale.options = scaleOptions;
  8148. scale.ctx = me.ctx;
  8149. scale.chart = me;
  8150. } else {
  8151. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  8152. if (!scaleClass) {
  8153. return;
  8154. }
  8155. scale = new scaleClass({
  8156. id: id,
  8157. type: scaleType,
  8158. options: scaleOptions,
  8159. ctx: me.ctx,
  8160. chart: me
  8161. });
  8162. scales[scale.id] = scale;
  8163. }
  8164. scale.mergeTicksOptions();
  8165. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  8166. // and consider it as a regular scale part of the "scales"" map only! This would
  8167. // make the logic easier and remove some useless? custom code.
  8168. if (item.isDefault) {
  8169. me.scale = scale;
  8170. }
  8171. });
  8172. // clear up discarded scales
  8173. helpers$1.each(updated, function(hasUpdated, id) {
  8174. if (!hasUpdated) {
  8175. delete scales[id];
  8176. }
  8177. });
  8178. me.scales = scales;
  8179. core_scaleService.addScalesToLayout(this);
  8180. },
  8181. buildOrUpdateControllers: function() {
  8182. var me = this;
  8183. var newControllers = [];
  8184. var datasets = me.data.datasets;
  8185. var i, ilen;
  8186. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  8187. var dataset = datasets[i];
  8188. var meta = me.getDatasetMeta(i);
  8189. var type = dataset.type || me.config.type;
  8190. if (meta.type && meta.type !== type) {
  8191. me.destroyDatasetMeta(i);
  8192. meta = me.getDatasetMeta(i);
  8193. }
  8194. meta.type = type;
  8195. meta.order = dataset.order || 0;
  8196. meta.index = i;
  8197. if (meta.controller) {
  8198. meta.controller.updateIndex(i);
  8199. meta.controller.linkScales();
  8200. } else {
  8201. var ControllerClass = controllers[meta.type];
  8202. if (ControllerClass === undefined) {
  8203. throw new Error('"' + meta.type + '" is not a chart type.');
  8204. }
  8205. meta.controller = new ControllerClass(me, i);
  8206. newControllers.push(meta.controller);
  8207. }
  8208. }
  8209. return newControllers;
  8210. },
  8211. /**
  8212. * Reset the elements of all datasets
  8213. * @private
  8214. */
  8215. resetElements: function() {
  8216. var me = this;
  8217. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  8218. me.getDatasetMeta(datasetIndex).controller.reset();
  8219. }, me);
  8220. },
  8221. /**
  8222. * Resets the chart back to it's state before the initial animation
  8223. */
  8224. reset: function() {
  8225. this.resetElements();
  8226. this.tooltip.initialize();
  8227. },
  8228. update: function(config) {
  8229. var me = this;
  8230. var i, ilen;
  8231. if (!config || typeof config !== 'object') {
  8232. // backwards compatibility
  8233. config = {
  8234. duration: config,
  8235. lazy: arguments[1]
  8236. };
  8237. }
  8238. updateConfig(me);
  8239. // plugins options references might have change, let's invalidate the cache
  8240. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  8241. core_plugins._invalidate(me);
  8242. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  8243. return;
  8244. }
  8245. // In case the entire data object changed
  8246. me.tooltip._data = me.data;
  8247. // Make sure dataset controllers are updated and new controllers are reset
  8248. var newControllers = me.buildOrUpdateControllers();
  8249. // Make sure all dataset controllers have correct meta data counts
  8250. for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  8251. me.getDatasetMeta(i).controller.buildOrUpdateElements();
  8252. }
  8253. me.updateLayout();
  8254. // Can only reset the new controllers after the scales have been updated
  8255. if (me.options.animation && me.options.animation.duration) {
  8256. helpers$1.each(newControllers, function(controller) {
  8257. controller.reset();
  8258. });
  8259. }
  8260. me.updateDatasets();
  8261. // Need to reset tooltip in case it is displayed with elements that are removed
  8262. // after update.
  8263. me.tooltip.initialize();
  8264. // Last active contains items that were previously in the tooltip.
  8265. // When we reset the tooltip, we need to clear it
  8266. me.lastActive = [];
  8267. // Do this before render so that any plugins that need final scale updates can use it
  8268. core_plugins.notify(me, 'afterUpdate');
  8269. me._layers.sort(compare2Level('z', '_idx'));
  8270. if (me._bufferedRender) {
  8271. me._bufferedRequest = {
  8272. duration: config.duration,
  8273. easing: config.easing,
  8274. lazy: config.lazy
  8275. };
  8276. } else {
  8277. me.render(config);
  8278. }
  8279. },
  8280. /**
  8281. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  8282. * hook, in which case, plugins will not be called on `afterLayout`.
  8283. * @private
  8284. */
  8285. updateLayout: function() {
  8286. var me = this;
  8287. if (core_plugins.notify(me, 'beforeLayout') === false) {
  8288. return;
  8289. }
  8290. core_layouts.update(this, this.width, this.height);
  8291. me._layers = [];
  8292. helpers$1.each(me.boxes, function(box) {
  8293. // _configure is called twice, once in core.scale.update and once here.
  8294. // Here the boxes are fully updated and at their final positions.
  8295. if (box._configure) {
  8296. box._configure();
  8297. }
  8298. me._layers.push.apply(me._layers, box._layers());
  8299. }, me);
  8300. me._layers.forEach(function(item, index) {
  8301. item._idx = index;
  8302. });
  8303. /**
  8304. * Provided for backward compatibility, use `afterLayout` instead.
  8305. * @method IPlugin#afterScaleUpdate
  8306. * @deprecated since version 2.5.0
  8307. * @todo remove at version 3
  8308. * @private
  8309. */
  8310. core_plugins.notify(me, 'afterScaleUpdate');
  8311. core_plugins.notify(me, 'afterLayout');
  8312. },
  8313. /**
  8314. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  8315. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  8316. * @private
  8317. */
  8318. updateDatasets: function() {
  8319. var me = this;
  8320. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  8321. return;
  8322. }
  8323. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8324. me.updateDataset(i);
  8325. }
  8326. core_plugins.notify(me, 'afterDatasetsUpdate');
  8327. },
  8328. /**
  8329. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  8330. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  8331. * @private
  8332. */
  8333. updateDataset: function(index) {
  8334. var me = this;
  8335. var meta = me.getDatasetMeta(index);
  8336. var args = {
  8337. meta: meta,
  8338. index: index
  8339. };
  8340. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  8341. return;
  8342. }
  8343. meta.controller._update();
  8344. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  8345. },
  8346. render: function(config) {
  8347. var me = this;
  8348. if (!config || typeof config !== 'object') {
  8349. // backwards compatibility
  8350. config = {
  8351. duration: config,
  8352. lazy: arguments[1]
  8353. };
  8354. }
  8355. var animationOptions = me.options.animation;
  8356. var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);
  8357. var lazy = config.lazy;
  8358. if (core_plugins.notify(me, 'beforeRender') === false) {
  8359. return;
  8360. }
  8361. var onComplete = function(animation) {
  8362. core_plugins.notify(me, 'afterRender');
  8363. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  8364. };
  8365. if (animationOptions && duration) {
  8366. var animation = new core_animation({
  8367. numSteps: duration / 16.66, // 60 fps
  8368. easing: config.easing || animationOptions.easing,
  8369. render: function(chart, animationObject) {
  8370. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  8371. var currentStep = animationObject.currentStep;
  8372. var stepDecimal = currentStep / animationObject.numSteps;
  8373. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  8374. },
  8375. onAnimationProgress: animationOptions.onProgress,
  8376. onAnimationComplete: onComplete
  8377. });
  8378. core_animations.addAnimation(me, animation, duration, lazy);
  8379. } else {
  8380. me.draw();
  8381. // See https://github.com/chartjs/Chart.js/issues/3781
  8382. onComplete(new core_animation({numSteps: 0, chart: me}));
  8383. }
  8384. return me;
  8385. },
  8386. draw: function(easingValue) {
  8387. var me = this;
  8388. var i, layers;
  8389. me.clear();
  8390. if (helpers$1.isNullOrUndef(easingValue)) {
  8391. easingValue = 1;
  8392. }
  8393. me.transition(easingValue);
  8394. if (me.width <= 0 || me.height <= 0) {
  8395. return;
  8396. }
  8397. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  8398. return;
  8399. }
  8400. // Because of plugin hooks (before/afterDatasetsDraw), datasets can't
  8401. // currently be part of layers. Instead, we draw
  8402. // layers <= 0 before(default, backward compat), and the rest after
  8403. layers = me._layers;
  8404. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  8405. layers[i].draw(me.chartArea);
  8406. }
  8407. me.drawDatasets(easingValue);
  8408. // Rest of layers
  8409. for (; i < layers.length; ++i) {
  8410. layers[i].draw(me.chartArea);
  8411. }
  8412. me._drawTooltip(easingValue);
  8413. core_plugins.notify(me, 'afterDraw', [easingValue]);
  8414. },
  8415. /**
  8416. * @private
  8417. */
  8418. transition: function(easingValue) {
  8419. var me = this;
  8420. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  8421. if (me.isDatasetVisible(i)) {
  8422. me.getDatasetMeta(i).controller.transition(easingValue);
  8423. }
  8424. }
  8425. me.tooltip.transition(easingValue);
  8426. },
  8427. /**
  8428. * @private
  8429. */
  8430. _getSortedDatasetMetas: function(filterVisible) {
  8431. var me = this;
  8432. var datasets = me.data.datasets || [];
  8433. var result = [];
  8434. var i, ilen;
  8435. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  8436. if (!filterVisible || me.isDatasetVisible(i)) {
  8437. result.push(me.getDatasetMeta(i));
  8438. }
  8439. }
  8440. result.sort(compare2Level('order', 'index'));
  8441. return result;
  8442. },
  8443. /**
  8444. * @private
  8445. */
  8446. _getSortedVisibleDatasetMetas: function() {
  8447. return this._getSortedDatasetMetas(true);
  8448. },
  8449. /**
  8450. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  8451. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  8452. * @private
  8453. */
  8454. drawDatasets: function(easingValue) {
  8455. var me = this;
  8456. var metasets, i;
  8457. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  8458. return;
  8459. }
  8460. metasets = me._getSortedVisibleDatasetMetas();
  8461. for (i = metasets.length - 1; i >= 0; --i) {
  8462. me.drawDataset(metasets[i], easingValue);
  8463. }
  8464. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  8465. },
  8466. /**
  8467. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  8468. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  8469. * @private
  8470. */
  8471. drawDataset: function(meta, easingValue) {
  8472. var me = this;
  8473. var args = {
  8474. meta: meta,
  8475. index: meta.index,
  8476. easingValue: easingValue
  8477. };
  8478. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  8479. return;
  8480. }
  8481. meta.controller.draw(easingValue);
  8482. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  8483. },
  8484. /**
  8485. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  8486. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  8487. * @private
  8488. */
  8489. _drawTooltip: function(easingValue) {
  8490. var me = this;
  8491. var tooltip = me.tooltip;
  8492. var args = {
  8493. tooltip: tooltip,
  8494. easingValue: easingValue
  8495. };
  8496. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  8497. return;
  8498. }
  8499. tooltip.draw();
  8500. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  8501. },
  8502. /**
  8503. * Get the single element that was clicked on
  8504. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  8505. */
  8506. getElementAtEvent: function(e) {
  8507. return core_interaction.modes.single(this, e);
  8508. },
  8509. getElementsAtEvent: function(e) {
  8510. return core_interaction.modes.label(this, e, {intersect: true});
  8511. },
  8512. getElementsAtXAxis: function(e) {
  8513. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  8514. },
  8515. getElementsAtEventForMode: function(e, mode, options) {
  8516. var method = core_interaction.modes[mode];
  8517. if (typeof method === 'function') {
  8518. return method(this, e, options);
  8519. }
  8520. return [];
  8521. },
  8522. getDatasetAtEvent: function(e) {
  8523. return core_interaction.modes.dataset(this, e, {intersect: true});
  8524. },
  8525. getDatasetMeta: function(datasetIndex) {
  8526. var me = this;
  8527. var dataset = me.data.datasets[datasetIndex];
  8528. if (!dataset._meta) {
  8529. dataset._meta = {};
  8530. }
  8531. var meta = dataset._meta[me.id];
  8532. if (!meta) {
  8533. meta = dataset._meta[me.id] = {
  8534. type: null,
  8535. data: [],
  8536. dataset: null,
  8537. controller: null,
  8538. hidden: null, // See isDatasetVisible() comment
  8539. xAxisID: null,
  8540. yAxisID: null,
  8541. order: dataset.order || 0,
  8542. index: datasetIndex
  8543. };
  8544. }
  8545. return meta;
  8546. },
  8547. getVisibleDatasetCount: function() {
  8548. var count = 0;
  8549. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  8550. if (this.isDatasetVisible(i)) {
  8551. count++;
  8552. }
  8553. }
  8554. return count;
  8555. },
  8556. isDatasetVisible: function(datasetIndex) {
  8557. var meta = this.getDatasetMeta(datasetIndex);
  8558. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  8559. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  8560. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  8561. },
  8562. generateLegend: function() {
  8563. return this.options.legendCallback(this);
  8564. },
  8565. /**
  8566. * @private
  8567. */
  8568. destroyDatasetMeta: function(datasetIndex) {
  8569. var id = this.id;
  8570. var dataset = this.data.datasets[datasetIndex];
  8571. var meta = dataset._meta && dataset._meta[id];
  8572. if (meta) {
  8573. meta.controller.destroy();
  8574. delete dataset._meta[id];
  8575. }
  8576. },
  8577. destroy: function() {
  8578. var me = this;
  8579. var canvas = me.canvas;
  8580. var i, ilen;
  8581. me.stop();
  8582. // dataset controllers need to cleanup associated data
  8583. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8584. me.destroyDatasetMeta(i);
  8585. }
  8586. if (canvas) {
  8587. me.unbindEvents();
  8588. helpers$1.canvas.clear(me);
  8589. platform.releaseContext(me.ctx);
  8590. me.canvas = null;
  8591. me.ctx = null;
  8592. }
  8593. core_plugins.notify(me, 'destroy');
  8594. delete Chart.instances[me.id];
  8595. },
  8596. toBase64Image: function() {
  8597. return this.canvas.toDataURL.apply(this.canvas, arguments);
  8598. },
  8599. initToolTip: function() {
  8600. var me = this;
  8601. me.tooltip = new core_tooltip({
  8602. _chart: me,
  8603. _chartInstance: me, // deprecated, backward compatibility
  8604. _data: me.data,
  8605. _options: me.options.tooltips
  8606. }, me);
  8607. },
  8608. /**
  8609. * @private
  8610. */
  8611. bindEvents: function() {
  8612. var me = this;
  8613. var listeners = me._listeners = {};
  8614. var listener = function() {
  8615. me.eventHandler.apply(me, arguments);
  8616. };
  8617. helpers$1.each(me.options.events, function(type) {
  8618. platform.addEventListener(me, type, listener);
  8619. listeners[type] = listener;
  8620. });
  8621. // Elements used to detect size change should not be injected for non responsive charts.
  8622. // See https://github.com/chartjs/Chart.js/issues/2210
  8623. if (me.options.responsive) {
  8624. listener = function() {
  8625. me.resize();
  8626. };
  8627. platform.addEventListener(me, 'resize', listener);
  8628. listeners.resize = listener;
  8629. }
  8630. },
  8631. /**
  8632. * @private
  8633. */
  8634. unbindEvents: function() {
  8635. var me = this;
  8636. var listeners = me._listeners;
  8637. if (!listeners) {
  8638. return;
  8639. }
  8640. delete me._listeners;
  8641. helpers$1.each(listeners, function(listener, type) {
  8642. platform.removeEventListener(me, type, listener);
  8643. });
  8644. },
  8645. updateHoverStyle: function(elements, mode, enabled) {
  8646. var prefix = enabled ? 'set' : 'remove';
  8647. var element, i, ilen;
  8648. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  8649. element = elements[i];
  8650. if (element) {
  8651. this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);
  8652. }
  8653. }
  8654. if (mode === 'dataset') {
  8655. this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();
  8656. }
  8657. },
  8658. /**
  8659. * @private
  8660. */
  8661. eventHandler: function(e) {
  8662. var me = this;
  8663. var tooltip = me.tooltip;
  8664. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  8665. return;
  8666. }
  8667. // Buffer any update calls so that renders do not occur
  8668. me._bufferedRender = true;
  8669. me._bufferedRequest = null;
  8670. var changed = me.handleEvent(e);
  8671. // for smooth tooltip animations issue #4989
  8672. // the tooltip should be the source of change
  8673. // Animation check workaround:
  8674. // tooltip._start will be null when tooltip isn't animating
  8675. if (tooltip) {
  8676. changed = tooltip._start
  8677. ? tooltip.handleEvent(e)
  8678. : changed | tooltip.handleEvent(e);
  8679. }
  8680. core_plugins.notify(me, 'afterEvent', [e]);
  8681. var bufferedRequest = me._bufferedRequest;
  8682. if (bufferedRequest) {
  8683. // If we have an update that was triggered, we need to do a normal render
  8684. me.render(bufferedRequest);
  8685. } else if (changed && !me.animating) {
  8686. // If entering, leaving, or changing elements, animate the change via pivot
  8687. me.stop();
  8688. // We only need to render at this point. Updating will cause scales to be
  8689. // recomputed generating flicker & using more memory than necessary.
  8690. me.render({
  8691. duration: me.options.hover.animationDuration,
  8692. lazy: true
  8693. });
  8694. }
  8695. me._bufferedRender = false;
  8696. me._bufferedRequest = null;
  8697. return me;
  8698. },
  8699. /**
  8700. * Handle an event
  8701. * @private
  8702. * @param {IEvent} event the event to handle
  8703. * @return {boolean} true if the chart needs to re-render
  8704. */
  8705. handleEvent: function(e) {
  8706. var me = this;
  8707. var options = me.options || {};
  8708. var hoverOptions = options.hover;
  8709. var changed = false;
  8710. me.lastActive = me.lastActive || [];
  8711. // Find Active Elements for hover and tooltips
  8712. if (e.type === 'mouseout') {
  8713. me.active = [];
  8714. } else {
  8715. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  8716. }
  8717. // Invoke onHover hook
  8718. // Need to call with native event here to not break backwards compatibility
  8719. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  8720. if (e.type === 'mouseup' || e.type === 'click') {
  8721. if (options.onClick) {
  8722. // Use e.native here for backwards compatibility
  8723. options.onClick.call(me, e.native, me.active);
  8724. }
  8725. }
  8726. // Remove styling for last active (even if it may still be active)
  8727. if (me.lastActive.length) {
  8728. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  8729. }
  8730. // Built in hover styling
  8731. if (me.active.length && hoverOptions.mode) {
  8732. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  8733. }
  8734. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  8735. // Remember Last Actives
  8736. me.lastActive = me.active;
  8737. return changed;
  8738. }
  8739. });
  8740. /**
  8741. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  8742. * for backward compatibility. Though, it can still be useful for plugins that
  8743. * would need to work on multiple charts?!
  8744. */
  8745. Chart.instances = {};
  8746. var core_controller = Chart;
  8747. // DEPRECATIONS
  8748. /**
  8749. * Provided for backward compatibility, use Chart instead.
  8750. * @class Chart.Controller
  8751. * @deprecated since version 2.6
  8752. * @todo remove at version 3
  8753. * @private
  8754. */
  8755. Chart.Controller = Chart;
  8756. /**
  8757. * Provided for backward compatibility, not available anymore.
  8758. * @namespace Chart
  8759. * @deprecated since version 2.8
  8760. * @todo remove at version 3
  8761. * @private
  8762. */
  8763. Chart.types = {};
  8764. /**
  8765. * Provided for backward compatibility, not available anymore.
  8766. * @namespace Chart.helpers.configMerge
  8767. * @deprecated since version 2.8.0
  8768. * @todo remove at version 3
  8769. * @private
  8770. */
  8771. helpers$1.configMerge = mergeConfig;
  8772. /**
  8773. * Provided for backward compatibility, not available anymore.
  8774. * @namespace Chart.helpers.scaleMerge
  8775. * @deprecated since version 2.8.0
  8776. * @todo remove at version 3
  8777. * @private
  8778. */
  8779. helpers$1.scaleMerge = mergeScaleConfig;
  8780. var core_helpers = function() {
  8781. // -- Basic js utility methods
  8782. helpers$1.where = function(collection, filterCallback) {
  8783. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  8784. return collection.filter(filterCallback);
  8785. }
  8786. var filtered = [];
  8787. helpers$1.each(collection, function(item) {
  8788. if (filterCallback(item)) {
  8789. filtered.push(item);
  8790. }
  8791. });
  8792. return filtered;
  8793. };
  8794. helpers$1.findIndex = Array.prototype.findIndex ?
  8795. function(array, callback, scope) {
  8796. return array.findIndex(callback, scope);
  8797. } :
  8798. function(array, callback, scope) {
  8799. scope = scope === undefined ? array : scope;
  8800. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  8801. if (callback.call(scope, array[i], i, array)) {
  8802. return i;
  8803. }
  8804. }
  8805. return -1;
  8806. };
  8807. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  8808. // Default to start of the array
  8809. if (helpers$1.isNullOrUndef(startIndex)) {
  8810. startIndex = -1;
  8811. }
  8812. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8813. var currentItem = arrayToSearch[i];
  8814. if (filterCallback(currentItem)) {
  8815. return currentItem;
  8816. }
  8817. }
  8818. };
  8819. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8820. // Default to end of the array
  8821. if (helpers$1.isNullOrUndef(startIndex)) {
  8822. startIndex = arrayToSearch.length;
  8823. }
  8824. for (var i = startIndex - 1; i >= 0; i--) {
  8825. var currentItem = arrayToSearch[i];
  8826. if (filterCallback(currentItem)) {
  8827. return currentItem;
  8828. }
  8829. }
  8830. };
  8831. // -- Math methods
  8832. helpers$1.isNumber = function(n) {
  8833. return !isNaN(parseFloat(n)) && isFinite(n);
  8834. };
  8835. helpers$1.almostEquals = function(x, y, epsilon) {
  8836. return Math.abs(x - y) < epsilon;
  8837. };
  8838. helpers$1.almostWhole = function(x, epsilon) {
  8839. var rounded = Math.round(x);
  8840. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  8841. };
  8842. helpers$1.max = function(array) {
  8843. return array.reduce(function(max, value) {
  8844. if (!isNaN(value)) {
  8845. return Math.max(max, value);
  8846. }
  8847. return max;
  8848. }, Number.NEGATIVE_INFINITY);
  8849. };
  8850. helpers$1.min = function(array) {
  8851. return array.reduce(function(min, value) {
  8852. if (!isNaN(value)) {
  8853. return Math.min(min, value);
  8854. }
  8855. return min;
  8856. }, Number.POSITIVE_INFINITY);
  8857. };
  8858. helpers$1.sign = Math.sign ?
  8859. function(x) {
  8860. return Math.sign(x);
  8861. } :
  8862. function(x) {
  8863. x = +x; // convert to a number
  8864. if (x === 0 || isNaN(x)) {
  8865. return x;
  8866. }
  8867. return x > 0 ? 1 : -1;
  8868. };
  8869. helpers$1.toRadians = function(degrees) {
  8870. return degrees * (Math.PI / 180);
  8871. };
  8872. helpers$1.toDegrees = function(radians) {
  8873. return radians * (180 / Math.PI);
  8874. };
  8875. /**
  8876. * Returns the number of decimal places
  8877. * i.e. the number of digits after the decimal point, of the value of this Number.
  8878. * @param {number} x - A number.
  8879. * @returns {number} The number of decimal places.
  8880. * @private
  8881. */
  8882. helpers$1._decimalPlaces = function(x) {
  8883. if (!helpers$1.isFinite(x)) {
  8884. return;
  8885. }
  8886. var e = 1;
  8887. var p = 0;
  8888. while (Math.round(x * e) / e !== x) {
  8889. e *= 10;
  8890. p++;
  8891. }
  8892. return p;
  8893. };
  8894. // Gets the angle from vertical upright to the point about a centre.
  8895. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  8896. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8897. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8898. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8899. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8900. if (angle < (-0.5 * Math.PI)) {
  8901. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8902. }
  8903. return {
  8904. angle: angle,
  8905. distance: radialDistanceFromCenter
  8906. };
  8907. };
  8908. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  8909. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8910. };
  8911. /**
  8912. * Provided for backward compatibility, not available anymore
  8913. * @function Chart.helpers.aliasPixel
  8914. * @deprecated since version 2.8.0
  8915. * @todo remove at version 3
  8916. */
  8917. helpers$1.aliasPixel = function(pixelWidth) {
  8918. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8919. };
  8920. /**
  8921. * Returns the aligned pixel value to avoid anti-aliasing blur
  8922. * @param {Chart} chart - The chart instance.
  8923. * @param {number} pixel - A pixel value.
  8924. * @param {number} width - The width of the element.
  8925. * @returns {number} The aligned pixel value.
  8926. * @private
  8927. */
  8928. helpers$1._alignPixel = function(chart, pixel, width) {
  8929. var devicePixelRatio = chart.currentDevicePixelRatio;
  8930. var halfWidth = width / 2;
  8931. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8932. };
  8933. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8934. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8935. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8936. // This function must also respect "skipped" points
  8937. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8938. var current = middlePoint;
  8939. var next = afterPoint.skip ? middlePoint : afterPoint;
  8940. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8941. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8942. var s01 = d01 / (d01 + d12);
  8943. var s12 = d12 / (d01 + d12);
  8944. // If all points are the same, s01 & s02 will be inf
  8945. s01 = isNaN(s01) ? 0 : s01;
  8946. s12 = isNaN(s12) ? 0 : s12;
  8947. var fa = t * s01; // scaling factor for triangle Ta
  8948. var fb = t * s12;
  8949. return {
  8950. previous: {
  8951. x: current.x - fa * (next.x - previous.x),
  8952. y: current.y - fa * (next.y - previous.y)
  8953. },
  8954. next: {
  8955. x: current.x + fb * (next.x - previous.x),
  8956. y: current.y + fb * (next.y - previous.y)
  8957. }
  8958. };
  8959. };
  8960. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  8961. helpers$1.splineCurveMonotone = function(points) {
  8962. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8963. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8964. // between the dataset discrete points due to the interpolation.
  8965. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8966. var pointsWithTangents = (points || []).map(function(point) {
  8967. return {
  8968. model: point._model,
  8969. deltaK: 0,
  8970. mK: 0
  8971. };
  8972. });
  8973. // Calculate slopes (deltaK) and initialize tangents (mK)
  8974. var pointsLen = pointsWithTangents.length;
  8975. var i, pointBefore, pointCurrent, pointAfter;
  8976. for (i = 0; i < pointsLen; ++i) {
  8977. pointCurrent = pointsWithTangents[i];
  8978. if (pointCurrent.model.skip) {
  8979. continue;
  8980. }
  8981. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8982. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8983. if (pointAfter && !pointAfter.model.skip) {
  8984. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8985. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  8986. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  8987. }
  8988. if (!pointBefore || pointBefore.model.skip) {
  8989. pointCurrent.mK = pointCurrent.deltaK;
  8990. } else if (!pointAfter || pointAfter.model.skip) {
  8991. pointCurrent.mK = pointBefore.deltaK;
  8992. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  8993. pointCurrent.mK = 0;
  8994. } else {
  8995. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  8996. }
  8997. }
  8998. // Adjust tangents to ensure monotonic properties
  8999. var alphaK, betaK, tauK, squaredMagnitude;
  9000. for (i = 0; i < pointsLen - 1; ++i) {
  9001. pointCurrent = pointsWithTangents[i];
  9002. pointAfter = pointsWithTangents[i + 1];
  9003. if (pointCurrent.model.skip || pointAfter.model.skip) {
  9004. continue;
  9005. }
  9006. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  9007. pointCurrent.mK = pointAfter.mK = 0;
  9008. continue;
  9009. }
  9010. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  9011. betaK = pointAfter.mK / pointCurrent.deltaK;
  9012. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  9013. if (squaredMagnitude <= 9) {
  9014. continue;
  9015. }
  9016. tauK = 3 / Math.sqrt(squaredMagnitude);
  9017. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  9018. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  9019. }
  9020. // Compute control points
  9021. var deltaX;
  9022. for (i = 0; i < pointsLen; ++i) {
  9023. pointCurrent = pointsWithTangents[i];
  9024. if (pointCurrent.model.skip) {
  9025. continue;
  9026. }
  9027. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  9028. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  9029. if (pointBefore && !pointBefore.model.skip) {
  9030. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  9031. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  9032. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  9033. }
  9034. if (pointAfter && !pointAfter.model.skip) {
  9035. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  9036. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  9037. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  9038. }
  9039. }
  9040. };
  9041. helpers$1.nextItem = function(collection, index, loop) {
  9042. if (loop) {
  9043. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  9044. }
  9045. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  9046. };
  9047. helpers$1.previousItem = function(collection, index, loop) {
  9048. if (loop) {
  9049. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  9050. }
  9051. return index <= 0 ? collection[0] : collection[index - 1];
  9052. };
  9053. // Implementation of the nice number algorithm used in determining where axis labels will go
  9054. helpers$1.niceNum = function(range, round) {
  9055. var exponent = Math.floor(helpers$1.log10(range));
  9056. var fraction = range / Math.pow(10, exponent);
  9057. var niceFraction;
  9058. if (round) {
  9059. if (fraction < 1.5) {
  9060. niceFraction = 1;
  9061. } else if (fraction < 3) {
  9062. niceFraction = 2;
  9063. } else if (fraction < 7) {
  9064. niceFraction = 5;
  9065. } else {
  9066. niceFraction = 10;
  9067. }
  9068. } else if (fraction <= 1.0) {
  9069. niceFraction = 1;
  9070. } else if (fraction <= 2) {
  9071. niceFraction = 2;
  9072. } else if (fraction <= 5) {
  9073. niceFraction = 5;
  9074. } else {
  9075. niceFraction = 10;
  9076. }
  9077. return niceFraction * Math.pow(10, exponent);
  9078. };
  9079. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  9080. helpers$1.requestAnimFrame = (function() {
  9081. if (typeof window === 'undefined') {
  9082. return function(callback) {
  9083. callback();
  9084. };
  9085. }
  9086. return window.requestAnimationFrame ||
  9087. window.webkitRequestAnimationFrame ||
  9088. window.mozRequestAnimationFrame ||
  9089. window.oRequestAnimationFrame ||
  9090. window.msRequestAnimationFrame ||
  9091. function(callback) {
  9092. return window.setTimeout(callback, 1000 / 60);
  9093. };
  9094. }());
  9095. // -- DOM methods
  9096. helpers$1.getRelativePosition = function(evt, chart) {
  9097. var mouseX, mouseY;
  9098. var e = evt.originalEvent || evt;
  9099. var canvas = evt.target || evt.srcElement;
  9100. var boundingRect = canvas.getBoundingClientRect();
  9101. var touches = e.touches;
  9102. if (touches && touches.length > 0) {
  9103. mouseX = touches[0].clientX;
  9104. mouseY = touches[0].clientY;
  9105. } else {
  9106. mouseX = e.clientX;
  9107. mouseY = e.clientY;
  9108. }
  9109. // Scale mouse coordinates into canvas coordinates
  9110. // by following the pattern laid out by 'jerryj' in the comments of
  9111. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  9112. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  9113. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  9114. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  9115. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  9116. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  9117. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  9118. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  9119. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  9120. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  9121. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  9122. return {
  9123. x: mouseX,
  9124. y: mouseY
  9125. };
  9126. };
  9127. // Private helper function to convert max-width/max-height values that may be percentages into a number
  9128. function parseMaxStyle(styleValue, node, parentProperty) {
  9129. var valueInPixels;
  9130. if (typeof styleValue === 'string') {
  9131. valueInPixels = parseInt(styleValue, 10);
  9132. if (styleValue.indexOf('%') !== -1) {
  9133. // percentage * size in dimension
  9134. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  9135. }
  9136. } else {
  9137. valueInPixels = styleValue;
  9138. }
  9139. return valueInPixels;
  9140. }
  9141. /**
  9142. * Returns if the given value contains an effective constraint.
  9143. * @private
  9144. */
  9145. function isConstrainedValue(value) {
  9146. return value !== undefined && value !== null && value !== 'none';
  9147. }
  9148. /**
  9149. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  9150. * @param {HTMLElement} domNode - the node to check the constraint on
  9151. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  9152. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  9153. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  9154. */
  9155. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  9156. var view = document.defaultView;
  9157. var parentNode = helpers$1._getParentNode(domNode);
  9158. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  9159. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  9160. var hasCNode = isConstrainedValue(constrainedNode);
  9161. var hasCContainer = isConstrainedValue(constrainedContainer);
  9162. var infinity = Number.POSITIVE_INFINITY;
  9163. if (hasCNode || hasCContainer) {
  9164. return Math.min(
  9165. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  9166. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  9167. }
  9168. return 'none';
  9169. }
  9170. // returns Number or undefined if no constraint
  9171. helpers$1.getConstraintWidth = function(domNode) {
  9172. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  9173. };
  9174. // returns Number or undefined if no constraint
  9175. helpers$1.getConstraintHeight = function(domNode) {
  9176. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  9177. };
  9178. /**
  9179. * @private
  9180. */
  9181. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  9182. padding = helpers$1.getStyle(container, padding);
  9183. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  9184. };
  9185. /**
  9186. * @private
  9187. */
  9188. helpers$1._getParentNode = function(domNode) {
  9189. var parent = domNode.parentNode;
  9190. if (parent && parent.toString() === '[object ShadowRoot]') {
  9191. parent = parent.host;
  9192. }
  9193. return parent;
  9194. };
  9195. helpers$1.getMaximumWidth = function(domNode) {
  9196. var container = helpers$1._getParentNode(domNode);
  9197. if (!container) {
  9198. return domNode.clientWidth;
  9199. }
  9200. var clientWidth = container.clientWidth;
  9201. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  9202. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  9203. var w = clientWidth - paddingLeft - paddingRight;
  9204. var cw = helpers$1.getConstraintWidth(domNode);
  9205. return isNaN(cw) ? w : Math.min(w, cw);
  9206. };
  9207. helpers$1.getMaximumHeight = function(domNode) {
  9208. var container = helpers$1._getParentNode(domNode);
  9209. if (!container) {
  9210. return domNode.clientHeight;
  9211. }
  9212. var clientHeight = container.clientHeight;
  9213. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  9214. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  9215. var h = clientHeight - paddingTop - paddingBottom;
  9216. var ch = helpers$1.getConstraintHeight(domNode);
  9217. return isNaN(ch) ? h : Math.min(h, ch);
  9218. };
  9219. helpers$1.getStyle = function(el, property) {
  9220. return el.currentStyle ?
  9221. el.currentStyle[property] :
  9222. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  9223. };
  9224. helpers$1.retinaScale = function(chart, forceRatio) {
  9225. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  9226. if (pixelRatio === 1) {
  9227. return;
  9228. }
  9229. var canvas = chart.canvas;
  9230. var height = chart.height;
  9231. var width = chart.width;
  9232. canvas.height = height * pixelRatio;
  9233. canvas.width = width * pixelRatio;
  9234. chart.ctx.scale(pixelRatio, pixelRatio);
  9235. // If no style has been set on the canvas, the render size is used as display size,
  9236. // making the chart visually bigger, so let's enforce it to the "correct" values.
  9237. // See https://github.com/chartjs/Chart.js/issues/3575
  9238. if (!canvas.style.height && !canvas.style.width) {
  9239. canvas.style.height = height + 'px';
  9240. canvas.style.width = width + 'px';
  9241. }
  9242. };
  9243. // -- Canvas methods
  9244. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  9245. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  9246. };
  9247. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  9248. cache = cache || {};
  9249. var data = cache.data = cache.data || {};
  9250. var gc = cache.garbageCollect = cache.garbageCollect || [];
  9251. if (cache.font !== font) {
  9252. data = cache.data = {};
  9253. gc = cache.garbageCollect = [];
  9254. cache.font = font;
  9255. }
  9256. ctx.font = font;
  9257. var longest = 0;
  9258. var ilen = arrayOfThings.length;
  9259. var i, j, jlen, thing, nestedThing;
  9260. for (i = 0; i < ilen; i++) {
  9261. thing = arrayOfThings[i];
  9262. // Undefined strings and arrays should not be measured
  9263. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  9264. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  9265. } else if (helpers$1.isArray(thing)) {
  9266. // if it is an array lets measure each element
  9267. // to do maybe simplify this function a bit so we can do this more recursively?
  9268. for (j = 0, jlen = thing.length; j < jlen; j++) {
  9269. nestedThing = thing[j];
  9270. // Undefined strings and arrays should not be measured
  9271. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  9272. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  9273. }
  9274. }
  9275. }
  9276. }
  9277. var gcLen = gc.length / 2;
  9278. if (gcLen > arrayOfThings.length) {
  9279. for (i = 0; i < gcLen; i++) {
  9280. delete data[gc[i]];
  9281. }
  9282. gc.splice(0, gcLen);
  9283. }
  9284. return longest;
  9285. };
  9286. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  9287. var textWidth = data[string];
  9288. if (!textWidth) {
  9289. textWidth = data[string] = ctx.measureText(string).width;
  9290. gc.push(string);
  9291. }
  9292. if (textWidth > longest) {
  9293. longest = textWidth;
  9294. }
  9295. return longest;
  9296. };
  9297. /**
  9298. * @deprecated
  9299. */
  9300. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  9301. var numberOfLines = 1;
  9302. helpers$1.each(arrayOfThings, function(thing) {
  9303. if (helpers$1.isArray(thing)) {
  9304. if (thing.length > numberOfLines) {
  9305. numberOfLines = thing.length;
  9306. }
  9307. }
  9308. });
  9309. return numberOfLines;
  9310. };
  9311. helpers$1.color = !chartjsColor ?
  9312. function(value) {
  9313. console.error('Color.js not found!');
  9314. return value;
  9315. } :
  9316. function(value) {
  9317. /* global CanvasGradient */
  9318. if (value instanceof CanvasGradient) {
  9319. value = core_defaults.global.defaultColor;
  9320. }
  9321. return chartjsColor(value);
  9322. };
  9323. helpers$1.getHoverColor = function(colorValue) {
  9324. /* global CanvasPattern */
  9325. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  9326. colorValue :
  9327. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  9328. };
  9329. };
  9330. function abstract() {
  9331. throw new Error(
  9332. 'This method is not implemented: either no adapter can ' +
  9333. 'be found or an incomplete integration was provided.'
  9334. );
  9335. }
  9336. /**
  9337. * Date adapter (current used by the time scale)
  9338. * @namespace Chart._adapters._date
  9339. * @memberof Chart._adapters
  9340. * @private
  9341. */
  9342. /**
  9343. * Currently supported unit string values.
  9344. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  9345. * @memberof Chart._adapters._date
  9346. * @name Unit
  9347. */
  9348. /**
  9349. * @class
  9350. */
  9351. function DateAdapter(options) {
  9352. this.options = options || {};
  9353. }
  9354. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  9355. /**
  9356. * Returns a map of time formats for the supported formatting units defined
  9357. * in Unit as well as 'datetime' representing a detailed date/time string.
  9358. * @returns {{string: string}}
  9359. */
  9360. formats: abstract,
  9361. /**
  9362. * Parses the given `value` and return the associated timestamp.
  9363. * @param {any} value - the value to parse (usually comes from the data)
  9364. * @param {string} [format] - the expected data format
  9365. * @returns {(number|null)}
  9366. * @function
  9367. */
  9368. parse: abstract,
  9369. /**
  9370. * Returns the formatted date in the specified `format` for a given `timestamp`.
  9371. * @param {number} timestamp - the timestamp to format
  9372. * @param {string} format - the date/time token
  9373. * @return {string}
  9374. * @function
  9375. */
  9376. format: abstract,
  9377. /**
  9378. * Adds the specified `amount` of `unit` to the given `timestamp`.
  9379. * @param {number} timestamp - the input timestamp
  9380. * @param {number} amount - the amount to add
  9381. * @param {Unit} unit - the unit as string
  9382. * @return {number}
  9383. * @function
  9384. */
  9385. add: abstract,
  9386. /**
  9387. * Returns the number of `unit` between the given timestamps.
  9388. * @param {number} max - the input timestamp (reference)
  9389. * @param {number} min - the timestamp to substract
  9390. * @param {Unit} unit - the unit as string
  9391. * @return {number}
  9392. * @function
  9393. */
  9394. diff: abstract,
  9395. /**
  9396. * Returns start of `unit` for the given `timestamp`.
  9397. * @param {number} timestamp - the input timestamp
  9398. * @param {Unit} unit - the unit as string
  9399. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  9400. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  9401. * @function
  9402. */
  9403. startOf: abstract,
  9404. /**
  9405. * Returns end of `unit` for the given `timestamp`.
  9406. * @param {number} timestamp - the input timestamp
  9407. * @param {Unit} unit - the unit as string
  9408. * @function
  9409. */
  9410. endOf: abstract,
  9411. // DEPRECATIONS
  9412. /**
  9413. * Provided for backward compatibility for scale.getValueForPixel(),
  9414. * this method should be overridden only by the moment adapter.
  9415. * @deprecated since version 2.8.0
  9416. * @todo remove at version 3
  9417. * @private
  9418. */
  9419. _create: function(value) {
  9420. return value;
  9421. }
  9422. });
  9423. DateAdapter.override = function(members) {
  9424. helpers$1.extend(DateAdapter.prototype, members);
  9425. };
  9426. var _date = DateAdapter;
  9427. var core_adapters = {
  9428. _date: _date
  9429. };
  9430. /**
  9431. * Namespace to hold static tick generation functions
  9432. * @namespace Chart.Ticks
  9433. */
  9434. var core_ticks = {
  9435. /**
  9436. * Namespace to hold formatters for different types of ticks
  9437. * @namespace Chart.Ticks.formatters
  9438. */
  9439. formatters: {
  9440. /**
  9441. * Formatter for value labels
  9442. * @method Chart.Ticks.formatters.values
  9443. * @param value the value to display
  9444. * @return {string|string[]} the label to display
  9445. */
  9446. values: function(value) {
  9447. return helpers$1.isArray(value) ? value : '' + value;
  9448. },
  9449. /**
  9450. * Formatter for linear numeric ticks
  9451. * @method Chart.Ticks.formatters.linear
  9452. * @param tickValue {number} the value to be formatted
  9453. * @param index {number} the position of the tickValue parameter in the ticks array
  9454. * @param ticks {number[]} the list of ticks being converted
  9455. * @return {string} string representation of the tickValue parameter
  9456. */
  9457. linear: function(tickValue, index, ticks) {
  9458. // If we have lots of ticks, don't use the ones
  9459. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  9460. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  9461. if (Math.abs(delta) > 1) {
  9462. if (tickValue !== Math.floor(tickValue)) {
  9463. // not an integer
  9464. delta = tickValue - Math.floor(tickValue);
  9465. }
  9466. }
  9467. var logDelta = helpers$1.log10(Math.abs(delta));
  9468. var tickString = '';
  9469. if (tickValue !== 0) {
  9470. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  9471. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  9472. var logTick = helpers$1.log10(Math.abs(tickValue));
  9473. var numExponential = Math.floor(logTick) - Math.floor(logDelta);
  9474. numExponential = Math.max(Math.min(numExponential, 20), 0);
  9475. tickString = tickValue.toExponential(numExponential);
  9476. } else {
  9477. var numDecimal = -1 * Math.floor(logDelta);
  9478. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  9479. tickString = tickValue.toFixed(numDecimal);
  9480. }
  9481. } else {
  9482. tickString = '0'; // never show decimal places for 0
  9483. }
  9484. return tickString;
  9485. },
  9486. logarithmic: function(tickValue, index, ticks) {
  9487. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  9488. if (tickValue === 0) {
  9489. return '0';
  9490. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  9491. return tickValue.toExponential();
  9492. }
  9493. return '';
  9494. }
  9495. }
  9496. };
  9497. var isArray = helpers$1.isArray;
  9498. var isNullOrUndef = helpers$1.isNullOrUndef;
  9499. var valueOrDefault$a = helpers$1.valueOrDefault;
  9500. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  9501. core_defaults._set('scale', {
  9502. display: true,
  9503. position: 'left',
  9504. offset: false,
  9505. // grid line settings
  9506. gridLines: {
  9507. display: true,
  9508. color: 'rgba(0,0,0,0.1)',
  9509. lineWidth: 1,
  9510. drawBorder: true,
  9511. drawOnChartArea: true,
  9512. drawTicks: true,
  9513. tickMarkLength: 10,
  9514. zeroLineWidth: 1,
  9515. zeroLineColor: 'rgba(0,0,0,0.25)',
  9516. zeroLineBorderDash: [],
  9517. zeroLineBorderDashOffset: 0.0,
  9518. offsetGridLines: false,
  9519. borderDash: [],
  9520. borderDashOffset: 0.0
  9521. },
  9522. // scale label
  9523. scaleLabel: {
  9524. // display property
  9525. display: false,
  9526. // actual label
  9527. labelString: '',
  9528. // top/bottom padding
  9529. padding: {
  9530. top: 4,
  9531. bottom: 4
  9532. }
  9533. },
  9534. // label settings
  9535. ticks: {
  9536. beginAtZero: false,
  9537. minRotation: 0,
  9538. maxRotation: 50,
  9539. mirror: false,
  9540. padding: 0,
  9541. reverse: false,
  9542. display: true,
  9543. autoSkip: true,
  9544. autoSkipPadding: 0,
  9545. labelOffset: 0,
  9546. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  9547. callback: core_ticks.formatters.values,
  9548. minor: {},
  9549. major: {}
  9550. }
  9551. });
  9552. /** Returns a new array containing numItems from arr */
  9553. function sample(arr, numItems) {
  9554. var result = [];
  9555. var increment = arr.length / numItems;
  9556. var i = 0;
  9557. var len = arr.length;
  9558. for (; i < len; i += increment) {
  9559. result.push(arr[Math.floor(i)]);
  9560. }
  9561. return result;
  9562. }
  9563. function getPixelForGridLine(scale, index, offsetGridLines) {
  9564. var length = scale.getTicks().length;
  9565. var validIndex = Math.min(index, length - 1);
  9566. var lineValue = scale.getPixelForTick(validIndex);
  9567. var start = scale._startPixel;
  9568. var end = scale._endPixel;
  9569. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  9570. var offset;
  9571. if (offsetGridLines) {
  9572. if (length === 1) {
  9573. offset = Math.max(lineValue - start, end - lineValue);
  9574. } else if (index === 0) {
  9575. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  9576. } else {
  9577. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  9578. }
  9579. lineValue += validIndex < index ? offset : -offset;
  9580. // Return undefined if the pixel is out of the range
  9581. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  9582. return;
  9583. }
  9584. }
  9585. return lineValue;
  9586. }
  9587. function garbageCollect(caches, length) {
  9588. helpers$1.each(caches, function(cache) {
  9589. var gc = cache.gc;
  9590. var gcLen = gc.length / 2;
  9591. var i;
  9592. if (gcLen > length) {
  9593. for (i = 0; i < gcLen; ++i) {
  9594. delete cache.data[gc[i]];
  9595. }
  9596. gc.splice(0, gcLen);
  9597. }
  9598. });
  9599. }
  9600. /**
  9601. * Returns {width, height, offset} objects for the first, last, widest, highest tick
  9602. * labels where offset indicates the anchor point offset from the top in pixels.
  9603. */
  9604. function computeLabelSizes(ctx, tickFonts, ticks, caches) {
  9605. var length = ticks.length;
  9606. var widths = [];
  9607. var heights = [];
  9608. var offsets = [];
  9609. var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
  9610. for (i = 0; i < length; ++i) {
  9611. label = ticks[i].label;
  9612. tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
  9613. ctx.font = fontString = tickFont.string;
  9614. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  9615. lineHeight = tickFont.lineHeight;
  9616. width = height = 0;
  9617. // Undefined labels and arrays should not be measured
  9618. if (!isNullOrUndef(label) && !isArray(label)) {
  9619. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);
  9620. height = lineHeight;
  9621. } else if (isArray(label)) {
  9622. // if it is an array let's measure each element
  9623. for (j = 0, jlen = label.length; j < jlen; ++j) {
  9624. nestedLabel = label[j];
  9625. // Undefined labels and arrays should not be measured
  9626. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  9627. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  9628. height += lineHeight;
  9629. }
  9630. }
  9631. }
  9632. widths.push(width);
  9633. heights.push(height);
  9634. offsets.push(lineHeight / 2);
  9635. }
  9636. garbageCollect(caches, length);
  9637. widest = widths.indexOf(Math.max.apply(null, widths));
  9638. highest = heights.indexOf(Math.max.apply(null, heights));
  9639. function valueAt(idx) {
  9640. return {
  9641. width: widths[idx] || 0,
  9642. height: heights[idx] || 0,
  9643. offset: offsets[idx] || 0
  9644. };
  9645. }
  9646. return {
  9647. first: valueAt(0),
  9648. last: valueAt(length - 1),
  9649. widest: valueAt(widest),
  9650. highest: valueAt(highest)
  9651. };
  9652. }
  9653. function getTickMarkLength(options) {
  9654. return options.drawTicks ? options.tickMarkLength : 0;
  9655. }
  9656. function getScaleLabelHeight(options) {
  9657. var font, padding;
  9658. if (!options.display) {
  9659. return 0;
  9660. }
  9661. font = helpers$1.options._parseFont(options);
  9662. padding = helpers$1.options.toPadding(options.padding);
  9663. return font.lineHeight + padding.height;
  9664. }
  9665. function parseFontOptions(options, nestedOpts) {
  9666. return helpers$1.extend(helpers$1.options._parseFont({
  9667. fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),
  9668. fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),
  9669. fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),
  9670. lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)
  9671. }), {
  9672. color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])
  9673. });
  9674. }
  9675. function parseTickFontOptions(options) {
  9676. var minor = parseFontOptions(options, options.minor);
  9677. var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
  9678. return {minor: minor, major: major};
  9679. }
  9680. function nonSkipped(ticksToFilter) {
  9681. var filtered = [];
  9682. var item, index, len;
  9683. for (index = 0, len = ticksToFilter.length; index < len; ++index) {
  9684. item = ticksToFilter[index];
  9685. if (typeof item._index !== 'undefined') {
  9686. filtered.push(item);
  9687. }
  9688. }
  9689. return filtered;
  9690. }
  9691. function getEvenSpacing(arr) {
  9692. var len = arr.length;
  9693. var i, diff;
  9694. if (len < 2) {
  9695. return false;
  9696. }
  9697. for (diff = arr[0], i = 1; i < len; ++i) {
  9698. if (arr[i] - arr[i - 1] !== diff) {
  9699. return false;
  9700. }
  9701. }
  9702. return diff;
  9703. }
  9704. function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
  9705. var evenMajorSpacing = getEvenSpacing(majorIndices);
  9706. var spacing = (ticks.length - 1) / ticksLimit;
  9707. var factors, factor, i, ilen;
  9708. // If the major ticks are evenly spaced apart, place the minor ticks
  9709. // so that they divide the major ticks into even chunks
  9710. if (!evenMajorSpacing) {
  9711. return Math.max(spacing, 1);
  9712. }
  9713. factors = helpers$1.math._factorize(evenMajorSpacing);
  9714. for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
  9715. factor = factors[i];
  9716. if (factor > spacing) {
  9717. return factor;
  9718. }
  9719. }
  9720. return Math.max(spacing, 1);
  9721. }
  9722. function getMajorIndices(ticks) {
  9723. var result = [];
  9724. var i, ilen;
  9725. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  9726. if (ticks[i].major) {
  9727. result.push(i);
  9728. }
  9729. }
  9730. return result;
  9731. }
  9732. function skipMajors(ticks, majorIndices, spacing) {
  9733. var count = 0;
  9734. var next = majorIndices[0];
  9735. var i, tick;
  9736. spacing = Math.ceil(spacing);
  9737. for (i = 0; i < ticks.length; i++) {
  9738. tick = ticks[i];
  9739. if (i === next) {
  9740. tick._index = i;
  9741. count++;
  9742. next = majorIndices[count * spacing];
  9743. } else {
  9744. delete tick.label;
  9745. }
  9746. }
  9747. }
  9748. function skip(ticks, spacing, majorStart, majorEnd) {
  9749. var start = valueOrDefault$a(majorStart, 0);
  9750. var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);
  9751. var count = 0;
  9752. var length, i, tick, next;
  9753. spacing = Math.ceil(spacing);
  9754. if (majorEnd) {
  9755. length = majorEnd - majorStart;
  9756. spacing = length / Math.floor(length / spacing);
  9757. }
  9758. next = start;
  9759. while (next < 0) {
  9760. count++;
  9761. next = Math.round(start + count * spacing);
  9762. }
  9763. for (i = Math.max(start, 0); i < end; i++) {
  9764. tick = ticks[i];
  9765. if (i === next) {
  9766. tick._index = i;
  9767. count++;
  9768. next = Math.round(start + count * spacing);
  9769. } else {
  9770. delete tick.label;
  9771. }
  9772. }
  9773. }
  9774. var Scale = core_element.extend({
  9775. zeroLineIndex: 0,
  9776. /**
  9777. * Get the padding needed for the scale
  9778. * @method getPadding
  9779. * @private
  9780. * @returns {Padding} the necessary padding
  9781. */
  9782. getPadding: function() {
  9783. var me = this;
  9784. return {
  9785. left: me.paddingLeft || 0,
  9786. top: me.paddingTop || 0,
  9787. right: me.paddingRight || 0,
  9788. bottom: me.paddingBottom || 0
  9789. };
  9790. },
  9791. /**
  9792. * Returns the scale tick objects ({label, major})
  9793. * @since 2.7
  9794. */
  9795. getTicks: function() {
  9796. return this._ticks;
  9797. },
  9798. /**
  9799. * @private
  9800. */
  9801. _getLabels: function() {
  9802. var data = this.chart.data;
  9803. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  9804. },
  9805. // These methods are ordered by lifecyle. Utilities then follow.
  9806. // Any function defined here is inherited by all scale types.
  9807. // Any function can be extended by the scale type
  9808. /**
  9809. * Provided for backward compatibility, not available anymore
  9810. * @function Chart.Scale.mergeTicksOptions
  9811. * @deprecated since version 2.8.0
  9812. * @todo remove at version 3
  9813. */
  9814. mergeTicksOptions: function() {
  9815. // noop
  9816. },
  9817. beforeUpdate: function() {
  9818. helpers$1.callback(this.options.beforeUpdate, [this]);
  9819. },
  9820. /**
  9821. * @param {number} maxWidth - the max width in pixels
  9822. * @param {number} maxHeight - the max height in pixels
  9823. * @param {object} margins - the space between the edge of the other scales and edge of the chart
  9824. * This space comes from two sources:
  9825. * - padding - space that's required to show the labels at the edges of the scale
  9826. * - thickness of scales or legends in another orientation
  9827. */
  9828. update: function(maxWidth, maxHeight, margins) {
  9829. var me = this;
  9830. var tickOpts = me.options.ticks;
  9831. var sampleSize = tickOpts.sampleSize;
  9832. var i, ilen, labels, ticks, samplingEnabled;
  9833. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  9834. me.beforeUpdate();
  9835. // Absorb the master measurements
  9836. me.maxWidth = maxWidth;
  9837. me.maxHeight = maxHeight;
  9838. me.margins = helpers$1.extend({
  9839. left: 0,
  9840. right: 0,
  9841. top: 0,
  9842. bottom: 0
  9843. }, margins);
  9844. me._ticks = null;
  9845. me.ticks = null;
  9846. me._labelSizes = null;
  9847. me._maxLabelLines = 0;
  9848. me.longestLabelWidth = 0;
  9849. me.longestTextCache = me.longestTextCache || {};
  9850. me._gridLineItems = null;
  9851. me._labelItems = null;
  9852. // Dimensions
  9853. me.beforeSetDimensions();
  9854. me.setDimensions();
  9855. me.afterSetDimensions();
  9856. // Data min/max
  9857. me.beforeDataLimits();
  9858. me.determineDataLimits();
  9859. me.afterDataLimits();
  9860. // Ticks - `this.ticks` is now DEPRECATED!
  9861. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  9862. // and must not be accessed directly from outside this class. `this.ticks` being
  9863. // around for long time and not marked as private, we can't change its structure
  9864. // without unexpected breaking changes. If you need to access the scale ticks,
  9865. // use scale.getTicks() instead.
  9866. me.beforeBuildTicks();
  9867. // New implementations should return an array of objects but for BACKWARD COMPAT,
  9868. // we still support no return (`this.ticks` internally set by calling this method).
  9869. ticks = me.buildTicks() || [];
  9870. // Allow modification of ticks in callback.
  9871. ticks = me.afterBuildTicks(ticks) || ticks;
  9872. // Ensure ticks contains ticks in new tick format
  9873. if ((!ticks || !ticks.length) && me.ticks) {
  9874. ticks = [];
  9875. for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
  9876. ticks.push({
  9877. value: me.ticks[i],
  9878. major: false
  9879. });
  9880. }
  9881. }
  9882. me._ticks = ticks;
  9883. // Compute tick rotation and fit using a sampled subset of labels
  9884. // We generally don't need to compute the size of every single label for determining scale size
  9885. samplingEnabled = sampleSize < ticks.length;
  9886. labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);
  9887. // _configure is called twice, once here, once from core.controller.updateLayout.
  9888. // Here we haven't been positioned yet, but dimensions are correct.
  9889. // Variables set in _configure are needed for calculateTickRotation, and
  9890. // it's ok that coordinates are not correct there, only dimensions matter.
  9891. me._configure();
  9892. // Tick Rotation
  9893. me.beforeCalculateTickRotation();
  9894. me.calculateTickRotation();
  9895. me.afterCalculateTickRotation();
  9896. me.beforeFit();
  9897. me.fit();
  9898. me.afterFit();
  9899. // Auto-skip
  9900. me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;
  9901. if (samplingEnabled) {
  9902. // Generate labels using all non-skipped ticks
  9903. labels = me._convertTicksToLabels(me._ticksToDraw);
  9904. }
  9905. me.ticks = labels; // BACKWARD COMPATIBILITY
  9906. // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
  9907. me.afterUpdate();
  9908. // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
  9909. // make maxWidth and maxHeight private
  9910. return me.minSize;
  9911. },
  9912. /**
  9913. * @private
  9914. */
  9915. _configure: function() {
  9916. var me = this;
  9917. var reversePixels = me.options.ticks.reverse;
  9918. var startPixel, endPixel;
  9919. if (me.isHorizontal()) {
  9920. startPixel = me.left;
  9921. endPixel = me.right;
  9922. } else {
  9923. startPixel = me.top;
  9924. endPixel = me.bottom;
  9925. // by default vertical scales are from bottom to top, so pixels are reversed
  9926. reversePixels = !reversePixels;
  9927. }
  9928. me._startPixel = startPixel;
  9929. me._endPixel = endPixel;
  9930. me._reversePixels = reversePixels;
  9931. me._length = endPixel - startPixel;
  9932. },
  9933. afterUpdate: function() {
  9934. helpers$1.callback(this.options.afterUpdate, [this]);
  9935. },
  9936. //
  9937. beforeSetDimensions: function() {
  9938. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  9939. },
  9940. setDimensions: function() {
  9941. var me = this;
  9942. // Set the unconstrained dimension before label rotation
  9943. if (me.isHorizontal()) {
  9944. // Reset position before calculating rotation
  9945. me.width = me.maxWidth;
  9946. me.left = 0;
  9947. me.right = me.width;
  9948. } else {
  9949. me.height = me.maxHeight;
  9950. // Reset position before calculating rotation
  9951. me.top = 0;
  9952. me.bottom = me.height;
  9953. }
  9954. // Reset padding
  9955. me.paddingLeft = 0;
  9956. me.paddingTop = 0;
  9957. me.paddingRight = 0;
  9958. me.paddingBottom = 0;
  9959. },
  9960. afterSetDimensions: function() {
  9961. helpers$1.callback(this.options.afterSetDimensions, [this]);
  9962. },
  9963. // Data limits
  9964. beforeDataLimits: function() {
  9965. helpers$1.callback(this.options.beforeDataLimits, [this]);
  9966. },
  9967. determineDataLimits: helpers$1.noop,
  9968. afterDataLimits: function() {
  9969. helpers$1.callback(this.options.afterDataLimits, [this]);
  9970. },
  9971. //
  9972. beforeBuildTicks: function() {
  9973. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  9974. },
  9975. buildTicks: helpers$1.noop,
  9976. afterBuildTicks: function(ticks) {
  9977. var me = this;
  9978. // ticks is empty for old axis implementations here
  9979. if (isArray(ticks) && ticks.length) {
  9980. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  9981. }
  9982. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  9983. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  9984. return ticks;
  9985. },
  9986. beforeTickToLabelConversion: function() {
  9987. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  9988. },
  9989. convertTicksToLabels: function() {
  9990. var me = this;
  9991. // Convert ticks to strings
  9992. var tickOpts = me.options.ticks;
  9993. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  9994. },
  9995. afterTickToLabelConversion: function() {
  9996. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  9997. },
  9998. //
  9999. beforeCalculateTickRotation: function() {
  10000. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  10001. },
  10002. calculateTickRotation: function() {
  10003. var me = this;
  10004. var options = me.options;
  10005. var tickOpts = options.ticks;
  10006. var numTicks = me.getTicks().length;
  10007. var minRotation = tickOpts.minRotation || 0;
  10008. var maxRotation = tickOpts.maxRotation;
  10009. var labelRotation = minRotation;
  10010. var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
  10011. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  10012. me.labelRotation = minRotation;
  10013. return;
  10014. }
  10015. labelSizes = me._getLabelSizes();
  10016. maxLabelWidth = labelSizes.widest.width;
  10017. maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
  10018. // Estimate the width of each grid based on the canvas width, the maximum
  10019. // label width and the number of tick intervals
  10020. maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
  10021. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  10022. // Allow 3 pixels x2 padding either side for label readability
  10023. if (maxLabelWidth + 6 > tickWidth) {
  10024. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  10025. maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
  10026. - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
  10027. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  10028. labelRotation = helpers$1.toDegrees(Math.min(
  10029. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  10030. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  10031. ));
  10032. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  10033. }
  10034. me.labelRotation = labelRotation;
  10035. },
  10036. afterCalculateTickRotation: function() {
  10037. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  10038. },
  10039. //
  10040. beforeFit: function() {
  10041. helpers$1.callback(this.options.beforeFit, [this]);
  10042. },
  10043. fit: function() {
  10044. var me = this;
  10045. // Reset
  10046. var minSize = me.minSize = {
  10047. width: 0,
  10048. height: 0
  10049. };
  10050. var chart = me.chart;
  10051. var opts = me.options;
  10052. var tickOpts = opts.ticks;
  10053. var scaleLabelOpts = opts.scaleLabel;
  10054. var gridLineOpts = opts.gridLines;
  10055. var display = me._isVisible();
  10056. var isBottom = opts.position === 'bottom';
  10057. var isHorizontal = me.isHorizontal();
  10058. // Width
  10059. if (isHorizontal) {
  10060. minSize.width = me.maxWidth;
  10061. } else if (display) {
  10062. minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10063. }
  10064. // height
  10065. if (!isHorizontal) {
  10066. minSize.height = me.maxHeight; // fill all the height
  10067. } else if (display) {
  10068. minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10069. }
  10070. // Don't bother fitting the ticks if we are not showing the labels
  10071. if (tickOpts.display && display) {
  10072. var tickFonts = parseTickFontOptions(tickOpts);
  10073. var labelSizes = me._getLabelSizes();
  10074. var firstLabelSize = labelSizes.first;
  10075. var lastLabelSize = labelSizes.last;
  10076. var widestLabelSize = labelSizes.widest;
  10077. var highestLabelSize = labelSizes.highest;
  10078. var lineSpace = tickFonts.minor.lineHeight * 0.4;
  10079. var tickPadding = tickOpts.padding;
  10080. if (isHorizontal) {
  10081. // A horizontal axis is more constrained by the height.
  10082. var isRotated = me.labelRotation !== 0;
  10083. var angleRadians = helpers$1.toRadians(me.labelRotation);
  10084. var cosRotation = Math.cos(angleRadians);
  10085. var sinRotation = Math.sin(angleRadians);
  10086. var labelHeight = sinRotation * widestLabelSize.width
  10087. + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
  10088. + (isRotated ? 0 : lineSpace); // padding
  10089. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  10090. var offsetLeft = me.getPixelForTick(0) - me.left;
  10091. var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
  10092. var paddingLeft, paddingRight;
  10093. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  10094. // which means that the right padding is dominated by the font height
  10095. if (isRotated) {
  10096. paddingLeft = isBottom ?
  10097. cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
  10098. sinRotation * (firstLabelSize.height - firstLabelSize.offset);
  10099. paddingRight = isBottom ?
  10100. sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
  10101. cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
  10102. } else {
  10103. paddingLeft = firstLabelSize.width / 2;
  10104. paddingRight = lastLabelSize.width / 2;
  10105. }
  10106. // Adjust padding taking into account changes in offsets
  10107. // and add 3 px to move away from canvas edges
  10108. me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
  10109. me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
  10110. } else {
  10111. // A vertical axis is more constrained by the width. Labels are the
  10112. // dominant factor here, so get that length first and account for padding
  10113. var labelWidth = tickOpts.mirror ? 0 :
  10114. // use lineSpace for consistency with horizontal axis
  10115. // tickPadding is not implemented for horizontal
  10116. widestLabelSize.width + tickPadding + lineSpace;
  10117. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
  10118. me.paddingTop = firstLabelSize.height / 2;
  10119. me.paddingBottom = lastLabelSize.height / 2;
  10120. }
  10121. }
  10122. me.handleMargins();
  10123. if (isHorizontal) {
  10124. me.width = me._length = chart.width - me.margins.left - me.margins.right;
  10125. me.height = minSize.height;
  10126. } else {
  10127. me.width = minSize.width;
  10128. me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
  10129. }
  10130. },
  10131. /**
  10132. * Handle margins and padding interactions
  10133. * @private
  10134. */
  10135. handleMargins: function() {
  10136. var me = this;
  10137. if (me.margins) {
  10138. me.margins.left = Math.max(me.paddingLeft, me.margins.left);
  10139. me.margins.top = Math.max(me.paddingTop, me.margins.top);
  10140. me.margins.right = Math.max(me.paddingRight, me.margins.right);
  10141. me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
  10142. }
  10143. },
  10144. afterFit: function() {
  10145. helpers$1.callback(this.options.afterFit, [this]);
  10146. },
  10147. // Shared Methods
  10148. isHorizontal: function() {
  10149. var pos = this.options.position;
  10150. return pos === 'top' || pos === 'bottom';
  10151. },
  10152. isFullWidth: function() {
  10153. return this.options.fullWidth;
  10154. },
  10155. // 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
  10156. getRightValue: function(rawValue) {
  10157. // Null and undefined values first
  10158. if (isNullOrUndef(rawValue)) {
  10159. return NaN;
  10160. }
  10161. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  10162. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  10163. return NaN;
  10164. }
  10165. // If it is in fact an object, dive in one more level
  10166. if (rawValue) {
  10167. if (this.isHorizontal()) {
  10168. if (rawValue.x !== undefined) {
  10169. return this.getRightValue(rawValue.x);
  10170. }
  10171. } else if (rawValue.y !== undefined) {
  10172. return this.getRightValue(rawValue.y);
  10173. }
  10174. }
  10175. // Value is good, return it
  10176. return rawValue;
  10177. },
  10178. _convertTicksToLabels: function(ticks) {
  10179. var me = this;
  10180. var labels, i, ilen;
  10181. me.ticks = ticks.map(function(tick) {
  10182. return tick.value;
  10183. });
  10184. me.beforeTickToLabelConversion();
  10185. // New implementations should return the formatted tick labels but for BACKWARD
  10186. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  10187. // this method and supposed to contain only string values).
  10188. labels = me.convertTicksToLabels(ticks) || me.ticks;
  10189. me.afterTickToLabelConversion();
  10190. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  10191. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10192. ticks[i].label = labels[i];
  10193. }
  10194. return labels;
  10195. },
  10196. /**
  10197. * @private
  10198. */
  10199. _getLabelSizes: function() {
  10200. var me = this;
  10201. var labelSizes = me._labelSizes;
  10202. if (!labelSizes) {
  10203. me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
  10204. me.longestLabelWidth = labelSizes.widest.width;
  10205. }
  10206. return labelSizes;
  10207. },
  10208. /**
  10209. * @private
  10210. */
  10211. _parseValue: function(value) {
  10212. var start, end, min, max;
  10213. if (isArray(value)) {
  10214. start = +this.getRightValue(value[0]);
  10215. end = +this.getRightValue(value[1]);
  10216. min = Math.min(start, end);
  10217. max = Math.max(start, end);
  10218. } else {
  10219. value = +this.getRightValue(value);
  10220. start = undefined;
  10221. end = value;
  10222. min = value;
  10223. max = value;
  10224. }
  10225. return {
  10226. min: min,
  10227. max: max,
  10228. start: start,
  10229. end: end
  10230. };
  10231. },
  10232. /**
  10233. * @private
  10234. */
  10235. _getScaleLabel: function(rawValue) {
  10236. var v = this._parseValue(rawValue);
  10237. if (v.start !== undefined) {
  10238. return '[' + v.start + ', ' + v.end + ']';
  10239. }
  10240. return +this.getRightValue(rawValue);
  10241. },
  10242. /**
  10243. * Used to get the value to display in the tooltip for the data at the given index
  10244. * @param index
  10245. * @param datasetIndex
  10246. */
  10247. getLabelForIndex: helpers$1.noop,
  10248. /**
  10249. * Returns the location of the given data point. Value can either be an index or a numerical value
  10250. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10251. * @param value
  10252. * @param index
  10253. * @param datasetIndex
  10254. */
  10255. getPixelForValue: helpers$1.noop,
  10256. /**
  10257. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  10258. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10259. * @param pixel
  10260. */
  10261. getValueForPixel: helpers$1.noop,
  10262. /**
  10263. * Returns the location of the tick at the given index
  10264. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10265. */
  10266. getPixelForTick: function(index) {
  10267. var me = this;
  10268. var offset = me.options.offset;
  10269. var numTicks = me._ticks.length;
  10270. var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
  10271. return index < 0 || index > numTicks - 1
  10272. ? null
  10273. : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
  10274. },
  10275. /**
  10276. * Utility for getting the pixel location of a percentage of scale
  10277. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10278. */
  10279. getPixelForDecimal: function(decimal) {
  10280. var me = this;
  10281. if (me._reversePixels) {
  10282. decimal = 1 - decimal;
  10283. }
  10284. return me._startPixel + decimal * me._length;
  10285. },
  10286. getDecimalForPixel: function(pixel) {
  10287. var decimal = (pixel - this._startPixel) / this._length;
  10288. return this._reversePixels ? 1 - decimal : decimal;
  10289. },
  10290. /**
  10291. * Returns the pixel for the minimum chart value
  10292. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10293. */
  10294. getBasePixel: function() {
  10295. return this.getPixelForValue(this.getBaseValue());
  10296. },
  10297. getBaseValue: function() {
  10298. var me = this;
  10299. var min = me.min;
  10300. var max = me.max;
  10301. return me.beginAtZero ? 0 :
  10302. min < 0 && max < 0 ? max :
  10303. min > 0 && max > 0 ? min :
  10304. 0;
  10305. },
  10306. /**
  10307. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  10308. * @private
  10309. */
  10310. _autoSkip: function(ticks) {
  10311. var me = this;
  10312. var tickOpts = me.options.ticks;
  10313. var axisLength = me._length;
  10314. var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;
  10315. var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  10316. var numMajorIndices = majorIndices.length;
  10317. var first = majorIndices[0];
  10318. var last = majorIndices[numMajorIndices - 1];
  10319. var i, ilen, spacing, avgMajorSpacing;
  10320. // If there are too many major ticks to display them all
  10321. if (numMajorIndices > ticksLimit) {
  10322. skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);
  10323. return nonSkipped(ticks);
  10324. }
  10325. spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
  10326. if (numMajorIndices > 0) {
  10327. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  10328. skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);
  10329. }
  10330. avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;
  10331. skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  10332. skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  10333. return nonSkipped(ticks);
  10334. }
  10335. skip(ticks, spacing);
  10336. return nonSkipped(ticks);
  10337. },
  10338. /**
  10339. * @private
  10340. */
  10341. _tickSize: function() {
  10342. var me = this;
  10343. var optionTicks = me.options.ticks;
  10344. // Calculate space needed by label in axis direction.
  10345. var rot = helpers$1.toRadians(me.labelRotation);
  10346. var cos = Math.abs(Math.cos(rot));
  10347. var sin = Math.abs(Math.sin(rot));
  10348. var labelSizes = me._getLabelSizes();
  10349. var padding = optionTicks.autoSkipPadding || 0;
  10350. var w = labelSizes ? labelSizes.widest.width + padding : 0;
  10351. var h = labelSizes ? labelSizes.highest.height + padding : 0;
  10352. // Calculate space needed for 1 tick in axis direction.
  10353. return me.isHorizontal()
  10354. ? h * cos > w * sin ? w / cos : h / sin
  10355. : h * sin < w * cos ? h / cos : w / sin;
  10356. },
  10357. /**
  10358. * @private
  10359. */
  10360. _isVisible: function() {
  10361. var me = this;
  10362. var chart = me.chart;
  10363. var display = me.options.display;
  10364. var i, ilen, meta;
  10365. if (display !== 'auto') {
  10366. return !!display;
  10367. }
  10368. // When 'auto', the scale is visible if at least one associated dataset is visible.
  10369. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  10370. if (chart.isDatasetVisible(i)) {
  10371. meta = chart.getDatasetMeta(i);
  10372. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  10373. return true;
  10374. }
  10375. }
  10376. }
  10377. return false;
  10378. },
  10379. /**
  10380. * @private
  10381. */
  10382. _computeGridLineItems: function(chartArea) {
  10383. var me = this;
  10384. var chart = me.chart;
  10385. var options = me.options;
  10386. var gridLines = options.gridLines;
  10387. var position = options.position;
  10388. var offsetGridLines = gridLines.offsetGridLines;
  10389. var isHorizontal = me.isHorizontal();
  10390. var ticks = me._ticksToDraw;
  10391. var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
  10392. var tl = getTickMarkLength(gridLines);
  10393. var items = [];
  10394. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10395. var axisHalfWidth = axisWidth / 2;
  10396. var alignPixel = helpers$1._alignPixel;
  10397. var alignBorderValue = function(pixel) {
  10398. return alignPixel(chart, pixel, axisWidth);
  10399. };
  10400. var borderValue, i, tick, lineValue, alignedLineValue;
  10401. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
  10402. if (position === 'top') {
  10403. borderValue = alignBorderValue(me.bottom);
  10404. ty1 = me.bottom - tl;
  10405. ty2 = borderValue - axisHalfWidth;
  10406. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  10407. y2 = chartArea.bottom;
  10408. } else if (position === 'bottom') {
  10409. borderValue = alignBorderValue(me.top);
  10410. y1 = chartArea.top;
  10411. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  10412. ty1 = borderValue + axisHalfWidth;
  10413. ty2 = me.top + tl;
  10414. } else if (position === 'left') {
  10415. borderValue = alignBorderValue(me.right);
  10416. tx1 = me.right - tl;
  10417. tx2 = borderValue - axisHalfWidth;
  10418. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  10419. x2 = chartArea.right;
  10420. } else {
  10421. borderValue = alignBorderValue(me.left);
  10422. x1 = chartArea.left;
  10423. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  10424. tx1 = borderValue + axisHalfWidth;
  10425. tx2 = me.left + tl;
  10426. }
  10427. for (i = 0; i < ticksLength; ++i) {
  10428. tick = ticks[i] || {};
  10429. // autoskipper skipped this tick (#4635)
  10430. if (isNullOrUndef(tick.label) && i < ticks.length) {
  10431. continue;
  10432. }
  10433. if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
  10434. // Draw the first index specially
  10435. lineWidth = gridLines.zeroLineWidth;
  10436. lineColor = gridLines.zeroLineColor;
  10437. borderDash = gridLines.zeroLineBorderDash || [];
  10438. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  10439. } else {
  10440. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);
  10441. lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');
  10442. borderDash = gridLines.borderDash || [];
  10443. borderDashOffset = gridLines.borderDashOffset || 0.0;
  10444. }
  10445. lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
  10446. // Skip if the pixel is out of the range
  10447. if (lineValue === undefined) {
  10448. continue;
  10449. }
  10450. alignedLineValue = alignPixel(chart, lineValue, lineWidth);
  10451. if (isHorizontal) {
  10452. tx1 = tx2 = x1 = x2 = alignedLineValue;
  10453. } else {
  10454. ty1 = ty2 = y1 = y2 = alignedLineValue;
  10455. }
  10456. items.push({
  10457. tx1: tx1,
  10458. ty1: ty1,
  10459. tx2: tx2,
  10460. ty2: ty2,
  10461. x1: x1,
  10462. y1: y1,
  10463. x2: x2,
  10464. y2: y2,
  10465. width: lineWidth,
  10466. color: lineColor,
  10467. borderDash: borderDash,
  10468. borderDashOffset: borderDashOffset,
  10469. });
  10470. }
  10471. items.ticksLength = ticksLength;
  10472. items.borderValue = borderValue;
  10473. return items;
  10474. },
  10475. /**
  10476. * @private
  10477. */
  10478. _computeLabelItems: function() {
  10479. var me = this;
  10480. var options = me.options;
  10481. var optionTicks = options.ticks;
  10482. var position = options.position;
  10483. var isMirrored = optionTicks.mirror;
  10484. var isHorizontal = me.isHorizontal();
  10485. var ticks = me._ticksToDraw;
  10486. var fonts = parseTickFontOptions(optionTicks);
  10487. var tickPadding = optionTicks.padding;
  10488. var tl = getTickMarkLength(options.gridLines);
  10489. var rotation = -helpers$1.toRadians(me.labelRotation);
  10490. var items = [];
  10491. var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  10492. if (position === 'top') {
  10493. y = me.bottom - tl - tickPadding;
  10494. textAlign = !rotation ? 'center' : 'left';
  10495. } else if (position === 'bottom') {
  10496. y = me.top + tl + tickPadding;
  10497. textAlign = !rotation ? 'center' : 'right';
  10498. } else if (position === 'left') {
  10499. x = me.right - (isMirrored ? 0 : tl) - tickPadding;
  10500. textAlign = isMirrored ? 'left' : 'right';
  10501. } else {
  10502. x = me.left + (isMirrored ? 0 : tl) + tickPadding;
  10503. textAlign = isMirrored ? 'right' : 'left';
  10504. }
  10505. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10506. tick = ticks[i];
  10507. label = tick.label;
  10508. // autoskipper skipped this tick (#4635)
  10509. if (isNullOrUndef(label)) {
  10510. continue;
  10511. }
  10512. pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
  10513. font = tick.major ? fonts.major : fonts.minor;
  10514. lineHeight = font.lineHeight;
  10515. lineCount = isArray(label) ? label.length : 1;
  10516. if (isHorizontal) {
  10517. x = pixel;
  10518. textOffset = position === 'top'
  10519. ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight
  10520. : (!rotation ? 0.5 : 0) * lineHeight;
  10521. } else {
  10522. y = pixel;
  10523. textOffset = (1 - lineCount) * lineHeight / 2;
  10524. }
  10525. items.push({
  10526. x: x,
  10527. y: y,
  10528. rotation: rotation,
  10529. label: label,
  10530. font: font,
  10531. textOffset: textOffset,
  10532. textAlign: textAlign
  10533. });
  10534. }
  10535. return items;
  10536. },
  10537. /**
  10538. * @private
  10539. */
  10540. _drawGrid: function(chartArea) {
  10541. var me = this;
  10542. var gridLines = me.options.gridLines;
  10543. if (!gridLines.display) {
  10544. return;
  10545. }
  10546. var ctx = me.ctx;
  10547. var chart = me.chart;
  10548. var alignPixel = helpers$1._alignPixel;
  10549. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10550. var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  10551. var width, color, i, ilen, item;
  10552. let xtmp = 70;
  10553. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10554. item = items[i];
  10555. if (Math.abs(item.x1 - item.x2) > 0.1) {
  10556. xtmp = item.x1;
  10557. break;
  10558. }
  10559. }
  10560. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10561. item = items[i];
  10562. width = item.width;
  10563. color = item.color;
  10564. if (width && color) {
  10565. ctx.save();
  10566. ctx.lineWidth = width;
  10567. ctx.strokeStyle = color;
  10568. if (ctx.setLineDash) {
  10569. ctx.setLineDash(item.borderDash);
  10570. ctx.lineDashOffset = item.borderDashOffset;
  10571. }
  10572. ctx.beginPath();
  10573. if (gridLines.drawTicks) {
  10574. ctx.moveTo(item.tx1, item.ty1);
  10575. ctx.lineTo(item.tx2, item.ty2);
  10576. }
  10577. if (gridLines.drawOnChartArea) {
  10578. if (Math.abs(item.x1 - item.x2) < 0.1) {
  10579. item.x1 = xtmp;
  10580. item.x2 = xtmp;
  10581. }
  10582. ctx.moveTo(item.x1, item.y1);
  10583. ctx.lineTo(item.x2, item.y2);
  10584. }
  10585. ctx.stroke();
  10586. ctx.restore();
  10587. }
  10588. }
  10589. if (axisWidth) {
  10590. // Draw the line at the edge of the axis
  10591. var firstLineWidth = axisWidth;
  10592. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);
  10593. var borderValue = items.borderValue;
  10594. var x1, x2, y1, y2;
  10595. if (me.isHorizontal()) {
  10596. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  10597. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  10598. y1 = y2 = borderValue;
  10599. } else {
  10600. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  10601. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  10602. x1 = x2 = borderValue;
  10603. }
  10604. ctx.lineWidth = axisWidth;
  10605. ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  10606. ctx.beginPath();
  10607. ctx.moveTo(x1, y1);
  10608. ctx.lineTo(x2, y2);
  10609. ctx.stroke();
  10610. }
  10611. },
  10612. /**
  10613. * @private
  10614. */
  10615. _drawLabels: function() {
  10616. var me = this;
  10617. var optionTicks = me.options.ticks;
  10618. if (!optionTicks.display) {
  10619. return;
  10620. }
  10621. var ctx = me.ctx;
  10622. var items = me._labelItems || (me._labelItems = me._computeLabelItems());
  10623. var i, j, ilen, jlen, item, tickFont, label, y;
  10624. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10625. item = items[i];
  10626. tickFont = item.font;
  10627. // Make sure we draw text in the correct color and font
  10628. ctx.save();
  10629. ctx.translate(item.x, item.y);
  10630. ctx.rotate(item.rotation);
  10631. ctx.font = tickFont.string;
  10632. ctx.fillStyle = tickFont.color;
  10633. ctx.textBaseline = 'middle';
  10634. ctx.textAlign = item.textAlign;
  10635. label = item.label;
  10636. y = item.textOffset;
  10637. if (isArray(label)) {
  10638. for (j = 0, jlen = label.length; j < jlen; ++j) {
  10639. // We just make sure the multiline element is a string here..
  10640. ctx.fillText('' + label[j], 0, y);
  10641. y += tickFont.lineHeight;
  10642. }
  10643. } else {
  10644. ctx.fillText(label, 0, y);
  10645. }
  10646. ctx.restore();
  10647. }
  10648. },
  10649. /**
  10650. * @private
  10651. */
  10652. _drawTitle: function() {
  10653. var me = this;
  10654. var ctx = me.ctx;
  10655. var options = me.options;
  10656. var scaleLabel = options.scaleLabel;
  10657. if (!scaleLabel.display) {
  10658. return;
  10659. }
  10660. var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);
  10661. var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);
  10662. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  10663. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  10664. var position = options.position;
  10665. var rotation = 0;
  10666. var scaleLabelX, scaleLabelY;
  10667. if (me.isHorizontal()) {
  10668. scaleLabelX = me.left + me.width / 2; // midpoint of the width
  10669. scaleLabelY = position === 'bottom'
  10670. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  10671. : me.top + halfLineHeight + scaleLabelPadding.top;
  10672. } else {
  10673. var isLeft = position === 'left';
  10674. scaleLabelX = isLeft
  10675. ? me.left + halfLineHeight + scaleLabelPadding.top
  10676. : me.right - halfLineHeight - scaleLabelPadding.top;
  10677. scaleLabelY = me.top + me.height / 2;
  10678. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  10679. }
  10680. ctx.save();
  10681. ctx.translate(scaleLabelX, scaleLabelY);
  10682. ctx.rotate(rotation);
  10683. ctx.textAlign = 'center';
  10684. ctx.textBaseline = 'middle';
  10685. ctx.fillStyle = scaleLabelFontColor; // render in correct colour
  10686. ctx.font = scaleLabelFont.string;
  10687. ctx.fillText(scaleLabel.labelString, 0, 0);
  10688. ctx.restore();
  10689. },
  10690. draw: function(chartArea) {
  10691. var me = this;
  10692. if (!me._isVisible()) {
  10693. return;
  10694. }
  10695. me._drawGrid(chartArea);
  10696. me._drawTitle();
  10697. me._drawLabels();
  10698. },
  10699. /**
  10700. * @private
  10701. */
  10702. _layers: function() {
  10703. var me = this;
  10704. var opts = me.options;
  10705. var tz = opts.ticks && opts.ticks.z || 0;
  10706. var gz = opts.gridLines && opts.gridLines.z || 0;
  10707. if (!me._isVisible() || tz === gz || me.draw !== me._draw) {
  10708. // backward compatibility: draw has been overridden by custom scale
  10709. return [{
  10710. z: tz,
  10711. draw: function() {
  10712. me.draw.apply(me, arguments);
  10713. }
  10714. }];
  10715. }
  10716. return [{
  10717. z: gz,
  10718. draw: function() {
  10719. me._drawGrid.apply(me, arguments);
  10720. me._drawTitle.apply(me, arguments);
  10721. }
  10722. }, {
  10723. z: tz,
  10724. draw: function() {
  10725. me._drawLabels.apply(me, arguments);
  10726. }
  10727. }];
  10728. },
  10729. /**
  10730. * @private
  10731. */
  10732. _getMatchingVisibleMetas: function(type) {
  10733. var me = this;
  10734. var isHorizontal = me.isHorizontal();
  10735. return me.chart._getSortedVisibleDatasetMetas()
  10736. .filter(function(meta) {
  10737. return (!type || meta.type === type)
  10738. && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);
  10739. });
  10740. }
  10741. });
  10742. Scale.prototype._draw = Scale.prototype.draw;
  10743. var core_scale = Scale;
  10744. var isNullOrUndef$1 = helpers$1.isNullOrUndef;
  10745. var defaultConfig = {
  10746. position: 'bottom'
  10747. };
  10748. var scale_category = core_scale.extend({
  10749. determineDataLimits: function() {
  10750. var me = this;
  10751. var labels = me._getLabels();
  10752. var ticksOpts = me.options.ticks;
  10753. var min = ticksOpts.min;
  10754. var max = ticksOpts.max;
  10755. var minIndex = 0;
  10756. var maxIndex = labels.length - 1;
  10757. var findIndex;
  10758. if (min !== undefined) {
  10759. // user specified min value
  10760. findIndex = labels.indexOf(min);
  10761. if (findIndex >= 0) {
  10762. minIndex = findIndex;
  10763. }
  10764. }
  10765. if (max !== undefined) {
  10766. // user specified max value
  10767. findIndex = labels.indexOf(max);
  10768. if (findIndex >= 0) {
  10769. maxIndex = findIndex;
  10770. }
  10771. }
  10772. me.minIndex = minIndex;
  10773. me.maxIndex = maxIndex;
  10774. me.min = labels[minIndex];
  10775. me.max = labels[maxIndex];
  10776. },
  10777. buildTicks: function() {
  10778. var me = this;
  10779. var labels = me._getLabels();
  10780. var minIndex = me.minIndex;
  10781. var maxIndex = me.maxIndex;
  10782. // If we are viewing some subset of labels, slice the original array
  10783. me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);
  10784. },
  10785. getLabelForIndex: function(index, datasetIndex) {
  10786. var me = this;
  10787. var chart = me.chart;
  10788. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  10789. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  10790. }
  10791. return me._getLabels()[index];
  10792. },
  10793. _configure: function() {
  10794. var me = this;
  10795. var offset = me.options.offset;
  10796. var ticks = me.ticks;
  10797. core_scale.prototype._configure.call(me);
  10798. if (!me.isHorizontal()) {
  10799. // For backward compatibility, vertical category scale reverse is inverted.
  10800. me._reversePixels = !me._reversePixels;
  10801. }
  10802. if (!ticks) {
  10803. return;
  10804. }
  10805. me._startValue = me.minIndex - (offset ? 0.5 : 0);
  10806. me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);
  10807. },
  10808. // Used to get data value locations. Value can either be an index or a numerical value
  10809. getPixelForValue: function(value, index, datasetIndex) {
  10810. var me = this;
  10811. var valueCategory, labels, idx;
  10812. if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {
  10813. value = me.chart.data.datasets[datasetIndex].data[index];
  10814. }
  10815. // If value is a data object, then index is the index in the data array,
  10816. // not the index of the scale. We need to change that.
  10817. if (!isNullOrUndef$1(value)) {
  10818. valueCategory = me.isHorizontal() ? value.x : value.y;
  10819. }
  10820. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  10821. labels = me._getLabels();
  10822. value = helpers$1.valueOrDefault(valueCategory, value);
  10823. idx = labels.indexOf(value);
  10824. index = idx !== -1 ? idx : index;
  10825. if (isNaN(index)) {
  10826. index = value;
  10827. }
  10828. }
  10829. return me.getPixelForDecimal((index - me._startValue) / me._valueRange);
  10830. },
  10831. getPixelForTick: function(index) {
  10832. var ticks = this.ticks;
  10833. return index < 0 || index > ticks.length - 1
  10834. ? null
  10835. : this.getPixelForValue(ticks[index], index + this.minIndex);
  10836. },
  10837. getValueForPixel: function(pixel) {
  10838. var me = this;
  10839. var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  10840. return Math.min(Math.max(value, 0), me.ticks.length - 1);
  10841. },
  10842. getBasePixel: function() {
  10843. return this.bottom;
  10844. }
  10845. });
  10846. // INTERNAL: static default options, registered in src/index.js
  10847. var _defaults = defaultConfig;
  10848. scale_category._defaults = _defaults;
  10849. var noop = helpers$1.noop;
  10850. var isNullOrUndef$2 = helpers$1.isNullOrUndef;
  10851. /**
  10852. * Generate a set of linear ticks
  10853. * @param generationOptions the options used to generate the ticks
  10854. * @param dataRange the range of the data
  10855. * @returns {number[]} array of tick values
  10856. */
  10857. function generateTicks(generationOptions, dataRange) {
  10858. var ticks = [];
  10859. // To get a "nice" value for the tick spacing, we will use the appropriately named
  10860. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  10861. // for details.
  10862. var MIN_SPACING = 1e-14;
  10863. var stepSize = generationOptions.stepSize;
  10864. var unit = stepSize || 1;
  10865. var maxNumSpaces = generationOptions.maxTicks - 1;
  10866. var min = generationOptions.min;
  10867. var max = generationOptions.max;
  10868. var precision = generationOptions.precision;
  10869. var rmin = dataRange.min;
  10870. var rmax = dataRange.max;
  10871. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  10872. var factor, niceMin, niceMax, numSpaces;
  10873. // Beyond MIN_SPACING floating point numbers being to lose precision
  10874. // such that we can't do the math necessary to generate ticks
  10875. if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {
  10876. return [rmin, rmax];
  10877. }
  10878. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  10879. if (numSpaces > maxNumSpaces) {
  10880. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  10881. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  10882. }
  10883. if (stepSize || isNullOrUndef$2(precision)) {
  10884. // If a precision is not specified, calculate factor based on spacing
  10885. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  10886. } else {
  10887. // If the user specified a precision, round to that number of decimal places
  10888. factor = Math.pow(10, precision);
  10889. spacing = Math.ceil(spacing * factor) / factor;
  10890. }
  10891. niceMin = Math.floor(rmin / spacing) * spacing;
  10892. niceMax = Math.ceil(rmax / spacing) * spacing;
  10893. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  10894. if (stepSize) {
  10895. // If very close to our whole number, use it.
  10896. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  10897. niceMin = min;
  10898. }
  10899. if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  10900. niceMax = max;
  10901. }
  10902. }
  10903. numSpaces = (niceMax - niceMin) / spacing;
  10904. // If very close to our rounded value, use it.
  10905. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10906. numSpaces = Math.round(numSpaces);
  10907. } else {
  10908. numSpaces = Math.ceil(numSpaces);
  10909. }
  10910. niceMin = Math.round(niceMin * factor) / factor;
  10911. niceMax = Math.round(niceMax * factor) / factor;
  10912. ticks.push(isNullOrUndef$2(min) ? niceMin : min);
  10913. for (var j = 1; j < numSpaces; ++j) {
  10914. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  10915. }
  10916. ticks.push(isNullOrUndef$2(max) ? niceMax : max);
  10917. return ticks;
  10918. }
  10919. var scale_linearbase = core_scale.extend({
  10920. getRightValue: function(value) {
  10921. if (typeof value === 'string') {
  10922. return +value;
  10923. }
  10924. return core_scale.prototype.getRightValue.call(this, value);
  10925. },
  10926. handleTickRangeOptions: function() {
  10927. var me = this;
  10928. var opts = me.options;
  10929. var tickOpts = opts.ticks;
  10930. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  10931. // do nothing since that would make the chart weird. If the user really wants a weird chart
  10932. // axis, they can manually override it
  10933. if (tickOpts.beginAtZero) {
  10934. var minSign = helpers$1.sign(me.min);
  10935. var maxSign = helpers$1.sign(me.max);
  10936. if (minSign < 0 && maxSign < 0) {
  10937. // move the top up to 0
  10938. me.max = 0;
  10939. } else if (minSign > 0 && maxSign > 0) {
  10940. // move the bottom down to 0
  10941. me.min = 0;
  10942. }
  10943. }
  10944. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  10945. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  10946. if (tickOpts.min !== undefined) {
  10947. me.min = tickOpts.min;
  10948. } else if (tickOpts.suggestedMin !== undefined) {
  10949. if (me.min === null) {
  10950. me.min = tickOpts.suggestedMin;
  10951. } else {
  10952. me.min = Math.min(me.min, tickOpts.suggestedMin);
  10953. }
  10954. }
  10955. if (tickOpts.max !== undefined) {
  10956. me.max = tickOpts.max;
  10957. } else if (tickOpts.suggestedMax !== undefined) {
  10958. if (me.max === null) {
  10959. me.max = tickOpts.suggestedMax;
  10960. } else {
  10961. me.max = Math.max(me.max, tickOpts.suggestedMax);
  10962. }
  10963. }
  10964. if (setMin !== setMax) {
  10965. // We set the min or the max but not both.
  10966. // So ensure that our range is good
  10967. // Inverted or 0 length range can happen when
  10968. // ticks.min is set, and no datasets are visible
  10969. if (me.min >= me.max) {
  10970. if (setMin) {
  10971. me.max = me.min + 1;
  10972. } else {
  10973. me.min = me.max - 1;
  10974. }
  10975. }
  10976. }
  10977. if (me.min === me.max) {
  10978. me.max++;
  10979. if (!tickOpts.beginAtZero) {
  10980. me.min--;
  10981. }
  10982. }
  10983. },
  10984. getTickLimit: function() {
  10985. var me = this;
  10986. var tickOpts = me.options.ticks;
  10987. var stepSize = tickOpts.stepSize;
  10988. var maxTicksLimit = tickOpts.maxTicksLimit;
  10989. var maxTicks;
  10990. if (stepSize) {
  10991. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  10992. } else {
  10993. maxTicks = me._computeTickLimit();
  10994. maxTicksLimit = maxTicksLimit || 11;
  10995. }
  10996. if (maxTicksLimit) {
  10997. maxTicks = Math.min(maxTicksLimit, maxTicks);
  10998. }
  10999. return maxTicks;
  11000. },
  11001. _computeTickLimit: function() {
  11002. return Number.POSITIVE_INFINITY;
  11003. },
  11004. handleDirectionalChanges: noop,
  11005. buildTicks: function() {
  11006. var me = this;
  11007. var opts = me.options;
  11008. var tickOpts = opts.ticks;
  11009. // Figure out what the max number of ticks we can support it is based on the size of
  11010. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  11011. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  11012. // the graph. Make sure we always have at least 2 ticks
  11013. var maxTicks = me.getTickLimit();
  11014. maxTicks = Math.max(2, maxTicks);
  11015. var numericGeneratorOptions = {
  11016. maxTicks: maxTicks,
  11017. min: tickOpts.min,
  11018. max: tickOpts.max,
  11019. precision: tickOpts.precision,
  11020. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  11021. };
  11022. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  11023. me.handleDirectionalChanges();
  11024. // At this point, we need to update our max and min given the tick values since we have expanded the
  11025. // range of the scale
  11026. me.max = helpers$1.max(ticks);
  11027. me.min = helpers$1.min(ticks);
  11028. if (tickOpts.reverse) {
  11029. ticks.reverse();
  11030. me.start = me.max;
  11031. me.end = me.min;
  11032. } else {
  11033. me.start = me.min;
  11034. me.end = me.max;
  11035. }
  11036. },
  11037. convertTicksToLabels: function() {
  11038. var me = this;
  11039. me.ticksAsNumbers = me.ticks.slice();
  11040. me.zeroLineIndex = me.ticks.indexOf(0);
  11041. core_scale.prototype.convertTicksToLabels.call(me);
  11042. },
  11043. _configure: function() {
  11044. var me = this;
  11045. var ticks = me.getTicks();
  11046. var start = me.min;
  11047. var end = me.max;
  11048. var offset;
  11049. core_scale.prototype._configure.call(me);
  11050. if (me.options.offset && ticks.length) {
  11051. offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  11052. start -= offset;
  11053. end += offset;
  11054. }
  11055. me._startValue = start;
  11056. me._endValue = end;
  11057. me._valueRange = end - start;
  11058. }
  11059. });
  11060. var defaultConfig$1 = {
  11061. position: 'left',
  11062. ticks: {
  11063. callback: core_ticks.formatters.linear
  11064. }
  11065. };
  11066. var DEFAULT_MIN = 0;
  11067. var DEFAULT_MAX = 1;
  11068. function getOrCreateStack(stacks, stacked, meta) {
  11069. var key = [
  11070. meta.type,
  11071. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11072. stacked === undefined && meta.stack === undefined ? meta.index : '',
  11073. meta.stack
  11074. ].join('.');
  11075. if (stacks[key] === undefined) {
  11076. stacks[key] = {
  11077. pos: [],
  11078. neg: []
  11079. };
  11080. }
  11081. return stacks[key];
  11082. }
  11083. function stackData(scale, stacks, meta, data) {
  11084. var opts = scale.options;
  11085. var stacked = opts.stacked;
  11086. var stack = getOrCreateStack(stacks, stacked, meta);
  11087. var pos = stack.pos;
  11088. var neg = stack.neg;
  11089. var ilen = data.length;
  11090. var i, value;
  11091. for (i = 0; i < ilen; ++i) {
  11092. value = scale._parseValue(data[i]);
  11093. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11094. continue;
  11095. }
  11096. pos[i] = pos[i] || 0;
  11097. neg[i] = neg[i] || 0;
  11098. if (opts.relativePoints) {
  11099. pos[i] = 100;
  11100. } else if (value.min < 0 || value.max < 0) {
  11101. neg[i] += value.min;
  11102. } else {
  11103. pos[i] += value.max;
  11104. }
  11105. }
  11106. }
  11107. function updateMinMax(scale, meta, data) {
  11108. var ilen = data.length;
  11109. var i, value;
  11110. for (i = 0; i < ilen; ++i) {
  11111. value = scale._parseValue(data[i]);
  11112. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11113. continue;
  11114. }
  11115. scale.min = Math.min(scale.min, value.min);
  11116. scale.max = Math.max(scale.max, value.max);
  11117. }
  11118. }
  11119. var scale_linear = scale_linearbase.extend({
  11120. determineDataLimits: function() {
  11121. var me = this;
  11122. var opts = me.options;
  11123. var chart = me.chart;
  11124. var datasets = chart.data.datasets;
  11125. var metasets = me._getMatchingVisibleMetas();
  11126. var hasStacks = opts.stacked;
  11127. var stacks = {};
  11128. var ilen = metasets.length;
  11129. var i, meta, data, values;
  11130. me.min = Number.POSITIVE_INFINITY;
  11131. me.max = Number.NEGATIVE_INFINITY;
  11132. if (hasStacks === undefined) {
  11133. for (i = 0; !hasStacks && i < ilen; ++i) {
  11134. meta = metasets[i];
  11135. hasStacks = meta.stack !== undefined;
  11136. }
  11137. }
  11138. for (i = 0; i < ilen; ++i) {
  11139. meta = metasets[i];
  11140. data = datasets[meta.index].data;
  11141. if (hasStacks) {
  11142. stackData(me, stacks, meta, data);
  11143. } else {
  11144. updateMinMax(me, meta, data);
  11145. }
  11146. }
  11147. helpers$1.each(stacks, function(stackValues) {
  11148. values = stackValues.pos.concat(stackValues.neg);
  11149. me.min = Math.min(me.min, helpers$1.min(values));
  11150. me.max = Math.max(me.max, helpers$1.max(values));
  11151. });
  11152. me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  11153. me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  11154. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11155. me.handleTickRangeOptions();
  11156. },
  11157. // Returns the maximum number of ticks based on the scale dimension
  11158. _computeTickLimit: function() {
  11159. var me = this;
  11160. var tickFont;
  11161. if (me.isHorizontal()) {
  11162. return Math.ceil(me.width / 40);
  11163. }
  11164. tickFont = helpers$1.options._parseFont(me.options.ticks);
  11165. return Math.ceil(me.height / tickFont.lineHeight);
  11166. },
  11167. // Called after the ticks are built. We need
  11168. handleDirectionalChanges: function() {
  11169. if (!this.isHorizontal()) {
  11170. // We are in a vertical orientation. The top value is the highest. So reverse the array
  11171. this.ticks.reverse();
  11172. }
  11173. },
  11174. getLabelForIndex: function(index, datasetIndex) {
  11175. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11176. },
  11177. // Utils
  11178. getPixelForValue: function(value) {
  11179. var me = this;
  11180. return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);
  11181. },
  11182. getValueForPixel: function(pixel) {
  11183. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  11184. },
  11185. getPixelForTick: function(index) {
  11186. var ticks = this.ticksAsNumbers;
  11187. if (index < 0 || index > ticks.length - 1) {
  11188. return null;
  11189. }
  11190. return this.getPixelForValue(ticks[index]);
  11191. }
  11192. });
  11193. // INTERNAL: static default options, registered in src/index.js
  11194. var _defaults$1 = defaultConfig$1;
  11195. scale_linear._defaults = _defaults$1;
  11196. var valueOrDefault$b = helpers$1.valueOrDefault;
  11197. var log10 = helpers$1.math.log10;
  11198. /**
  11199. * Generate a set of logarithmic ticks
  11200. * @param generationOptions the options used to generate the ticks
  11201. * @param dataRange the range of the data
  11202. * @returns {number[]} array of tick values
  11203. */
  11204. function generateTicks$1(generationOptions, dataRange) {
  11205. var ticks = [];
  11206. var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  11207. var endExp = Math.floor(log10(dataRange.max));
  11208. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  11209. var exp, significand;
  11210. if (tickVal === 0) {
  11211. exp = Math.floor(log10(dataRange.minNotZero));
  11212. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  11213. ticks.push(tickVal);
  11214. tickVal = significand * Math.pow(10, exp);
  11215. } else {
  11216. exp = Math.floor(log10(tickVal));
  11217. significand = Math.floor(tickVal / Math.pow(10, exp));
  11218. }
  11219. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  11220. do {
  11221. ticks.push(tickVal);
  11222. ++significand;
  11223. if (significand === 10) {
  11224. significand = 1;
  11225. ++exp;
  11226. precision = exp >= 0 ? 1 : precision;
  11227. }
  11228. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  11229. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  11230. var lastTick = valueOrDefault$b(generationOptions.max, tickVal);
  11231. ticks.push(lastTick);
  11232. return ticks;
  11233. }
  11234. var defaultConfig$2 = {
  11235. position: 'left',
  11236. // label settings
  11237. ticks: {
  11238. callback: core_ticks.formatters.logarithmic
  11239. }
  11240. };
  11241. // TODO(v3): change this to positiveOrDefault
  11242. function nonNegativeOrDefault(value, defaultValue) {
  11243. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  11244. }
  11245. var scale_logarithmic = core_scale.extend({
  11246. determineDataLimits: function() {
  11247. var me = this;
  11248. var opts = me.options;
  11249. var chart = me.chart;
  11250. var datasets = chart.data.datasets;
  11251. var isHorizontal = me.isHorizontal();
  11252. function IDMatches(meta) {
  11253. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  11254. }
  11255. var datasetIndex, meta, value, data, i, ilen;
  11256. // Calculate Range
  11257. me.min = Number.POSITIVE_INFINITY;
  11258. me.max = Number.NEGATIVE_INFINITY;
  11259. me.minNotZero = Number.POSITIVE_INFINITY;
  11260. var hasStacks = opts.stacked;
  11261. if (hasStacks === undefined) {
  11262. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11263. meta = chart.getDatasetMeta(datasetIndex);
  11264. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  11265. meta.stack !== undefined) {
  11266. hasStacks = true;
  11267. break;
  11268. }
  11269. }
  11270. }
  11271. if (opts.stacked || hasStacks) {
  11272. var valuesPerStack = {};
  11273. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11274. meta = chart.getDatasetMeta(datasetIndex);
  11275. var key = [
  11276. meta.type,
  11277. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11278. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  11279. meta.stack
  11280. ].join('.');
  11281. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11282. if (valuesPerStack[key] === undefined) {
  11283. valuesPerStack[key] = [];
  11284. }
  11285. data = datasets[datasetIndex].data;
  11286. for (i = 0, ilen = data.length; i < ilen; i++) {
  11287. var values = valuesPerStack[key];
  11288. value = me._parseValue(data[i]);
  11289. // invalid, hidden and negative values are ignored
  11290. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11291. continue;
  11292. }
  11293. values[i] = values[i] || 0;
  11294. values[i] += value.max;
  11295. }
  11296. }
  11297. }
  11298. helpers$1.each(valuesPerStack, function(valuesForType) {
  11299. if (valuesForType.length > 0) {
  11300. var minVal = helpers$1.min(valuesForType);
  11301. var maxVal = helpers$1.max(valuesForType);
  11302. me.min = Math.min(me.min, minVal);
  11303. me.max = Math.max(me.max, maxVal);
  11304. }
  11305. });
  11306. } else {
  11307. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11308. meta = chart.getDatasetMeta(datasetIndex);
  11309. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11310. data = datasets[datasetIndex].data;
  11311. for (i = 0, ilen = data.length; i < ilen; i++) {
  11312. value = me._parseValue(data[i]);
  11313. // invalid, hidden and negative values are ignored
  11314. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11315. continue;
  11316. }
  11317. me.min = Math.min(value.min, me.min);
  11318. me.max = Math.max(value.max, me.max);
  11319. if (value.min !== 0) {
  11320. me.minNotZero = Math.min(value.min, me.minNotZero);
  11321. }
  11322. }
  11323. }
  11324. }
  11325. }
  11326. me.min = helpers$1.isFinite(me.min) ? me.min : null;
  11327. me.max = helpers$1.isFinite(me.max) ? me.max : null;
  11328. me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;
  11329. // Common base implementation to handle ticks.min, ticks.max
  11330. this.handleTickRangeOptions();
  11331. },
  11332. handleTickRangeOptions: function() {
  11333. var me = this;
  11334. var tickOpts = me.options.ticks;
  11335. var DEFAULT_MIN = 1;
  11336. var DEFAULT_MAX = 10;
  11337. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  11338. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  11339. if (me.min === me.max) {
  11340. if (me.min !== 0 && me.min !== null) {
  11341. me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);
  11342. me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);
  11343. } else {
  11344. me.min = DEFAULT_MIN;
  11345. me.max = DEFAULT_MAX;
  11346. }
  11347. }
  11348. if (me.min === null) {
  11349. me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);
  11350. }
  11351. if (me.max === null) {
  11352. me.max = me.min !== 0
  11353. ? Math.pow(10, Math.floor(log10(me.min)) + 1)
  11354. : DEFAULT_MAX;
  11355. }
  11356. if (me.minNotZero === null) {
  11357. if (me.min > 0) {
  11358. me.minNotZero = me.min;
  11359. } else if (me.max < 1) {
  11360. me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));
  11361. } else {
  11362. me.minNotZero = DEFAULT_MIN;
  11363. }
  11364. }
  11365. },
  11366. buildTicks: function() {
  11367. var me = this;
  11368. var tickOpts = me.options.ticks;
  11369. var reverse = !me.isHorizontal();
  11370. var generationOptions = {
  11371. min: nonNegativeOrDefault(tickOpts.min),
  11372. max: nonNegativeOrDefault(tickOpts.max)
  11373. };
  11374. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  11375. // At this point, we need to update our max and min given the tick values since we have expanded the
  11376. // range of the scale
  11377. me.max = helpers$1.max(ticks);
  11378. me.min = helpers$1.min(ticks);
  11379. if (tickOpts.reverse) {
  11380. reverse = !reverse;
  11381. me.start = me.max;
  11382. me.end = me.min;
  11383. } else {
  11384. me.start = me.min;
  11385. me.end = me.max;
  11386. }
  11387. if (reverse) {
  11388. ticks.reverse();
  11389. }
  11390. },
  11391. convertTicksToLabels: function() {
  11392. this.tickValues = this.ticks.slice();
  11393. core_scale.prototype.convertTicksToLabels.call(this);
  11394. },
  11395. // Get the correct tooltip label
  11396. getLabelForIndex: function(index, datasetIndex) {
  11397. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11398. },
  11399. getPixelForTick: function(index) {
  11400. var ticks = this.tickValues;
  11401. if (index < 0 || index > ticks.length - 1) {
  11402. return null;
  11403. }
  11404. return this.getPixelForValue(ticks[index]);
  11405. },
  11406. /**
  11407. * Returns the value of the first tick.
  11408. * @param {number} value - The minimum not zero value.
  11409. * @return {number} The first tick value.
  11410. * @private
  11411. */
  11412. _getFirstTickValue: function(value) {
  11413. var exp = Math.floor(log10(value));
  11414. var significand = Math.floor(value / Math.pow(10, exp));
  11415. return significand * Math.pow(10, exp);
  11416. },
  11417. _configure: function() {
  11418. var me = this;
  11419. var start = me.min;
  11420. var offset = 0;
  11421. core_scale.prototype._configure.call(me);
  11422. if (start === 0) {
  11423. start = me._getFirstTickValue(me.minNotZero);
  11424. offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;
  11425. }
  11426. me._startValue = log10(start);
  11427. me._valueOffset = offset;
  11428. me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);
  11429. },
  11430. getPixelForValue: function(value) {
  11431. var me = this;
  11432. var decimal = 0;
  11433. value = +me.getRightValue(value);
  11434. if (value > me.min && value > 0) {
  11435. decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;
  11436. }
  11437. return me.getPixelForDecimal(decimal);
  11438. },
  11439. getValueForPixel: function(pixel) {
  11440. var me = this;
  11441. var decimal = me.getDecimalForPixel(pixel);
  11442. return decimal === 0 && me.min === 0
  11443. ? 0
  11444. : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);
  11445. }
  11446. });
  11447. // INTERNAL: static default options, registered in src/index.js
  11448. var _defaults$2 = defaultConfig$2;
  11449. scale_logarithmic._defaults = _defaults$2;
  11450. var valueOrDefault$c = helpers$1.valueOrDefault;
  11451. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  11452. var resolve$4 = helpers$1.options.resolve;
  11453. var defaultConfig$3 = {
  11454. display: true,
  11455. // Boolean - Whether to animate scaling the chart from the centre
  11456. animate: true,
  11457. position: 'chartArea',
  11458. angleLines: {
  11459. display: true,
  11460. color: 'rgba(0,0,0,0.1)',
  11461. lineWidth: 1,
  11462. borderDash: [],
  11463. borderDashOffset: 0.0
  11464. },
  11465. gridLines: {
  11466. circular: false
  11467. },
  11468. // label settings
  11469. ticks: {
  11470. // Boolean - Show a backdrop to the scale label
  11471. showLabelBackdrop: true,
  11472. // String - The colour of the label backdrop
  11473. backdropColor: 'rgba(255,255,255,0.75)',
  11474. // Number - The backdrop padding above & below the label in pixels
  11475. backdropPaddingY: 2,
  11476. // Number - The backdrop padding to the side of the label in pixels
  11477. backdropPaddingX: 2,
  11478. callback: core_ticks.formatters.linear
  11479. },
  11480. pointLabels: {
  11481. // Boolean - if true, show point labels
  11482. display: true,
  11483. // Number - Point label font size in pixels
  11484. fontSize: 10,
  11485. // Function - Used to convert point labels
  11486. callback: function(label) {
  11487. return label;
  11488. }
  11489. }
  11490. };
  11491. function getTickBackdropHeight(opts) {
  11492. var tickOpts = opts.ticks;
  11493. if (tickOpts.display && opts.display) {
  11494. return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  11495. }
  11496. return 0;
  11497. }
  11498. function measureLabelSize(ctx, lineHeight, label) {
  11499. if (helpers$1.isArray(label)) {
  11500. return {
  11501. w: helpers$1.longestText(ctx, ctx.font, label),
  11502. h: label.length * lineHeight
  11503. };
  11504. }
  11505. return {
  11506. w: ctx.measureText(label).width,
  11507. h: lineHeight
  11508. };
  11509. }
  11510. function determineLimits(angle, pos, size, min, max) {
  11511. if (angle === min || angle === max) {
  11512. return {
  11513. start: pos - (size / 2),
  11514. end: pos + (size / 2)
  11515. };
  11516. } else if (angle < min || angle > max) {
  11517. return {
  11518. start: pos - size,
  11519. end: pos
  11520. };
  11521. }
  11522. return {
  11523. start: pos,
  11524. end: pos + size
  11525. };
  11526. }
  11527. /**
  11528. * Helper function to fit a radial linear scale with point labels
  11529. */
  11530. function fitWithPointLabels(scale) {
  11531. // Right, this is really confusing and there is a lot of maths going on here
  11532. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  11533. //
  11534. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  11535. //
  11536. // Solution:
  11537. //
  11538. // We assume the radius of the polygon is half the size of the canvas at first
  11539. // at each index we check if the text overlaps.
  11540. //
  11541. // Where it does, we store that angle and that index.
  11542. //
  11543. // After finding the largest index and angle we calculate how much we need to remove
  11544. // from the shape radius to move the point inwards by that x.
  11545. //
  11546. // We average the left and right distances to get the maximum shape radius that can fit in the box
  11547. // along with labels.
  11548. //
  11549. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  11550. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  11551. //
  11552. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  11553. // and position it in the most space efficient manner
  11554. //
  11555. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  11556. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  11557. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  11558. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  11559. var furthestLimits = {
  11560. l: 0,
  11561. r: scale.width,
  11562. t: 0,
  11563. b: scale.height - scale.paddingTop
  11564. };
  11565. var furthestAngles = {};
  11566. var i, textSize, pointPosition;
  11567. scale.ctx.font = plFont.string;
  11568. scale._pointLabelSizes = [];
  11569. var valueCount = scale.chart.data.labels.length;
  11570. for (i = 0; i < valueCount; i++) {
  11571. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  11572. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
  11573. scale._pointLabelSizes[i] = textSize;
  11574. // Add quarter circle to make degree 0 mean top of circle
  11575. var angleRadians = scale.getIndexAngle(i);
  11576. var angle = helpers$1.toDegrees(angleRadians) % 360;
  11577. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  11578. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  11579. if (hLimits.start < furthestLimits.l) {
  11580. furthestLimits.l = hLimits.start;
  11581. furthestAngles.l = angleRadians;
  11582. }
  11583. if (hLimits.end > furthestLimits.r) {
  11584. furthestLimits.r = hLimits.end;
  11585. furthestAngles.r = angleRadians;
  11586. }
  11587. if (vLimits.start < furthestLimits.t) {
  11588. furthestLimits.t = vLimits.start;
  11589. furthestAngles.t = angleRadians;
  11590. }
  11591. if (vLimits.end > furthestLimits.b) {
  11592. furthestLimits.b = vLimits.end;
  11593. furthestAngles.b = angleRadians;
  11594. }
  11595. }
  11596. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  11597. }
  11598. function getTextAlignForAngle(angle) {
  11599. if (angle === 0 || angle === 180) {
  11600. return 'center';
  11601. } else if (angle < 180) {
  11602. return 'left';
  11603. }
  11604. return 'right';
  11605. }
  11606. function fillText(ctx, text, position, lineHeight) {
  11607. var y = position.y + lineHeight / 2;
  11608. var i, ilen;
  11609. if (helpers$1.isArray(text)) {
  11610. for (i = 0, ilen = text.length; i < ilen; ++i) {
  11611. ctx.fillText(text[i], position.x, y);
  11612. y += lineHeight;
  11613. }
  11614. } else {
  11615. ctx.fillText(text, position.x, y);
  11616. }
  11617. }
  11618. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  11619. if (angle === 90 || angle === 270) {
  11620. position.y -= (textSize.h / 2);
  11621. } else if (angle > 270 || angle < 90) {
  11622. position.y -= textSize.h;
  11623. }
  11624. }
  11625. function drawPointLabels(scale) {
  11626. var ctx = scale.ctx;
  11627. var opts = scale.options;
  11628. var pointLabelOpts = opts.pointLabels;
  11629. var tickBackdropHeight = getTickBackdropHeight(opts);
  11630. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  11631. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  11632. ctx.save();
  11633. ctx.font = plFont.string;
  11634. ctx.textBaseline = 'middle';
  11635. for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
  11636. // Extra pixels out for some label spacing
  11637. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  11638. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  11639. // Keep this in loop since we may support array properties here
  11640. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  11641. ctx.fillStyle = pointLabelFontColor;
  11642. var angleRadians = scale.getIndexAngle(i);
  11643. var angle = helpers$1.toDegrees(angleRadians);
  11644. ctx.textAlign = getTextAlignForAngle(angle);
  11645. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  11646. fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
  11647. }
  11648. ctx.restore();
  11649. }
  11650. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  11651. var ctx = scale.ctx;
  11652. var circular = gridLineOpts.circular;
  11653. var valueCount = scale.chart.data.labels.length;
  11654. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  11655. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  11656. var pointPosition;
  11657. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  11658. return;
  11659. }
  11660. ctx.save();
  11661. ctx.strokeStyle = lineColor;
  11662. ctx.lineWidth = lineWidth;
  11663. if (ctx.setLineDash) {
  11664. ctx.setLineDash(gridLineOpts.borderDash || []);
  11665. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  11666. }
  11667. ctx.beginPath();
  11668. if (circular) {
  11669. // Draw circular arcs between the points
  11670. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  11671. } else {
  11672. // Draw straight lines connecting each index
  11673. pointPosition = scale.getPointPosition(0, radius);
  11674. ctx.moveTo(pointPosition.x, pointPosition.y);
  11675. for (var i = 1; i < valueCount; i++) {
  11676. pointPosition = scale.getPointPosition(i, radius);
  11677. ctx.lineTo(pointPosition.x, pointPosition.y);
  11678. }
  11679. }
  11680. ctx.closePath();
  11681. ctx.stroke();
  11682. ctx.restore();
  11683. }
  11684. function numberOrZero(param) {
  11685. return helpers$1.isNumber(param) ? param : 0;
  11686. }
  11687. var scale_radialLinear = scale_linearbase.extend({
  11688. setDimensions: function() {
  11689. var me = this;
  11690. // Set the unconstrained dimension before label rotation
  11691. me.width = me.maxWidth;
  11692. me.height = me.maxHeight;
  11693. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  11694. me.xCenter = Math.floor(me.width / 2);
  11695. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  11696. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  11697. },
  11698. determineDataLimits: function() {
  11699. var me = this;
  11700. var chart = me.chart;
  11701. var min = Number.POSITIVE_INFINITY;
  11702. var max = Number.NEGATIVE_INFINITY;
  11703. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  11704. if (chart.isDatasetVisible(datasetIndex)) {
  11705. var meta = chart.getDatasetMeta(datasetIndex);
  11706. helpers$1.each(dataset.data, function(rawValue, index) {
  11707. var value = +me.getRightValue(rawValue);
  11708. if (isNaN(value) || meta.data[index].hidden) {
  11709. return;
  11710. }
  11711. min = Math.min(value, min);
  11712. max = Math.max(value, max);
  11713. });
  11714. }
  11715. });
  11716. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  11717. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  11718. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11719. me.handleTickRangeOptions();
  11720. },
  11721. // Returns the maximum number of ticks based on the scale dimension
  11722. _computeTickLimit: function() {
  11723. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  11724. },
  11725. convertTicksToLabels: function() {
  11726. var me = this;
  11727. scale_linearbase.prototype.convertTicksToLabels.call(me);
  11728. // Point labels
  11729. me.pointLabels = me.chart.data.labels.map(function() {
  11730. var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);
  11731. return label || label === 0 ? label : '';
  11732. });
  11733. },
  11734. getLabelForIndex: function(index, datasetIndex) {
  11735. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  11736. },
  11737. fit: function() {
  11738. var me = this;
  11739. var opts = me.options;
  11740. if (opts.display && opts.pointLabels.display) {
  11741. fitWithPointLabels(me);
  11742. } else {
  11743. me.setCenterPoint(0, 0, 0, 0);
  11744. }
  11745. },
  11746. /**
  11747. * Set radius reductions and determine new radius and center point
  11748. * @private
  11749. */
  11750. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  11751. var me = this;
  11752. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  11753. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  11754. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  11755. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  11756. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  11757. radiusReductionRight = numberOrZero(radiusReductionRight);
  11758. radiusReductionTop = numberOrZero(radiusReductionTop);
  11759. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  11760. me.drawingArea = Math.min(
  11761. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  11762. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  11763. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  11764. },
  11765. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  11766. var me = this;
  11767. var maxRight = me.width - rightMovement - me.drawingArea;
  11768. var maxLeft = leftMovement + me.drawingArea;
  11769. var maxTop = topMovement + me.drawingArea;
  11770. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  11771. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  11772. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  11773. },
  11774. getIndexAngle: function(index) {
  11775. var chart = this.chart;
  11776. var angleMultiplier = 360 / chart.data.labels.length;
  11777. var options = chart.options || {};
  11778. var startAngle = options.startAngle || 0;
  11779. // Start from the top instead of right, so remove a quarter of the circle
  11780. var angle = (index * angleMultiplier + startAngle) % 360;
  11781. return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;
  11782. },
  11783. getDistanceFromCenterForValue: function(value) {
  11784. var me = this;
  11785. if (helpers$1.isNullOrUndef(value)) {
  11786. return NaN;
  11787. }
  11788. // Take into account half font size + the yPadding of the top value
  11789. var scalingFactor = me.drawingArea / (me.max - me.min);
  11790. if (me.options.ticks.reverse) {
  11791. return (me.max - value) * scalingFactor;
  11792. }
  11793. return (value - me.min) * scalingFactor;
  11794. },
  11795. getPointPosition: function(index, distanceFromCenter) {
  11796. var me = this;
  11797. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  11798. return {
  11799. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  11800. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  11801. };
  11802. },
  11803. getPointPositionForValue: function(index, value) {
  11804. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  11805. },
  11806. getBasePosition: function(index) {
  11807. var me = this;
  11808. var min = me.min;
  11809. var max = me.max;
  11810. return me.getPointPositionForValue(index || 0,
  11811. me.beginAtZero ? 0 :
  11812. min < 0 && max < 0 ? max :
  11813. min > 0 && max > 0 ? min :
  11814. 0);
  11815. },
  11816. /**
  11817. * @private
  11818. */
  11819. _drawGrid: function() {
  11820. var me = this;
  11821. var ctx = me.ctx;
  11822. var opts = me.options;
  11823. var gridLineOpts = opts.gridLines;
  11824. var angleLineOpts = opts.angleLines;
  11825. var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  11826. var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);
  11827. var i, offset, position;
  11828. if (opts.pointLabels.display) {
  11829. drawPointLabels(me);
  11830. }
  11831. if (gridLineOpts.display) {
  11832. helpers$1.each(me.ticks, function(label, index) {
  11833. if (index !== 0) {
  11834. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11835. drawRadiusLine(me, gridLineOpts, offset, index);
  11836. }
  11837. });
  11838. }
  11839. if (angleLineOpts.display && lineWidth && lineColor) {
  11840. ctx.save();
  11841. ctx.lineWidth = lineWidth;
  11842. ctx.strokeStyle = lineColor;
  11843. if (ctx.setLineDash) {
  11844. ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  11845. ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  11846. }
  11847. for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
  11848. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  11849. position = me.getPointPosition(i, offset);
  11850. ctx.beginPath();
  11851. ctx.moveTo(me.xCenter, me.yCenter);
  11852. ctx.lineTo(position.x, position.y);
  11853. ctx.stroke();
  11854. }
  11855. ctx.restore();
  11856. }
  11857. },
  11858. /**
  11859. * @private
  11860. */
  11861. _drawLabels: function() {
  11862. var me = this;
  11863. var ctx = me.ctx;
  11864. var opts = me.options;
  11865. var tickOpts = opts.ticks;
  11866. if (!tickOpts.display) {
  11867. return;
  11868. }
  11869. var startAngle = me.getIndexAngle(0);
  11870. var tickFont = helpers$1.options._parseFont(tickOpts);
  11871. var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  11872. var offset, width;
  11873. ctx.save();
  11874. ctx.font = tickFont.string;
  11875. ctx.translate(me.xCenter, me.yCenter);
  11876. ctx.rotate(startAngle);
  11877. ctx.textAlign = 'center';
  11878. ctx.textBaseline = 'middle';
  11879. helpers$1.each(me.ticks, function(label, index) {
  11880. if (index === 0 && !tickOpts.reverse) {
  11881. return;
  11882. }
  11883. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11884. if (tickOpts.showLabelBackdrop) {
  11885. width = ctx.measureText(label).width;
  11886. ctx.fillStyle = tickOpts.backdropColor;
  11887. ctx.fillRect(
  11888. -width / 2 - tickOpts.backdropPaddingX,
  11889. -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  11890. width + tickOpts.backdropPaddingX * 2,
  11891. tickFont.size + tickOpts.backdropPaddingY * 2
  11892. );
  11893. }
  11894. ctx.fillStyle = tickFontColor;
  11895. ctx.fillText(label, 0, -offset);
  11896. });
  11897. ctx.restore();
  11898. },
  11899. /**
  11900. * @private
  11901. */
  11902. _drawTitle: helpers$1.noop
  11903. });
  11904. // INTERNAL: static default options, registered in src/index.js
  11905. var _defaults$3 = defaultConfig$3;
  11906. scale_radialLinear._defaults = _defaults$3;
  11907. var deprecated$1 = helpers$1._deprecated;
  11908. var resolve$5 = helpers$1.options.resolve;
  11909. var valueOrDefault$d = helpers$1.valueOrDefault;
  11910. // Integer constants are from the ES6 spec.
  11911. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  11912. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  11913. var INTERVALS = {
  11914. millisecond: {
  11915. common: true,
  11916. size: 1,
  11917. steps: 1000
  11918. },
  11919. second: {
  11920. common: true,
  11921. size: 1000,
  11922. steps: 60
  11923. },
  11924. minute: {
  11925. common: true,
  11926. size: 60000,
  11927. steps: 60
  11928. },
  11929. hour: {
  11930. common: true,
  11931. size: 3600000,
  11932. steps: 24
  11933. },
  11934. day: {
  11935. common: true,
  11936. size: 86400000,
  11937. steps: 30
  11938. },
  11939. week: {
  11940. common: false,
  11941. size: 604800000,
  11942. steps: 4
  11943. },
  11944. month: {
  11945. common: true,
  11946. size: 2.628e9,
  11947. steps: 12
  11948. },
  11949. quarter: {
  11950. common: false,
  11951. size: 7.884e9,
  11952. steps: 4
  11953. },
  11954. year: {
  11955. common: true,
  11956. size: 3.154e10
  11957. }
  11958. };
  11959. var UNITS = Object.keys(INTERVALS);
  11960. function sorter(a, b) {
  11961. return a - b;
  11962. }
  11963. function arrayUnique(items) {
  11964. var hash = {};
  11965. var out = [];
  11966. var i, ilen, item;
  11967. for (i = 0, ilen = items.length; i < ilen; ++i) {
  11968. item = items[i];
  11969. if (!hash[item]) {
  11970. hash[item] = true;
  11971. out.push(item);
  11972. }
  11973. }
  11974. return out;
  11975. }
  11976. function getMin(options) {
  11977. return helpers$1.valueOrDefault(options.time.min, options.ticks.min);
  11978. }
  11979. function getMax(options) {
  11980. return helpers$1.valueOrDefault(options.time.max, options.ticks.max);
  11981. }
  11982. /**
  11983. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  11984. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  11985. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  11986. * extremity (left + width or top + height). Note that it would be more optimized to directly
  11987. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  11988. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  11989. *
  11990. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  11991. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  11992. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  11993. * If 'series', timestamps will be positioned at the same distance from each other. In this
  11994. * case, only timestamps that break the time linearity are registered, meaning that in the
  11995. * best case, all timestamps are linear, the table contains only min and max.
  11996. */
  11997. function buildLookupTable(timestamps, min, max, distribution) {
  11998. if (distribution === 'linear' || !timestamps.length) {
  11999. return [
  12000. {time: min, pos: 0},
  12001. {time: max, pos: 1}
  12002. ];
  12003. }
  12004. var table = [];
  12005. var items = [min];
  12006. var i, ilen, prev, curr, next;
  12007. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12008. curr = timestamps[i];
  12009. if (curr > min && curr < max) {
  12010. items.push(curr);
  12011. }
  12012. }
  12013. items.push(max);
  12014. for (i = 0, ilen = items.length; i < ilen; ++i) {
  12015. next = items[i + 1];
  12016. prev = items[i - 1];
  12017. curr = items[i];
  12018. // only add points that breaks the scale linearity
  12019. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  12020. table.push({time: curr, pos: i / (ilen - 1)});
  12021. }
  12022. }
  12023. return table;
  12024. }
  12025. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  12026. function lookup(table, key, value) {
  12027. var lo = 0;
  12028. var hi = table.length - 1;
  12029. var mid, i0, i1;
  12030. while (lo >= 0 && lo <= hi) {
  12031. mid = (lo + hi) >> 1;
  12032. i0 = table[mid - 1] || null;
  12033. i1 = table[mid];
  12034. if (!i0) {
  12035. // given value is outside table (before first item)
  12036. return {lo: null, hi: i1};
  12037. } else if (i1[key] < value) {
  12038. lo = mid + 1;
  12039. } else if (i0[key] > value) {
  12040. hi = mid - 1;
  12041. } else {
  12042. return {lo: i0, hi: i1};
  12043. }
  12044. }
  12045. // given value is outside table (after last item)
  12046. return {lo: i1, hi: null};
  12047. }
  12048. /**
  12049. * Linearly interpolates the given source `value` using the table items `skey` values and
  12050. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  12051. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  12052. * index [0, 1] or [n - 1, n] are used for the interpolation.
  12053. */
  12054. function interpolate$1(table, skey, sval, tkey) {
  12055. var range = lookup(table, skey, sval);
  12056. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  12057. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  12058. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  12059. var span = next[skey] - prev[skey];
  12060. var ratio = span ? (sval - prev[skey]) / span : 0;
  12061. var offset = (next[tkey] - prev[tkey]) * ratio;
  12062. return prev[tkey] + offset;
  12063. }
  12064. function toTimestamp(scale, input) {
  12065. var adapter = scale._adapter;
  12066. var options = scale.options.time;
  12067. var parser = options.parser;
  12068. var format = parser || options.format;
  12069. var value = input;
  12070. if (typeof parser === 'function') {
  12071. value = parser(value);
  12072. }
  12073. // Only parse if its not a timestamp already
  12074. if (!helpers$1.isFinite(value)) {
  12075. value = typeof format === 'string'
  12076. ? adapter.parse(value, format)
  12077. : adapter.parse(value);
  12078. }
  12079. if (value !== null) {
  12080. return +value;
  12081. }
  12082. // Labels are in an incompatible format and no `parser` has been provided.
  12083. // The user might still use the deprecated `format` option for parsing.
  12084. if (!parser && typeof format === 'function') {
  12085. value = format(input);
  12086. // `format` could return something else than a timestamp, if so, parse it
  12087. if (!helpers$1.isFinite(value)) {
  12088. value = adapter.parse(value);
  12089. }
  12090. }
  12091. return value;
  12092. }
  12093. function parse(scale, input) {
  12094. if (helpers$1.isNullOrUndef(input)) {
  12095. return null;
  12096. }
  12097. var options = scale.options.time;
  12098. var value = toTimestamp(scale, scale.getRightValue(input));
  12099. if (value === null) {
  12100. return value;
  12101. }
  12102. if (options.round) {
  12103. value = +scale._adapter.startOf(value, options.round);
  12104. }
  12105. return value;
  12106. }
  12107. /**
  12108. * Figures out what unit results in an appropriate number of auto-generated ticks
  12109. */
  12110. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  12111. var ilen = UNITS.length;
  12112. var i, interval, factor;
  12113. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  12114. interval = INTERVALS[UNITS[i]];
  12115. factor = interval.steps ? interval.steps : MAX_INTEGER;
  12116. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  12117. return UNITS[i];
  12118. }
  12119. }
  12120. return UNITS[ilen - 1];
  12121. }
  12122. /**
  12123. * Figures out what unit to format a set of ticks with
  12124. */
  12125. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  12126. var i, unit;
  12127. for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  12128. unit = UNITS[i];
  12129. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  12130. return unit;
  12131. }
  12132. }
  12133. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  12134. }
  12135. function determineMajorUnit(unit) {
  12136. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  12137. if (INTERVALS[UNITS[i]].common) {
  12138. return UNITS[i];
  12139. }
  12140. }
  12141. }
  12142. /**
  12143. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  12144. * `minor` unit using the given scale time `options`.
  12145. * Important: this method can return ticks outside the min and max range, it's the
  12146. * responsibility of the calling code to clamp values if needed.
  12147. */
  12148. function generate(scale, min, max, capacity) {
  12149. var adapter = scale._adapter;
  12150. var options = scale.options;
  12151. var timeOpts = options.time;
  12152. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  12153. var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
  12154. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  12155. var first = min;
  12156. var ticks = [];
  12157. var time;
  12158. // For 'week' unit, handle the first day of week option
  12159. if (weekday) {
  12160. first = +adapter.startOf(first, 'isoWeek', weekday);
  12161. }
  12162. // Align first ticks on unit
  12163. first = +adapter.startOf(first, weekday ? 'day' : minor);
  12164. // Prevent browser from freezing in case user options request millions of milliseconds
  12165. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  12166. throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
  12167. }
  12168. for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {
  12169. ticks.push(time);
  12170. }
  12171. if (time === max || options.bounds === 'ticks') {
  12172. ticks.push(time);
  12173. }
  12174. return ticks;
  12175. }
  12176. /**
  12177. * Returns the start and end offsets from edges in the form of {start, end}
  12178. * where each value is a relative width to the scale and ranges between 0 and 1.
  12179. * They add extra margins on the both sides by scaling down the original scale.
  12180. * Offsets are added when the `offset` option is true.
  12181. */
  12182. function computeOffsets(table, ticks, min, max, options) {
  12183. var start = 0;
  12184. var end = 0;
  12185. var first, last;
  12186. if (options.offset && ticks.length) {
  12187. first = interpolate$1(table, 'time', ticks[0], 'pos');
  12188. if (ticks.length === 1) {
  12189. start = 1 - first;
  12190. } else {
  12191. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  12192. }
  12193. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  12194. if (ticks.length === 1) {
  12195. end = last;
  12196. } else {
  12197. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  12198. }
  12199. }
  12200. return {start: start, end: end, factor: 1 / (start + 1 + end)};
  12201. }
  12202. function setMajorTicks(scale, ticks, map, majorUnit) {
  12203. var adapter = scale._adapter;
  12204. var first = +adapter.startOf(ticks[0].value, majorUnit);
  12205. var last = ticks[ticks.length - 1].value;
  12206. var major, index;
  12207. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  12208. index = map[major];
  12209. if (index >= 0) {
  12210. ticks[index].major = true;
  12211. }
  12212. }
  12213. return ticks;
  12214. }
  12215. function ticksFromTimestamps(scale, values, majorUnit) {
  12216. var ticks = [];
  12217. var map = {};
  12218. var ilen = values.length;
  12219. var i, value;
  12220. for (i = 0; i < ilen; ++i) {
  12221. value = values[i];
  12222. map[value] = i;
  12223. ticks.push({
  12224. value: value,
  12225. major: false
  12226. });
  12227. }
  12228. // We set the major ticks separately from the above loop because calling startOf for every tick
  12229. // is expensive when there is a large number of ticks
  12230. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  12231. }
  12232. var defaultConfig$4 = {
  12233. position: 'bottom',
  12234. /**
  12235. * Data distribution along the scale:
  12236. * - 'linear': data are spread according to their time (distances can vary),
  12237. * - 'series': data are spread at the same distance from each other.
  12238. * @see https://github.com/chartjs/Chart.js/pull/4507
  12239. * @since 2.7.0
  12240. */
  12241. distribution: 'linear',
  12242. /**
  12243. * Scale boundary strategy (bypassed by min/max time options)
  12244. * - `data`: make sure data are fully visible, ticks outside are removed
  12245. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  12246. * @see https://github.com/chartjs/Chart.js/pull/4556
  12247. * @since 2.7.0
  12248. */
  12249. bounds: 'data',
  12250. adapters: {},
  12251. time: {
  12252. 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
  12253. unit: false, // false == automatic or override with week, month, year, etc.
  12254. round: false, // none, or override with week, month, year, etc.
  12255. displayFormat: false, // DEPRECATED
  12256. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  12257. minUnit: 'millisecond',
  12258. displayFormats: {}
  12259. },
  12260. ticks: {
  12261. autoSkip: false,
  12262. /**
  12263. * Ticks generation input values:
  12264. * - 'auto': generates "optimal" ticks based on scale size and time options.
  12265. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  12266. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  12267. * @see https://github.com/chartjs/Chart.js/pull/4507
  12268. * @since 2.7.0
  12269. */
  12270. source: 'auto',
  12271. major: {
  12272. enabled: false
  12273. }
  12274. }
  12275. };
  12276. var scale_time = core_scale.extend({
  12277. initialize: function() {
  12278. this.mergeTicksOptions();
  12279. core_scale.prototype.initialize.call(this);
  12280. },
  12281. update: function() {
  12282. var me = this;
  12283. var options = me.options;
  12284. var time = options.time || (options.time = {});
  12285. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  12286. // DEPRECATIONS: output a message only one time per update
  12287. deprecated$1('time scale', time.format, 'time.format', 'time.parser');
  12288. deprecated$1('time scale', time.min, 'time.min', 'ticks.min');
  12289. deprecated$1('time scale', time.max, 'time.max', 'ticks.max');
  12290. // Backward compatibility: before introducing adapter, `displayFormats` was
  12291. // supposed to contain *all* unit/string pairs but this can't be resolved
  12292. // when loading the scale (adapters are loaded afterward), so let's populate
  12293. // missing formats on update
  12294. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  12295. return core_scale.prototype.update.apply(me, arguments);
  12296. },
  12297. /**
  12298. * Allows data to be referenced via 't' attribute
  12299. */
  12300. getRightValue: function(rawValue) {
  12301. if (rawValue && rawValue.t !== undefined) {
  12302. rawValue = rawValue.t;
  12303. }
  12304. return core_scale.prototype.getRightValue.call(this, rawValue);
  12305. },
  12306. determineDataLimits: function() {
  12307. var me = this;
  12308. var chart = me.chart;
  12309. var adapter = me._adapter;
  12310. var options = me.options;
  12311. var unit = options.time.unit || 'day';
  12312. var min = MAX_INTEGER;
  12313. var max = MIN_INTEGER;
  12314. var timestamps = [];
  12315. var datasets = [];
  12316. var labels = [];
  12317. var i, j, ilen, jlen, data, timestamp, labelsAdded;
  12318. var dataLabels = me._getLabels();
  12319. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  12320. labels.push(parse(me, dataLabels[i]));
  12321. }
  12322. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  12323. if (chart.isDatasetVisible(i)) {
  12324. data = chart.data.datasets[i].data;
  12325. // Let's consider that all data have the same format.
  12326. if (helpers$1.isObject(data[0])) {
  12327. datasets[i] = [];
  12328. for (j = 0, jlen = data.length; j < jlen; ++j) {
  12329. timestamp = parse(me, data[j]);
  12330. timestamps.push(timestamp);
  12331. datasets[i][j] = timestamp;
  12332. }
  12333. } else {
  12334. datasets[i] = labels.slice(0);
  12335. if (!labelsAdded) {
  12336. timestamps = timestamps.concat(labels);
  12337. labelsAdded = true;
  12338. }
  12339. }
  12340. } else {
  12341. datasets[i] = [];
  12342. }
  12343. }
  12344. if (labels.length) {
  12345. min = Math.min(min, labels[0]);
  12346. max = Math.max(max, labels[labels.length - 1]);
  12347. }
  12348. if (timestamps.length) {
  12349. timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);
  12350. min = Math.min(min, timestamps[0]);
  12351. max = Math.max(max, timestamps[timestamps.length - 1]);
  12352. }
  12353. min = parse(me, getMin(options)) || min;
  12354. max = parse(me, getMax(options)) || max;
  12355. // In case there is no valid min/max, set limits based on unit time option
  12356. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  12357. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  12358. // Make sure that max is strictly higher than min (required by the lookup table)
  12359. me.min = Math.min(min, max);
  12360. me.max = Math.max(min + 1, max);
  12361. // PRIVATE
  12362. me._table = [];
  12363. me._timestamps = {
  12364. data: timestamps,
  12365. datasets: datasets,
  12366. labels: labels
  12367. };
  12368. },
  12369. buildTicks: function() {
  12370. var me = this;
  12371. var min = me.min;
  12372. var max = me.max;
  12373. var options = me.options;
  12374. var tickOpts = options.ticks;
  12375. var timeOpts = options.time;
  12376. var timestamps = me._timestamps;
  12377. var ticks = [];
  12378. var capacity = me.getLabelCapacity(min);
  12379. var source = tickOpts.source;
  12380. var distribution = options.distribution;
  12381. var i, ilen, timestamp;
  12382. if (source === 'data' || (source === 'auto' && distribution === 'series')) {
  12383. timestamps = timestamps.data;
  12384. } else if (source === 'labels') {
  12385. timestamps = timestamps.labels;
  12386. } else {
  12387. timestamps = generate(me, min, max, capacity);
  12388. }
  12389. if (options.bounds === 'ticks' && timestamps.length) {
  12390. min = timestamps[0];
  12391. max = timestamps[timestamps.length - 1];
  12392. }
  12393. // Enforce limits with user min/max options
  12394. min = parse(me, getMin(options)) || min;
  12395. max = parse(me, getMax(options)) || max;
  12396. // Remove ticks outside the min/max range
  12397. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12398. timestamp = timestamps[i];
  12399. if (timestamp >= min && timestamp <= max) {
  12400. ticks.push(timestamp);
  12401. }
  12402. }
  12403. me.min = min;
  12404. me.max = max;
  12405. // PRIVATE
  12406. // determineUnitForFormatting relies on the number of ticks so we don't use it when
  12407. // autoSkip is enabled because we don't yet know what the final number of ticks will be
  12408. me._unit = timeOpts.unit || (tickOpts.autoSkip
  12409. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
  12410. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  12411. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  12412. : determineMajorUnit(me._unit);
  12413. me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
  12414. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  12415. if (tickOpts.reverse) {
  12416. ticks.reverse();
  12417. }
  12418. return ticksFromTimestamps(me, ticks, me._majorUnit);
  12419. },
  12420. getLabelForIndex: function(index, datasetIndex) {
  12421. var me = this;
  12422. var adapter = me._adapter;
  12423. var data = me.chart.data;
  12424. var timeOpts = me.options.time;
  12425. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  12426. var value = data.datasets[datasetIndex].data[index];
  12427. if (helpers$1.isObject(value)) {
  12428. label = me.getRightValue(value);
  12429. }
  12430. if (timeOpts.tooltipFormat) {
  12431. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  12432. }
  12433. if (typeof label === 'string') {
  12434. return label;
  12435. }
  12436. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  12437. },
  12438. /**
  12439. * Function to format an individual tick mark
  12440. * @private
  12441. */
  12442. tickFormatFunction: function(time, index, ticks, format) {
  12443. var me = this;
  12444. var adapter = me._adapter;
  12445. var options = me.options;
  12446. var formats = options.time.displayFormats;
  12447. var minorFormat = formats[me._unit];
  12448. var majorUnit = me._majorUnit;
  12449. var majorFormat = formats[majorUnit];
  12450. var tick = ticks[index];
  12451. var tickOpts = options.ticks;
  12452. var major = majorUnit && majorFormat && tick && tick.major;
  12453. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  12454. var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;
  12455. var formatter = resolve$5([
  12456. nestedTickOpts.callback,
  12457. nestedTickOpts.userCallback,
  12458. tickOpts.callback,
  12459. tickOpts.userCallback
  12460. ]);
  12461. return formatter ? formatter(label, index, ticks) : label;
  12462. },
  12463. convertTicksToLabels: function(ticks) {
  12464. var labels = [];
  12465. var i, ilen;
  12466. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  12467. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  12468. }
  12469. return labels;
  12470. },
  12471. /**
  12472. * @private
  12473. */
  12474. getPixelForOffset: function(time) {
  12475. var me = this;
  12476. var offsets = me._offsets;
  12477. var pos = interpolate$1(me._table, 'time', time, 'pos');
  12478. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12479. },
  12480. getPixelForValue: function(value, index, datasetIndex) {
  12481. var me = this;
  12482. var time = null;
  12483. if (index !== undefined && datasetIndex !== undefined) {
  12484. time = me._timestamps.datasets[datasetIndex][index];
  12485. }
  12486. if (time === null) {
  12487. time = parse(me, value);
  12488. }
  12489. if (time !== null) {
  12490. return me.getPixelForOffset(time);
  12491. }
  12492. },
  12493. getPixelForTick: function(index) {
  12494. var ticks = this.getTicks();
  12495. return index >= 0 && index < ticks.length ?
  12496. this.getPixelForOffset(ticks[index].value) :
  12497. null;
  12498. },
  12499. getValueForPixel: function(pixel) {
  12500. var me = this;
  12501. var offsets = me._offsets;
  12502. var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12503. var time = interpolate$1(me._table, 'pos', pos, 'time');
  12504. // DEPRECATION, we should return time directly
  12505. return me._adapter._create(time);
  12506. },
  12507. /**
  12508. * @private
  12509. */
  12510. _getLabelSize: function(label) {
  12511. var me = this;
  12512. var ticksOpts = me.options.ticks;
  12513. var tickLabelWidth = me.ctx.measureText(label).width;
  12514. var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  12515. var cosRotation = Math.cos(angle);
  12516. var sinRotation = Math.sin(angle);
  12517. var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  12518. return {
  12519. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  12520. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  12521. };
  12522. },
  12523. /**
  12524. * Crude approximation of what the label width might be
  12525. * @private
  12526. */
  12527. getLabelWidth: function(label) {
  12528. return this._getLabelSize(label).w;
  12529. },
  12530. /**
  12531. * @private
  12532. */
  12533. getLabelCapacity: function(exampleTime) {
  12534. var me = this;
  12535. var timeOpts = me.options.time;
  12536. var displayFormats = timeOpts.displayFormats;
  12537. // pick the longest format (milliseconds) for guestimation
  12538. var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  12539. var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  12540. var size = me._getLabelSize(exampleLabel);
  12541. var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);
  12542. if (me.options.offset) {
  12543. capacity--;
  12544. }
  12545. return capacity > 0 ? capacity : 1;
  12546. }
  12547. });
  12548. // INTERNAL: static default options, registered in src/index.js
  12549. var _defaults$4 = defaultConfig$4;
  12550. scale_time._defaults = _defaults$4;
  12551. var scales = {
  12552. category: scale_category,
  12553. linear: scale_linear,
  12554. logarithmic: scale_logarithmic,
  12555. radialLinear: scale_radialLinear,
  12556. time: scale_time
  12557. };
  12558. var moment = createCommonjsModule(function (module, exports) {
  12559. (function (global, factory) {
  12560. module.exports = factory() ;
  12561. }(commonjsGlobal, (function () {
  12562. var hookCallback;
  12563. function hooks () {
  12564. return hookCallback.apply(null, arguments);
  12565. }
  12566. // This is done to register the method called with moment()
  12567. // without creating circular dependencies.
  12568. function setHookCallback (callback) {
  12569. hookCallback = callback;
  12570. }
  12571. function isArray(input) {
  12572. return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
  12573. }
  12574. function isObject(input) {
  12575. // IE8 will treat undefined and null as object if it wasn't for
  12576. // input != null
  12577. return input != null && Object.prototype.toString.call(input) === '[object Object]';
  12578. }
  12579. function isObjectEmpty(obj) {
  12580. if (Object.getOwnPropertyNames) {
  12581. return (Object.getOwnPropertyNames(obj).length === 0);
  12582. } else {
  12583. var k;
  12584. for (k in obj) {
  12585. if (obj.hasOwnProperty(k)) {
  12586. return false;
  12587. }
  12588. }
  12589. return true;
  12590. }
  12591. }
  12592. function isUndefined(input) {
  12593. return input === void 0;
  12594. }
  12595. function isNumber(input) {
  12596. return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
  12597. }
  12598. function isDate(input) {
  12599. return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
  12600. }
  12601. function map(arr, fn) {
  12602. var res = [], i;
  12603. for (i = 0; i < arr.length; ++i) {
  12604. res.push(fn(arr[i], i));
  12605. }
  12606. return res;
  12607. }
  12608. function hasOwnProp(a, b) {
  12609. return Object.prototype.hasOwnProperty.call(a, b);
  12610. }
  12611. function extend(a, b) {
  12612. for (var i in b) {
  12613. if (hasOwnProp(b, i)) {
  12614. a[i] = b[i];
  12615. }
  12616. }
  12617. if (hasOwnProp(b, 'toString')) {
  12618. a.toString = b.toString;
  12619. }
  12620. if (hasOwnProp(b, 'valueOf')) {
  12621. a.valueOf = b.valueOf;
  12622. }
  12623. return a;
  12624. }
  12625. function createUTC (input, format, locale, strict) {
  12626. return createLocalOrUTC(input, format, locale, strict, true).utc();
  12627. }
  12628. function defaultParsingFlags() {
  12629. // We need to deep clone this object.
  12630. return {
  12631. empty : false,
  12632. unusedTokens : [],
  12633. unusedInput : [],
  12634. overflow : -2,
  12635. charsLeftOver : 0,
  12636. nullInput : false,
  12637. invalidMonth : null,
  12638. invalidFormat : false,
  12639. userInvalidated : false,
  12640. iso : false,
  12641. parsedDateParts : [],
  12642. meridiem : null,
  12643. rfc2822 : false,
  12644. weekdayMismatch : false
  12645. };
  12646. }
  12647. function getParsingFlags(m) {
  12648. if (m._pf == null) {
  12649. m._pf = defaultParsingFlags();
  12650. }
  12651. return m._pf;
  12652. }
  12653. var some;
  12654. if (Array.prototype.some) {
  12655. some = Array.prototype.some;
  12656. } else {
  12657. some = function (fun) {
  12658. var t = Object(this);
  12659. var len = t.length >>> 0;
  12660. for (var i = 0; i < len; i++) {
  12661. if (i in t && fun.call(this, t[i], i, t)) {
  12662. return true;
  12663. }
  12664. }
  12665. return false;
  12666. };
  12667. }
  12668. function isValid(m) {
  12669. if (m._isValid == null) {
  12670. var flags = getParsingFlags(m);
  12671. var parsedParts = some.call(flags.parsedDateParts, function (i) {
  12672. return i != null;
  12673. });
  12674. var isNowValid = !isNaN(m._d.getTime()) &&
  12675. flags.overflow < 0 &&
  12676. !flags.empty &&
  12677. !flags.invalidMonth &&
  12678. !flags.invalidWeekday &&
  12679. !flags.weekdayMismatch &&
  12680. !flags.nullInput &&
  12681. !flags.invalidFormat &&
  12682. !flags.userInvalidated &&
  12683. (!flags.meridiem || (flags.meridiem && parsedParts));
  12684. if (m._strict) {
  12685. isNowValid = isNowValid &&
  12686. flags.charsLeftOver === 0 &&
  12687. flags.unusedTokens.length === 0 &&
  12688. flags.bigHour === undefined;
  12689. }
  12690. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  12691. m._isValid = isNowValid;
  12692. }
  12693. else {
  12694. return isNowValid;
  12695. }
  12696. }
  12697. return m._isValid;
  12698. }
  12699. function createInvalid (flags) {
  12700. var m = createUTC(NaN);
  12701. if (flags != null) {
  12702. extend(getParsingFlags(m), flags);
  12703. }
  12704. else {
  12705. getParsingFlags(m).userInvalidated = true;
  12706. }
  12707. return m;
  12708. }
  12709. // Plugins that add properties should also add the key here (null value),
  12710. // so we can properly clone ourselves.
  12711. var momentProperties = hooks.momentProperties = [];
  12712. function copyConfig(to, from) {
  12713. var i, prop, val;
  12714. if (!isUndefined(from._isAMomentObject)) {
  12715. to._isAMomentObject = from._isAMomentObject;
  12716. }
  12717. if (!isUndefined(from._i)) {
  12718. to._i = from._i;
  12719. }
  12720. if (!isUndefined(from._f)) {
  12721. to._f = from._f;
  12722. }
  12723. if (!isUndefined(from._l)) {
  12724. to._l = from._l;
  12725. }
  12726. if (!isUndefined(from._strict)) {
  12727. to._strict = from._strict;
  12728. }
  12729. if (!isUndefined(from._tzm)) {
  12730. to._tzm = from._tzm;
  12731. }
  12732. if (!isUndefined(from._isUTC)) {
  12733. to._isUTC = from._isUTC;
  12734. }
  12735. if (!isUndefined(from._offset)) {
  12736. to._offset = from._offset;
  12737. }
  12738. if (!isUndefined(from._pf)) {
  12739. to._pf = getParsingFlags(from);
  12740. }
  12741. if (!isUndefined(from._locale)) {
  12742. to._locale = from._locale;
  12743. }
  12744. if (momentProperties.length > 0) {
  12745. for (i = 0; i < momentProperties.length; i++) {
  12746. prop = momentProperties[i];
  12747. val = from[prop];
  12748. if (!isUndefined(val)) {
  12749. to[prop] = val;
  12750. }
  12751. }
  12752. }
  12753. return to;
  12754. }
  12755. var updateInProgress = false;
  12756. // Moment prototype object
  12757. function Moment(config) {
  12758. copyConfig(this, config);
  12759. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  12760. if (!this.isValid()) {
  12761. this._d = new Date(NaN);
  12762. }
  12763. // Prevent infinite loop in case updateOffset creates new moment
  12764. // objects.
  12765. if (updateInProgress === false) {
  12766. updateInProgress = true;
  12767. hooks.updateOffset(this);
  12768. updateInProgress = false;
  12769. }
  12770. }
  12771. function isMoment (obj) {
  12772. return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
  12773. }
  12774. function absFloor (number) {
  12775. if (number < 0) {
  12776. // -0 -> 0
  12777. return Math.ceil(number) || 0;
  12778. } else {
  12779. return Math.floor(number);
  12780. }
  12781. }
  12782. function toInt(argumentForCoercion) {
  12783. var coercedNumber = +argumentForCoercion,
  12784. value = 0;
  12785. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  12786. value = absFloor(coercedNumber);
  12787. }
  12788. return value;
  12789. }
  12790. // compare two arrays, return the number of differences
  12791. function compareArrays(array1, array2, dontConvert) {
  12792. var len = Math.min(array1.length, array2.length),
  12793. lengthDiff = Math.abs(array1.length - array2.length),
  12794. diffs = 0,
  12795. i;
  12796. for (i = 0; i < len; i++) {
  12797. if ((dontConvert && array1[i] !== array2[i]) ||
  12798. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  12799. diffs++;
  12800. }
  12801. }
  12802. return diffs + lengthDiff;
  12803. }
  12804. function warn(msg) {
  12805. if (hooks.suppressDeprecationWarnings === false &&
  12806. (typeof console !== 'undefined') && console.warn) {
  12807. console.warn('Deprecation warning: ' + msg);
  12808. }
  12809. }
  12810. function deprecate(msg, fn) {
  12811. var firstTime = true;
  12812. return extend(function () {
  12813. if (hooks.deprecationHandler != null) {
  12814. hooks.deprecationHandler(null, msg);
  12815. }
  12816. if (firstTime) {
  12817. var args = [];
  12818. var arg;
  12819. for (var i = 0; i < arguments.length; i++) {
  12820. arg = '';
  12821. if (typeof arguments[i] === 'object') {
  12822. arg += '\n[' + i + '] ';
  12823. for (var key in arguments[0]) {
  12824. arg += key + ': ' + arguments[0][key] + ', ';
  12825. }
  12826. arg = arg.slice(0, -2); // Remove trailing comma and space
  12827. } else {
  12828. arg = arguments[i];
  12829. }
  12830. args.push(arg);
  12831. }
  12832. warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
  12833. firstTime = false;
  12834. }
  12835. return fn.apply(this, arguments);
  12836. }, fn);
  12837. }
  12838. var deprecations = {};
  12839. function deprecateSimple(name, msg) {
  12840. if (hooks.deprecationHandler != null) {
  12841. hooks.deprecationHandler(name, msg);
  12842. }
  12843. if (!deprecations[name]) {
  12844. warn(msg);
  12845. deprecations[name] = true;
  12846. }
  12847. }
  12848. hooks.suppressDeprecationWarnings = false;
  12849. hooks.deprecationHandler = null;
  12850. function isFunction(input) {
  12851. return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
  12852. }
  12853. function set (config) {
  12854. var prop, i;
  12855. for (i in config) {
  12856. prop = config[i];
  12857. if (isFunction(prop)) {
  12858. this[i] = prop;
  12859. } else {
  12860. this['_' + i] = prop;
  12861. }
  12862. }
  12863. this._config = config;
  12864. // Lenient ordinal parsing accepts just a number in addition to
  12865. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  12866. // TODO: Remove "ordinalParse" fallback in next major release.
  12867. this._dayOfMonthOrdinalParseLenient = new RegExp(
  12868. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  12869. '|' + (/\d{1,2}/).source);
  12870. }
  12871. function mergeConfigs(parentConfig, childConfig) {
  12872. var res = extend({}, parentConfig), prop;
  12873. for (prop in childConfig) {
  12874. if (hasOwnProp(childConfig, prop)) {
  12875. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  12876. res[prop] = {};
  12877. extend(res[prop], parentConfig[prop]);
  12878. extend(res[prop], childConfig[prop]);
  12879. } else if (childConfig[prop] != null) {
  12880. res[prop] = childConfig[prop];
  12881. } else {
  12882. delete res[prop];
  12883. }
  12884. }
  12885. }
  12886. for (prop in parentConfig) {
  12887. if (hasOwnProp(parentConfig, prop) &&
  12888. !hasOwnProp(childConfig, prop) &&
  12889. isObject(parentConfig[prop])) {
  12890. // make sure changes to properties don't modify parent config
  12891. res[prop] = extend({}, res[prop]);
  12892. }
  12893. }
  12894. return res;
  12895. }
  12896. function Locale(config) {
  12897. if (config != null) {
  12898. this.set(config);
  12899. }
  12900. }
  12901. var keys;
  12902. if (Object.keys) {
  12903. keys = Object.keys;
  12904. } else {
  12905. keys = function (obj) {
  12906. var i, res = [];
  12907. for (i in obj) {
  12908. if (hasOwnProp(obj, i)) {
  12909. res.push(i);
  12910. }
  12911. }
  12912. return res;
  12913. };
  12914. }
  12915. var defaultCalendar = {
  12916. sameDay : '[Today at] LT',
  12917. nextDay : '[Tomorrow at] LT',
  12918. nextWeek : 'dddd [at] LT',
  12919. lastDay : '[Yesterday at] LT',
  12920. lastWeek : '[Last] dddd [at] LT',
  12921. sameElse : 'L'
  12922. };
  12923. function calendar (key, mom, now) {
  12924. var output = this._calendar[key] || this._calendar['sameElse'];
  12925. return isFunction(output) ? output.call(mom, now) : output;
  12926. }
  12927. var defaultLongDateFormat = {
  12928. LTS : 'h:mm:ss A',
  12929. LT : 'h:mm A',
  12930. L : 'MM/DD/YYYY',
  12931. LL : 'MMMM D, YYYY',
  12932. LLL : 'MMMM D, YYYY h:mm A',
  12933. LLLL : 'dddd, MMMM D, YYYY h:mm A'
  12934. };
  12935. function longDateFormat (key) {
  12936. var format = this._longDateFormat[key],
  12937. formatUpper = this._longDateFormat[key.toUpperCase()];
  12938. if (format || !formatUpper) {
  12939. return format;
  12940. }
  12941. this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
  12942. return val.slice(1);
  12943. });
  12944. return this._longDateFormat[key];
  12945. }
  12946. var defaultInvalidDate = 'Invalid date';
  12947. function invalidDate () {
  12948. return this._invalidDate;
  12949. }
  12950. var defaultOrdinal = '%d';
  12951. var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  12952. function ordinal (number) {
  12953. return this._ordinal.replace('%d', number);
  12954. }
  12955. var defaultRelativeTime = {
  12956. future : 'in %s',
  12957. past : '%s ago',
  12958. s : 'a few seconds',
  12959. ss : '%d seconds',
  12960. m : 'a minute',
  12961. mm : '%d minutes',
  12962. h : 'an hour',
  12963. hh : '%d hours',
  12964. d : 'a day',
  12965. dd : '%d days',
  12966. M : 'a month',
  12967. MM : '%d months',
  12968. y : 'a year',
  12969. yy : '%d years'
  12970. };
  12971. function relativeTime (number, withoutSuffix, string, isFuture) {
  12972. var output = this._relativeTime[string];
  12973. return (isFunction(output)) ?
  12974. output(number, withoutSuffix, string, isFuture) :
  12975. output.replace(/%d/i, number);
  12976. }
  12977. function pastFuture (diff, output) {
  12978. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  12979. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  12980. }
  12981. var aliases = {};
  12982. function addUnitAlias (unit, shorthand) {
  12983. var lowerCase = unit.toLowerCase();
  12984. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  12985. }
  12986. function normalizeUnits(units) {
  12987. return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
  12988. }
  12989. function normalizeObjectUnits(inputObject) {
  12990. var normalizedInput = {},
  12991. normalizedProp,
  12992. prop;
  12993. for (prop in inputObject) {
  12994. if (hasOwnProp(inputObject, prop)) {
  12995. normalizedProp = normalizeUnits(prop);
  12996. if (normalizedProp) {
  12997. normalizedInput[normalizedProp] = inputObject[prop];
  12998. }
  12999. }
  13000. }
  13001. return normalizedInput;
  13002. }
  13003. var priorities = {};
  13004. function addUnitPriority(unit, priority) {
  13005. priorities[unit] = priority;
  13006. }
  13007. function getPrioritizedUnits(unitsObj) {
  13008. var units = [];
  13009. for (var u in unitsObj) {
  13010. units.push({unit: u, priority: priorities[u]});
  13011. }
  13012. units.sort(function (a, b) {
  13013. return a.priority - b.priority;
  13014. });
  13015. return units;
  13016. }
  13017. function zeroFill(number, targetLength, forceSign) {
  13018. var absNumber = '' + Math.abs(number),
  13019. zerosToFill = targetLength - absNumber.length,
  13020. sign = number >= 0;
  13021. return (sign ? (forceSign ? '+' : '') : '-') +
  13022. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
  13023. }
  13024. 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;
  13025. var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  13026. var formatFunctions = {};
  13027. var formatTokenFunctions = {};
  13028. // token: 'M'
  13029. // padded: ['MM', 2]
  13030. // ordinal: 'Mo'
  13031. // callback: function () { this.month() + 1 }
  13032. function addFormatToken (token, padded, ordinal, callback) {
  13033. var func = callback;
  13034. if (typeof callback === 'string') {
  13035. func = function () {
  13036. return this[callback]();
  13037. };
  13038. }
  13039. if (token) {
  13040. formatTokenFunctions[token] = func;
  13041. }
  13042. if (padded) {
  13043. formatTokenFunctions[padded[0]] = function () {
  13044. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  13045. };
  13046. }
  13047. if (ordinal) {
  13048. formatTokenFunctions[ordinal] = function () {
  13049. return this.localeData().ordinal(func.apply(this, arguments), token);
  13050. };
  13051. }
  13052. }
  13053. function removeFormattingTokens(input) {
  13054. if (input.match(/\[[\s\S]/)) {
  13055. return input.replace(/^\[|\]$/g, '');
  13056. }
  13057. return input.replace(/\\/g, '');
  13058. }
  13059. function makeFormatFunction(format) {
  13060. var array = format.match(formattingTokens), i, length;
  13061. for (i = 0, length = array.length; i < length; i++) {
  13062. if (formatTokenFunctions[array[i]]) {
  13063. array[i] = formatTokenFunctions[array[i]];
  13064. } else {
  13065. array[i] = removeFormattingTokens(array[i]);
  13066. }
  13067. }
  13068. return function (mom) {
  13069. var output = '', i;
  13070. for (i = 0; i < length; i++) {
  13071. output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
  13072. }
  13073. return output;
  13074. };
  13075. }
  13076. // format date using native date object
  13077. function formatMoment(m, format) {
  13078. if (!m.isValid()) {
  13079. return m.localeData().invalidDate();
  13080. }
  13081. format = expandFormat(format, m.localeData());
  13082. formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
  13083. return formatFunctions[format](m);
  13084. }
  13085. function expandFormat(format, locale) {
  13086. var i = 5;
  13087. function replaceLongDateFormatTokens(input) {
  13088. return locale.longDateFormat(input) || input;
  13089. }
  13090. localFormattingTokens.lastIndex = 0;
  13091. while (i >= 0 && localFormattingTokens.test(format)) {
  13092. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  13093. localFormattingTokens.lastIndex = 0;
  13094. i -= 1;
  13095. }
  13096. return format;
  13097. }
  13098. var match1 = /\d/; // 0 - 9
  13099. var match2 = /\d\d/; // 00 - 99
  13100. var match3 = /\d{3}/; // 000 - 999
  13101. var match4 = /\d{4}/; // 0000 - 9999
  13102. var match6 = /[+-]?\d{6}/; // -999999 - 999999
  13103. var match1to2 = /\d\d?/; // 0 - 99
  13104. var match3to4 = /\d\d\d\d?/; // 999 - 9999
  13105. var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
  13106. var match1to3 = /\d{1,3}/; // 0 - 999
  13107. var match1to4 = /\d{1,4}/; // 0 - 9999
  13108. var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
  13109. var matchUnsigned = /\d+/; // 0 - inf
  13110. var matchSigned = /[+-]?\d+/; // -inf - inf
  13111. var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
  13112. var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  13113. var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
  13114. // any word (or two) characters or numbers including two/three word month in arabic.
  13115. // includes scottish gaelic two word and hyphenated months
  13116. 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;
  13117. var regexes = {};
  13118. function addRegexToken (token, regex, strictRegex) {
  13119. regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
  13120. return (isStrict && strictRegex) ? strictRegex : regex;
  13121. };
  13122. }
  13123. function getParseRegexForToken (token, config) {
  13124. if (!hasOwnProp(regexes, token)) {
  13125. return new RegExp(unescapeFormat(token));
  13126. }
  13127. return regexes[token](config._strict, config._locale);
  13128. }
  13129. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  13130. function unescapeFormat(s) {
  13131. return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  13132. return p1 || p2 || p3 || p4;
  13133. }));
  13134. }
  13135. function regexEscape(s) {
  13136. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  13137. }
  13138. var tokens = {};
  13139. function addParseToken (token, callback) {
  13140. var i, func = callback;
  13141. if (typeof token === 'string') {
  13142. token = [token];
  13143. }
  13144. if (isNumber(callback)) {
  13145. func = function (input, array) {
  13146. array[callback] = toInt(input);
  13147. };
  13148. }
  13149. for (i = 0; i < token.length; i++) {
  13150. tokens[token[i]] = func;
  13151. }
  13152. }
  13153. function addWeekParseToken (token, callback) {
  13154. addParseToken(token, function (input, array, config, token) {
  13155. config._w = config._w || {};
  13156. callback(input, config._w, config, token);
  13157. });
  13158. }
  13159. function addTimeToArrayFromToken(token, input, config) {
  13160. if (input != null && hasOwnProp(tokens, token)) {
  13161. tokens[token](input, config._a, config, token);
  13162. }
  13163. }
  13164. var YEAR = 0;
  13165. var MONTH = 1;
  13166. var DATE = 2;
  13167. var HOUR = 3;
  13168. var MINUTE = 4;
  13169. var SECOND = 5;
  13170. var MILLISECOND = 6;
  13171. var WEEK = 7;
  13172. var WEEKDAY = 8;
  13173. // FORMATTING
  13174. addFormatToken('Y', 0, 0, function () {
  13175. var y = this.year();
  13176. return y <= 9999 ? '' + y : '+' + y;
  13177. });
  13178. addFormatToken(0, ['YY', 2], 0, function () {
  13179. return this.year() % 100;
  13180. });
  13181. addFormatToken(0, ['YYYY', 4], 0, 'year');
  13182. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  13183. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  13184. // ALIASES
  13185. addUnitAlias('year', 'y');
  13186. // PRIORITIES
  13187. addUnitPriority('year', 1);
  13188. // PARSING
  13189. addRegexToken('Y', matchSigned);
  13190. addRegexToken('YY', match1to2, match2);
  13191. addRegexToken('YYYY', match1to4, match4);
  13192. addRegexToken('YYYYY', match1to6, match6);
  13193. addRegexToken('YYYYYY', match1to6, match6);
  13194. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  13195. addParseToken('YYYY', function (input, array) {
  13196. array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  13197. });
  13198. addParseToken('YY', function (input, array) {
  13199. array[YEAR] = hooks.parseTwoDigitYear(input);
  13200. });
  13201. addParseToken('Y', function (input, array) {
  13202. array[YEAR] = parseInt(input, 10);
  13203. });
  13204. // HELPERS
  13205. function daysInYear(year) {
  13206. return isLeapYear(year) ? 366 : 365;
  13207. }
  13208. function isLeapYear(year) {
  13209. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  13210. }
  13211. // HOOKS
  13212. hooks.parseTwoDigitYear = function (input) {
  13213. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  13214. };
  13215. // MOMENTS
  13216. var getSetYear = makeGetSet('FullYear', true);
  13217. function getIsLeapYear () {
  13218. return isLeapYear(this.year());
  13219. }
  13220. function makeGetSet (unit, keepTime) {
  13221. return function (value) {
  13222. if (value != null) {
  13223. set$1(this, unit, value);
  13224. hooks.updateOffset(this, keepTime);
  13225. return this;
  13226. } else {
  13227. return get(this, unit);
  13228. }
  13229. };
  13230. }
  13231. function get (mom, unit) {
  13232. return mom.isValid() ?
  13233. mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
  13234. }
  13235. function set$1 (mom, unit, value) {
  13236. if (mom.isValid() && !isNaN(value)) {
  13237. if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
  13238. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
  13239. }
  13240. else {
  13241. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  13242. }
  13243. }
  13244. }
  13245. // MOMENTS
  13246. function stringGet (units) {
  13247. units = normalizeUnits(units);
  13248. if (isFunction(this[units])) {
  13249. return this[units]();
  13250. }
  13251. return this;
  13252. }
  13253. function stringSet (units, value) {
  13254. if (typeof units === 'object') {
  13255. units = normalizeObjectUnits(units);
  13256. var prioritized = getPrioritizedUnits(units);
  13257. for (var i = 0; i < prioritized.length; i++) {
  13258. this[prioritized[i].unit](units[prioritized[i].unit]);
  13259. }
  13260. } else {
  13261. units = normalizeUnits(units);
  13262. if (isFunction(this[units])) {
  13263. return this[units](value);
  13264. }
  13265. }
  13266. return this;
  13267. }
  13268. function mod(n, x) {
  13269. return ((n % x) + x) % x;
  13270. }
  13271. var indexOf;
  13272. if (Array.prototype.indexOf) {
  13273. indexOf = Array.prototype.indexOf;
  13274. } else {
  13275. indexOf = function (o) {
  13276. // I know
  13277. var i;
  13278. for (i = 0; i < this.length; ++i) {
  13279. if (this[i] === o) {
  13280. return i;
  13281. }
  13282. }
  13283. return -1;
  13284. };
  13285. }
  13286. function daysInMonth(year, month) {
  13287. if (isNaN(year) || isNaN(month)) {
  13288. return NaN;
  13289. }
  13290. var modMonth = mod(month, 12);
  13291. year += (month - modMonth) / 12;
  13292. return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
  13293. }
  13294. // FORMATTING
  13295. addFormatToken('M', ['MM', 2], 'Mo', function () {
  13296. return this.month() + 1;
  13297. });
  13298. addFormatToken('MMM', 0, 0, function (format) {
  13299. return this.localeData().monthsShort(this, format);
  13300. });
  13301. addFormatToken('MMMM', 0, 0, function (format) {
  13302. return this.localeData().months(this, format);
  13303. });
  13304. // ALIASES
  13305. addUnitAlias('month', 'M');
  13306. // PRIORITY
  13307. addUnitPriority('month', 8);
  13308. // PARSING
  13309. addRegexToken('M', match1to2);
  13310. addRegexToken('MM', match1to2, match2);
  13311. addRegexToken('MMM', function (isStrict, locale) {
  13312. return locale.monthsShortRegex(isStrict);
  13313. });
  13314. addRegexToken('MMMM', function (isStrict, locale) {
  13315. return locale.monthsRegex(isStrict);
  13316. });
  13317. addParseToken(['M', 'MM'], function (input, array) {
  13318. array[MONTH] = toInt(input) - 1;
  13319. });
  13320. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  13321. var month = config._locale.monthsParse(input, token, config._strict);
  13322. // if we didn't find a month name, mark the date as invalid.
  13323. if (month != null) {
  13324. array[MONTH] = month;
  13325. } else {
  13326. getParsingFlags(config).invalidMonth = input;
  13327. }
  13328. });
  13329. // LOCALES
  13330. var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
  13331. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
  13332. function localeMonths (m, format) {
  13333. if (!m) {
  13334. return isArray(this._months) ? this._months :
  13335. this._months['standalone'];
  13336. }
  13337. return isArray(this._months) ? this._months[m.month()] :
  13338. this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
  13339. }
  13340. var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
  13341. function localeMonthsShort (m, format) {
  13342. if (!m) {
  13343. return isArray(this._monthsShort) ? this._monthsShort :
  13344. this._monthsShort['standalone'];
  13345. }
  13346. return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
  13347. this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
  13348. }
  13349. function handleStrictParse(monthName, format, strict) {
  13350. var i, ii, mom, llc = monthName.toLocaleLowerCase();
  13351. if (!this._monthsParse) {
  13352. // this is not used
  13353. this._monthsParse = [];
  13354. this._longMonthsParse = [];
  13355. this._shortMonthsParse = [];
  13356. for (i = 0; i < 12; ++i) {
  13357. mom = createUTC([2000, i]);
  13358. this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
  13359. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  13360. }
  13361. }
  13362. if (strict) {
  13363. if (format === 'MMM') {
  13364. ii = indexOf.call(this._shortMonthsParse, llc);
  13365. return ii !== -1 ? ii : null;
  13366. } else {
  13367. ii = indexOf.call(this._longMonthsParse, llc);
  13368. return ii !== -1 ? ii : null;
  13369. }
  13370. } else {
  13371. if (format === 'MMM') {
  13372. ii = indexOf.call(this._shortMonthsParse, llc);
  13373. if (ii !== -1) {
  13374. return ii;
  13375. }
  13376. ii = indexOf.call(this._longMonthsParse, llc);
  13377. return ii !== -1 ? ii : null;
  13378. } else {
  13379. ii = indexOf.call(this._longMonthsParse, llc);
  13380. if (ii !== -1) {
  13381. return ii;
  13382. }
  13383. ii = indexOf.call(this._shortMonthsParse, llc);
  13384. return ii !== -1 ? ii : null;
  13385. }
  13386. }
  13387. }
  13388. function localeMonthsParse (monthName, format, strict) {
  13389. var i, mom, regex;
  13390. if (this._monthsParseExact) {
  13391. return handleStrictParse.call(this, monthName, format, strict);
  13392. }
  13393. if (!this._monthsParse) {
  13394. this._monthsParse = [];
  13395. this._longMonthsParse = [];
  13396. this._shortMonthsParse = [];
  13397. }
  13398. // TODO: add sorting
  13399. // Sorting makes sure if one month (or abbr) is a prefix of another
  13400. // see sorting in computeMonthsParse
  13401. for (i = 0; i < 12; i++) {
  13402. // make the regex if we don't have it already
  13403. mom = createUTC([2000, i]);
  13404. if (strict && !this._longMonthsParse[i]) {
  13405. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  13406. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  13407. }
  13408. if (!strict && !this._monthsParse[i]) {
  13409. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  13410. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13411. }
  13412. // test the regex
  13413. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  13414. return i;
  13415. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  13416. return i;
  13417. } else if (!strict && this._monthsParse[i].test(monthName)) {
  13418. return i;
  13419. }
  13420. }
  13421. }
  13422. // MOMENTS
  13423. function setMonth (mom, value) {
  13424. var dayOfMonth;
  13425. if (!mom.isValid()) {
  13426. // No op
  13427. return mom;
  13428. }
  13429. if (typeof value === 'string') {
  13430. if (/^\d+$/.test(value)) {
  13431. value = toInt(value);
  13432. } else {
  13433. value = mom.localeData().monthsParse(value);
  13434. // TODO: Another silent failure?
  13435. if (!isNumber(value)) {
  13436. return mom;
  13437. }
  13438. }
  13439. }
  13440. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  13441. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  13442. return mom;
  13443. }
  13444. function getSetMonth (value) {
  13445. if (value != null) {
  13446. setMonth(this, value);
  13447. hooks.updateOffset(this, true);
  13448. return this;
  13449. } else {
  13450. return get(this, 'Month');
  13451. }
  13452. }
  13453. function getDaysInMonth () {
  13454. return daysInMonth(this.year(), this.month());
  13455. }
  13456. var defaultMonthsShortRegex = matchWord;
  13457. function monthsShortRegex (isStrict) {
  13458. if (this._monthsParseExact) {
  13459. if (!hasOwnProp(this, '_monthsRegex')) {
  13460. computeMonthsParse.call(this);
  13461. }
  13462. if (isStrict) {
  13463. return this._monthsShortStrictRegex;
  13464. } else {
  13465. return this._monthsShortRegex;
  13466. }
  13467. } else {
  13468. if (!hasOwnProp(this, '_monthsShortRegex')) {
  13469. this._monthsShortRegex = defaultMonthsShortRegex;
  13470. }
  13471. return this._monthsShortStrictRegex && isStrict ?
  13472. this._monthsShortStrictRegex : this._monthsShortRegex;
  13473. }
  13474. }
  13475. var defaultMonthsRegex = matchWord;
  13476. function monthsRegex (isStrict) {
  13477. if (this._monthsParseExact) {
  13478. if (!hasOwnProp(this, '_monthsRegex')) {
  13479. computeMonthsParse.call(this);
  13480. }
  13481. if (isStrict) {
  13482. return this._monthsStrictRegex;
  13483. } else {
  13484. return this._monthsRegex;
  13485. }
  13486. } else {
  13487. if (!hasOwnProp(this, '_monthsRegex')) {
  13488. this._monthsRegex = defaultMonthsRegex;
  13489. }
  13490. return this._monthsStrictRegex && isStrict ?
  13491. this._monthsStrictRegex : this._monthsRegex;
  13492. }
  13493. }
  13494. function computeMonthsParse () {
  13495. function cmpLenRev(a, b) {
  13496. return b.length - a.length;
  13497. }
  13498. var shortPieces = [], longPieces = [], mixedPieces = [],
  13499. i, mom;
  13500. for (i = 0; i < 12; i++) {
  13501. // make the regex if we don't have it already
  13502. mom = createUTC([2000, i]);
  13503. shortPieces.push(this.monthsShort(mom, ''));
  13504. longPieces.push(this.months(mom, ''));
  13505. mixedPieces.push(this.months(mom, ''));
  13506. mixedPieces.push(this.monthsShort(mom, ''));
  13507. }
  13508. // Sorting makes sure if one month (or abbr) is a prefix of another it
  13509. // will match the longer piece.
  13510. shortPieces.sort(cmpLenRev);
  13511. longPieces.sort(cmpLenRev);
  13512. mixedPieces.sort(cmpLenRev);
  13513. for (i = 0; i < 12; i++) {
  13514. shortPieces[i] = regexEscape(shortPieces[i]);
  13515. longPieces[i] = regexEscape(longPieces[i]);
  13516. }
  13517. for (i = 0; i < 24; i++) {
  13518. mixedPieces[i] = regexEscape(mixedPieces[i]);
  13519. }
  13520. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  13521. this._monthsShortRegex = this._monthsRegex;
  13522. this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  13523. this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  13524. }
  13525. function createDate (y, m, d, h, M, s, ms) {
  13526. // can't just apply() to create a date:
  13527. // https://stackoverflow.com/q/181348
  13528. var date;
  13529. // the date constructor remaps years 0-99 to 1900-1999
  13530. if (y < 100 && y >= 0) {
  13531. // preserve leap years using a full 400 year cycle, then reset
  13532. date = new Date(y + 400, m, d, h, M, s, ms);
  13533. if (isFinite(date.getFullYear())) {
  13534. date.setFullYear(y);
  13535. }
  13536. } else {
  13537. date = new Date(y, m, d, h, M, s, ms);
  13538. }
  13539. return date;
  13540. }
  13541. function createUTCDate (y) {
  13542. var date;
  13543. // the Date.UTC function remaps years 0-99 to 1900-1999
  13544. if (y < 100 && y >= 0) {
  13545. var args = Array.prototype.slice.call(arguments);
  13546. // preserve leap years using a full 400 year cycle, then reset
  13547. args[0] = y + 400;
  13548. date = new Date(Date.UTC.apply(null, args));
  13549. if (isFinite(date.getUTCFullYear())) {
  13550. date.setUTCFullYear(y);
  13551. }
  13552. } else {
  13553. date = new Date(Date.UTC.apply(null, arguments));
  13554. }
  13555. return date;
  13556. }
  13557. // start-of-first-week - start-of-year
  13558. function firstWeekOffset(year, dow, doy) {
  13559. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  13560. fwd = 7 + dow - doy,
  13561. // first-week day local weekday -- which local weekday is fwd
  13562. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  13563. return -fwdlw + fwd - 1;
  13564. }
  13565. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  13566. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  13567. var localWeekday = (7 + weekday - dow) % 7,
  13568. weekOffset = firstWeekOffset(year, dow, doy),
  13569. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  13570. resYear, resDayOfYear;
  13571. if (dayOfYear <= 0) {
  13572. resYear = year - 1;
  13573. resDayOfYear = daysInYear(resYear) + dayOfYear;
  13574. } else if (dayOfYear > daysInYear(year)) {
  13575. resYear = year + 1;
  13576. resDayOfYear = dayOfYear - daysInYear(year);
  13577. } else {
  13578. resYear = year;
  13579. resDayOfYear = dayOfYear;
  13580. }
  13581. return {
  13582. year: resYear,
  13583. dayOfYear: resDayOfYear
  13584. };
  13585. }
  13586. function weekOfYear(mom, dow, doy) {
  13587. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  13588. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  13589. resWeek, resYear;
  13590. if (week < 1) {
  13591. resYear = mom.year() - 1;
  13592. resWeek = week + weeksInYear(resYear, dow, doy);
  13593. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  13594. resWeek = week - weeksInYear(mom.year(), dow, doy);
  13595. resYear = mom.year() + 1;
  13596. } else {
  13597. resYear = mom.year();
  13598. resWeek = week;
  13599. }
  13600. return {
  13601. week: resWeek,
  13602. year: resYear
  13603. };
  13604. }
  13605. function weeksInYear(year, dow, doy) {
  13606. var weekOffset = firstWeekOffset(year, dow, doy),
  13607. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  13608. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  13609. }
  13610. // FORMATTING
  13611. addFormatToken('w', ['ww', 2], 'wo', 'week');
  13612. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  13613. // ALIASES
  13614. addUnitAlias('week', 'w');
  13615. addUnitAlias('isoWeek', 'W');
  13616. // PRIORITIES
  13617. addUnitPriority('week', 5);
  13618. addUnitPriority('isoWeek', 5);
  13619. // PARSING
  13620. addRegexToken('w', match1to2);
  13621. addRegexToken('ww', match1to2, match2);
  13622. addRegexToken('W', match1to2);
  13623. addRegexToken('WW', match1to2, match2);
  13624. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
  13625. week[token.substr(0, 1)] = toInt(input);
  13626. });
  13627. // HELPERS
  13628. // LOCALES
  13629. function localeWeek (mom) {
  13630. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  13631. }
  13632. var defaultLocaleWeek = {
  13633. dow : 0, // Sunday is the first day of the week.
  13634. doy : 6 // The week that contains Jan 6th is the first week of the year.
  13635. };
  13636. function localeFirstDayOfWeek () {
  13637. return this._week.dow;
  13638. }
  13639. function localeFirstDayOfYear () {
  13640. return this._week.doy;
  13641. }
  13642. // MOMENTS
  13643. function getSetWeek (input) {
  13644. var week = this.localeData().week(this);
  13645. return input == null ? week : this.add((input - week) * 7, 'd');
  13646. }
  13647. function getSetISOWeek (input) {
  13648. var week = weekOfYear(this, 1, 4).week;
  13649. return input == null ? week : this.add((input - week) * 7, 'd');
  13650. }
  13651. // FORMATTING
  13652. addFormatToken('d', 0, 'do', 'day');
  13653. addFormatToken('dd', 0, 0, function (format) {
  13654. return this.localeData().weekdaysMin(this, format);
  13655. });
  13656. addFormatToken('ddd', 0, 0, function (format) {
  13657. return this.localeData().weekdaysShort(this, format);
  13658. });
  13659. addFormatToken('dddd', 0, 0, function (format) {
  13660. return this.localeData().weekdays(this, format);
  13661. });
  13662. addFormatToken('e', 0, 0, 'weekday');
  13663. addFormatToken('E', 0, 0, 'isoWeekday');
  13664. // ALIASES
  13665. addUnitAlias('day', 'd');
  13666. addUnitAlias('weekday', 'e');
  13667. addUnitAlias('isoWeekday', 'E');
  13668. // PRIORITY
  13669. addUnitPriority('day', 11);
  13670. addUnitPriority('weekday', 11);
  13671. addUnitPriority('isoWeekday', 11);
  13672. // PARSING
  13673. addRegexToken('d', match1to2);
  13674. addRegexToken('e', match1to2);
  13675. addRegexToken('E', match1to2);
  13676. addRegexToken('dd', function (isStrict, locale) {
  13677. return locale.weekdaysMinRegex(isStrict);
  13678. });
  13679. addRegexToken('ddd', function (isStrict, locale) {
  13680. return locale.weekdaysShortRegex(isStrict);
  13681. });
  13682. addRegexToken('dddd', function (isStrict, locale) {
  13683. return locale.weekdaysRegex(isStrict);
  13684. });
  13685. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  13686. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  13687. // if we didn't get a weekday name, mark the date as invalid
  13688. if (weekday != null) {
  13689. week.d = weekday;
  13690. } else {
  13691. getParsingFlags(config).invalidWeekday = input;
  13692. }
  13693. });
  13694. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  13695. week[token] = toInt(input);
  13696. });
  13697. // HELPERS
  13698. function parseWeekday(input, locale) {
  13699. if (typeof input !== 'string') {
  13700. return input;
  13701. }
  13702. if (!isNaN(input)) {
  13703. return parseInt(input, 10);
  13704. }
  13705. input = locale.weekdaysParse(input);
  13706. if (typeof input === 'number') {
  13707. return input;
  13708. }
  13709. return null;
  13710. }
  13711. function parseIsoWeekday(input, locale) {
  13712. if (typeof input === 'string') {
  13713. return locale.weekdaysParse(input) % 7 || 7;
  13714. }
  13715. return isNaN(input) ? null : input;
  13716. }
  13717. // LOCALES
  13718. function shiftWeekdays (ws, n) {
  13719. return ws.slice(n, 7).concat(ws.slice(0, n));
  13720. }
  13721. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
  13722. function localeWeekdays (m, format) {
  13723. var weekdays = isArray(this._weekdays) ? this._weekdays :
  13724. this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone'];
  13725. return (m === true) ? shiftWeekdays(weekdays, this._week.dow)
  13726. : (m) ? weekdays[m.day()] : weekdays;
  13727. }
  13728. var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
  13729. function localeWeekdaysShort (m) {
  13730. return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  13731. : (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
  13732. }
  13733. var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
  13734. function localeWeekdaysMin (m) {
  13735. return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  13736. : (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
  13737. }
  13738. function handleStrictParse$1(weekdayName, format, strict) {
  13739. var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
  13740. if (!this._weekdaysParse) {
  13741. this._weekdaysParse = [];
  13742. this._shortWeekdaysParse = [];
  13743. this._minWeekdaysParse = [];
  13744. for (i = 0; i < 7; ++i) {
  13745. mom = createUTC([2000, 1]).day(i);
  13746. this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
  13747. this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
  13748. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  13749. }
  13750. }
  13751. if (strict) {
  13752. if (format === 'dddd') {
  13753. ii = indexOf.call(this._weekdaysParse, llc);
  13754. return ii !== -1 ? ii : null;
  13755. } else if (format === 'ddd') {
  13756. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13757. return ii !== -1 ? ii : null;
  13758. } else {
  13759. ii = indexOf.call(this._minWeekdaysParse, llc);
  13760. return ii !== -1 ? ii : null;
  13761. }
  13762. } else {
  13763. if (format === 'dddd') {
  13764. ii = indexOf.call(this._weekdaysParse, llc);
  13765. if (ii !== -1) {
  13766. return ii;
  13767. }
  13768. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13769. if (ii !== -1) {
  13770. return ii;
  13771. }
  13772. ii = indexOf.call(this._minWeekdaysParse, llc);
  13773. return ii !== -1 ? ii : null;
  13774. } else if (format === 'ddd') {
  13775. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13776. if (ii !== -1) {
  13777. return ii;
  13778. }
  13779. ii = indexOf.call(this._weekdaysParse, llc);
  13780. if (ii !== -1) {
  13781. return ii;
  13782. }
  13783. ii = indexOf.call(this._minWeekdaysParse, llc);
  13784. return ii !== -1 ? ii : null;
  13785. } else {
  13786. ii = indexOf.call(this._minWeekdaysParse, llc);
  13787. if (ii !== -1) {
  13788. return ii;
  13789. }
  13790. ii = indexOf.call(this._weekdaysParse, llc);
  13791. if (ii !== -1) {
  13792. return ii;
  13793. }
  13794. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13795. return ii !== -1 ? ii : null;
  13796. }
  13797. }
  13798. }
  13799. function localeWeekdaysParse (weekdayName, format, strict) {
  13800. var i, mom, regex;
  13801. if (this._weekdaysParseExact) {
  13802. return handleStrictParse$1.call(this, weekdayName, format, strict);
  13803. }
  13804. if (!this._weekdaysParse) {
  13805. this._weekdaysParse = [];
  13806. this._minWeekdaysParse = [];
  13807. this._shortWeekdaysParse = [];
  13808. this._fullWeekdaysParse = [];
  13809. }
  13810. for (i = 0; i < 7; i++) {
  13811. // make the regex if we don't have it already
  13812. mom = createUTC([2000, 1]).day(i);
  13813. if (strict && !this._fullWeekdaysParse[i]) {
  13814. this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
  13815. this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
  13816. this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
  13817. }
  13818. if (!this._weekdaysParse[i]) {
  13819. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  13820. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13821. }
  13822. // test the regex
  13823. if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
  13824. return i;
  13825. } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
  13826. return i;
  13827. } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
  13828. return i;
  13829. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  13830. return i;
  13831. }
  13832. }
  13833. }
  13834. // MOMENTS
  13835. function getSetDayOfWeek (input) {
  13836. if (!this.isValid()) {
  13837. return input != null ? this : NaN;
  13838. }
  13839. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  13840. if (input != null) {
  13841. input = parseWeekday(input, this.localeData());
  13842. return this.add(input - day, 'd');
  13843. } else {
  13844. return day;
  13845. }
  13846. }
  13847. function getSetLocaleDayOfWeek (input) {
  13848. if (!this.isValid()) {
  13849. return input != null ? this : NaN;
  13850. }
  13851. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  13852. return input == null ? weekday : this.add(input - weekday, 'd');
  13853. }
  13854. function getSetISODayOfWeek (input) {
  13855. if (!this.isValid()) {
  13856. return input != null ? this : NaN;
  13857. }
  13858. // behaves the same as moment#day except
  13859. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  13860. // as a setter, sunday should belong to the previous week.
  13861. if (input != null) {
  13862. var weekday = parseIsoWeekday(input, this.localeData());
  13863. return this.day(this.day() % 7 ? weekday : weekday - 7);
  13864. } else {
  13865. return this.day() || 7;
  13866. }
  13867. }
  13868. var defaultWeekdaysRegex = matchWord;
  13869. function weekdaysRegex (isStrict) {
  13870. if (this._weekdaysParseExact) {
  13871. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13872. computeWeekdaysParse.call(this);
  13873. }
  13874. if (isStrict) {
  13875. return this._weekdaysStrictRegex;
  13876. } else {
  13877. return this._weekdaysRegex;
  13878. }
  13879. } else {
  13880. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13881. this._weekdaysRegex = defaultWeekdaysRegex;
  13882. }
  13883. return this._weekdaysStrictRegex && isStrict ?
  13884. this._weekdaysStrictRegex : this._weekdaysRegex;
  13885. }
  13886. }
  13887. var defaultWeekdaysShortRegex = matchWord;
  13888. function weekdaysShortRegex (isStrict) {
  13889. if (this._weekdaysParseExact) {
  13890. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13891. computeWeekdaysParse.call(this);
  13892. }
  13893. if (isStrict) {
  13894. return this._weekdaysShortStrictRegex;
  13895. } else {
  13896. return this._weekdaysShortRegex;
  13897. }
  13898. } else {
  13899. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  13900. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  13901. }
  13902. return this._weekdaysShortStrictRegex && isStrict ?
  13903. this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
  13904. }
  13905. }
  13906. var defaultWeekdaysMinRegex = matchWord;
  13907. function weekdaysMinRegex (isStrict) {
  13908. if (this._weekdaysParseExact) {
  13909. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13910. computeWeekdaysParse.call(this);
  13911. }
  13912. if (isStrict) {
  13913. return this._weekdaysMinStrictRegex;
  13914. } else {
  13915. return this._weekdaysMinRegex;
  13916. }
  13917. } else {
  13918. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  13919. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  13920. }
  13921. return this._weekdaysMinStrictRegex && isStrict ?
  13922. this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
  13923. }
  13924. }
  13925. function computeWeekdaysParse () {
  13926. function cmpLenRev(a, b) {
  13927. return b.length - a.length;
  13928. }
  13929. var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
  13930. i, mom, minp, shortp, longp;
  13931. for (i = 0; i < 7; i++) {
  13932. // make the regex if we don't have it already
  13933. mom = createUTC([2000, 1]).day(i);
  13934. minp = this.weekdaysMin(mom, '');
  13935. shortp = this.weekdaysShort(mom, '');
  13936. longp = this.weekdays(mom, '');
  13937. minPieces.push(minp);
  13938. shortPieces.push(shortp);
  13939. longPieces.push(longp);
  13940. mixedPieces.push(minp);
  13941. mixedPieces.push(shortp);
  13942. mixedPieces.push(longp);
  13943. }
  13944. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  13945. // will match the longer piece.
  13946. minPieces.sort(cmpLenRev);
  13947. shortPieces.sort(cmpLenRev);
  13948. longPieces.sort(cmpLenRev);
  13949. mixedPieces.sort(cmpLenRev);
  13950. for (i = 0; i < 7; i++) {
  13951. shortPieces[i] = regexEscape(shortPieces[i]);
  13952. longPieces[i] = regexEscape(longPieces[i]);
  13953. mixedPieces[i] = regexEscape(mixedPieces[i]);
  13954. }
  13955. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  13956. this._weekdaysShortRegex = this._weekdaysRegex;
  13957. this._weekdaysMinRegex = this._weekdaysRegex;
  13958. this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  13959. this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  13960. this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
  13961. }
  13962. // FORMATTING
  13963. function hFormat() {
  13964. return this.hours() % 12 || 12;
  13965. }
  13966. function kFormat() {
  13967. return this.hours() || 24;
  13968. }
  13969. addFormatToken('H', ['HH', 2], 0, 'hour');
  13970. addFormatToken('h', ['hh', 2], 0, hFormat);
  13971. addFormatToken('k', ['kk', 2], 0, kFormat);
  13972. addFormatToken('hmm', 0, 0, function () {
  13973. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  13974. });
  13975. addFormatToken('hmmss', 0, 0, function () {
  13976. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
  13977. zeroFill(this.seconds(), 2);
  13978. });
  13979. addFormatToken('Hmm', 0, 0, function () {
  13980. return '' + this.hours() + zeroFill(this.minutes(), 2);
  13981. });
  13982. addFormatToken('Hmmss', 0, 0, function () {
  13983. return '' + this.hours() + zeroFill(this.minutes(), 2) +
  13984. zeroFill(this.seconds(), 2);
  13985. });
  13986. function meridiem (token, lowercase) {
  13987. addFormatToken(token, 0, 0, function () {
  13988. return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
  13989. });
  13990. }
  13991. meridiem('a', true);
  13992. meridiem('A', false);
  13993. // ALIASES
  13994. addUnitAlias('hour', 'h');
  13995. // PRIORITY
  13996. addUnitPriority('hour', 13);
  13997. // PARSING
  13998. function matchMeridiem (isStrict, locale) {
  13999. return locale._meridiemParse;
  14000. }
  14001. addRegexToken('a', matchMeridiem);
  14002. addRegexToken('A', matchMeridiem);
  14003. addRegexToken('H', match1to2);
  14004. addRegexToken('h', match1to2);
  14005. addRegexToken('k', match1to2);
  14006. addRegexToken('HH', match1to2, match2);
  14007. addRegexToken('hh', match1to2, match2);
  14008. addRegexToken('kk', match1to2, match2);
  14009. addRegexToken('hmm', match3to4);
  14010. addRegexToken('hmmss', match5to6);
  14011. addRegexToken('Hmm', match3to4);
  14012. addRegexToken('Hmmss', match5to6);
  14013. addParseToken(['H', 'HH'], HOUR);
  14014. addParseToken(['k', 'kk'], function (input, array, config) {
  14015. var kInput = toInt(input);
  14016. array[HOUR] = kInput === 24 ? 0 : kInput;
  14017. });
  14018. addParseToken(['a', 'A'], function (input, array, config) {
  14019. config._isPm = config._locale.isPM(input);
  14020. config._meridiem = input;
  14021. });
  14022. addParseToken(['h', 'hh'], function (input, array, config) {
  14023. array[HOUR] = toInt(input);
  14024. getParsingFlags(config).bigHour = true;
  14025. });
  14026. addParseToken('hmm', function (input, array, config) {
  14027. var pos = input.length - 2;
  14028. array[HOUR] = toInt(input.substr(0, pos));
  14029. array[MINUTE] = toInt(input.substr(pos));
  14030. getParsingFlags(config).bigHour = true;
  14031. });
  14032. addParseToken('hmmss', function (input, array, config) {
  14033. var pos1 = input.length - 4;
  14034. var pos2 = input.length - 2;
  14035. array[HOUR] = toInt(input.substr(0, pos1));
  14036. array[MINUTE] = toInt(input.substr(pos1, 2));
  14037. array[SECOND] = toInt(input.substr(pos2));
  14038. getParsingFlags(config).bigHour = true;
  14039. });
  14040. addParseToken('Hmm', function (input, array, config) {
  14041. var pos = input.length - 2;
  14042. array[HOUR] = toInt(input.substr(0, pos));
  14043. array[MINUTE] = toInt(input.substr(pos));
  14044. });
  14045. addParseToken('Hmmss', function (input, array, config) {
  14046. var pos1 = input.length - 4;
  14047. var pos2 = input.length - 2;
  14048. array[HOUR] = toInt(input.substr(0, pos1));
  14049. array[MINUTE] = toInt(input.substr(pos1, 2));
  14050. array[SECOND] = toInt(input.substr(pos2));
  14051. });
  14052. // LOCALES
  14053. function localeIsPM (input) {
  14054. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  14055. // Using charAt should be more compatible.
  14056. return ((input + '').toLowerCase().charAt(0) === 'p');
  14057. }
  14058. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  14059. function localeMeridiem (hours, minutes, isLower) {
  14060. if (hours > 11) {
  14061. return isLower ? 'pm' : 'PM';
  14062. } else {
  14063. return isLower ? 'am' : 'AM';
  14064. }
  14065. }
  14066. // MOMENTS
  14067. // Setting the hour should keep the time, because the user explicitly
  14068. // specified which hour they want. So trying to maintain the same hour (in
  14069. // a new timezone) makes sense. Adding/subtracting hours does not follow
  14070. // this rule.
  14071. var getSetHour = makeGetSet('Hours', true);
  14072. var baseConfig = {
  14073. calendar: defaultCalendar,
  14074. longDateFormat: defaultLongDateFormat,
  14075. invalidDate: defaultInvalidDate,
  14076. ordinal: defaultOrdinal,
  14077. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  14078. relativeTime: defaultRelativeTime,
  14079. months: defaultLocaleMonths,
  14080. monthsShort: defaultLocaleMonthsShort,
  14081. week: defaultLocaleWeek,
  14082. weekdays: defaultLocaleWeekdays,
  14083. weekdaysMin: defaultLocaleWeekdaysMin,
  14084. weekdaysShort: defaultLocaleWeekdaysShort,
  14085. meridiemParse: defaultLocaleMeridiemParse
  14086. };
  14087. // internal storage for locale config files
  14088. var locales = {};
  14089. var localeFamilies = {};
  14090. var globalLocale;
  14091. function normalizeLocale(key) {
  14092. return key ? key.toLowerCase().replace('_', '-') : key;
  14093. }
  14094. // pick the locale from the array
  14095. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  14096. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  14097. function chooseLocale(names) {
  14098. var i = 0, j, next, locale, split;
  14099. while (i < names.length) {
  14100. split = normalizeLocale(names[i]).split('-');
  14101. j = split.length;
  14102. next = normalizeLocale(names[i + 1]);
  14103. next = next ? next.split('-') : null;
  14104. while (j > 0) {
  14105. locale = loadLocale(split.slice(0, j).join('-'));
  14106. if (locale) {
  14107. return locale;
  14108. }
  14109. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  14110. //the next array item is better than a shallower substring of this one
  14111. break;
  14112. }
  14113. j--;
  14114. }
  14115. i++;
  14116. }
  14117. return globalLocale;
  14118. }
  14119. function loadLocale(name) {
  14120. var oldLocale = null;
  14121. // TODO: Find a better way to register and load all the locales in Node
  14122. if (!locales[name] && ('object' !== 'undefined') &&
  14123. module && module.exports) {
  14124. try {
  14125. oldLocale = globalLocale._abbr;
  14126. var aliasedRequire = commonjsRequire;
  14127. aliasedRequire('./locale/' + name);
  14128. getSetGlobalLocale(oldLocale);
  14129. } catch (e) {}
  14130. }
  14131. return locales[name];
  14132. }
  14133. // This function will load locale and then set the global locale. If
  14134. // no arguments are passed in, it will simply return the current global
  14135. // locale key.
  14136. function getSetGlobalLocale (key, values) {
  14137. var data;
  14138. if (key) {
  14139. if (isUndefined(values)) {
  14140. data = getLocale(key);
  14141. }
  14142. else {
  14143. data = defineLocale(key, values);
  14144. }
  14145. if (data) {
  14146. // moment.duration._locale = moment._locale = data;
  14147. globalLocale = data;
  14148. }
  14149. else {
  14150. if ((typeof console !== 'undefined') && console.warn) {
  14151. //warn user if arguments are passed but the locale could not be set
  14152. console.warn('Locale ' + key + ' not found. Did you forget to load it?');
  14153. }
  14154. }
  14155. }
  14156. return globalLocale._abbr;
  14157. }
  14158. function defineLocale (name, config) {
  14159. if (config !== null) {
  14160. var locale, parentConfig = baseConfig;
  14161. config.abbr = name;
  14162. if (locales[name] != null) {
  14163. deprecateSimple('defineLocaleOverride',
  14164. 'use moment.updateLocale(localeName, config) to change ' +
  14165. 'an existing locale. moment.defineLocale(localeName, ' +
  14166. 'config) should only be used for creating a new locale ' +
  14167. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
  14168. parentConfig = locales[name]._config;
  14169. } else if (config.parentLocale != null) {
  14170. if (locales[config.parentLocale] != null) {
  14171. parentConfig = locales[config.parentLocale]._config;
  14172. } else {
  14173. locale = loadLocale(config.parentLocale);
  14174. if (locale != null) {
  14175. parentConfig = locale._config;
  14176. } else {
  14177. if (!localeFamilies[config.parentLocale]) {
  14178. localeFamilies[config.parentLocale] = [];
  14179. }
  14180. localeFamilies[config.parentLocale].push({
  14181. name: name,
  14182. config: config
  14183. });
  14184. return null;
  14185. }
  14186. }
  14187. }
  14188. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  14189. if (localeFamilies[name]) {
  14190. localeFamilies[name].forEach(function (x) {
  14191. defineLocale(x.name, x.config);
  14192. });
  14193. }
  14194. // backwards compat for now: also set the locale
  14195. // make sure we set the locale AFTER all child locales have been
  14196. // created, so we won't end up with the child locale set.
  14197. getSetGlobalLocale(name);
  14198. return locales[name];
  14199. } else {
  14200. // useful for testing
  14201. delete locales[name];
  14202. return null;
  14203. }
  14204. }
  14205. function updateLocale(name, config) {
  14206. if (config != null) {
  14207. var locale, tmpLocale, parentConfig = baseConfig;
  14208. // MERGE
  14209. tmpLocale = loadLocale(name);
  14210. if (tmpLocale != null) {
  14211. parentConfig = tmpLocale._config;
  14212. }
  14213. config = mergeConfigs(parentConfig, config);
  14214. locale = new Locale(config);
  14215. locale.parentLocale = locales[name];
  14216. locales[name] = locale;
  14217. // backwards compat for now: also set the locale
  14218. getSetGlobalLocale(name);
  14219. } else {
  14220. // pass null for config to unupdate, useful for tests
  14221. if (locales[name] != null) {
  14222. if (locales[name].parentLocale != null) {
  14223. locales[name] = locales[name].parentLocale;
  14224. } else if (locales[name] != null) {
  14225. delete locales[name];
  14226. }
  14227. }
  14228. }
  14229. return locales[name];
  14230. }
  14231. // returns locale data
  14232. function getLocale (key) {
  14233. var locale;
  14234. if (key && key._locale && key._locale._abbr) {
  14235. key = key._locale._abbr;
  14236. }
  14237. if (!key) {
  14238. return globalLocale;
  14239. }
  14240. if (!isArray(key)) {
  14241. //short-circuit everything else
  14242. locale = loadLocale(key);
  14243. if (locale) {
  14244. return locale;
  14245. }
  14246. key = [key];
  14247. }
  14248. return chooseLocale(key);
  14249. }
  14250. function listLocales() {
  14251. return keys(locales);
  14252. }
  14253. function checkOverflow (m) {
  14254. var overflow;
  14255. var a = m._a;
  14256. if (a && getParsingFlags(m).overflow === -2) {
  14257. overflow =
  14258. a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
  14259. a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
  14260. a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
  14261. a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
  14262. a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
  14263. a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
  14264. -1;
  14265. if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  14266. overflow = DATE;
  14267. }
  14268. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  14269. overflow = WEEK;
  14270. }
  14271. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  14272. overflow = WEEKDAY;
  14273. }
  14274. getParsingFlags(m).overflow = overflow;
  14275. }
  14276. return m;
  14277. }
  14278. // Pick the first defined of two or three arguments.
  14279. function defaults(a, b, c) {
  14280. if (a != null) {
  14281. return a;
  14282. }
  14283. if (b != null) {
  14284. return b;
  14285. }
  14286. return c;
  14287. }
  14288. function currentDateArray(config) {
  14289. // hooks is actually the exported moment object
  14290. var nowValue = new Date(hooks.now());
  14291. if (config._useUTC) {
  14292. return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
  14293. }
  14294. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  14295. }
  14296. // convert an array to a date.
  14297. // the array should mirror the parameters below
  14298. // note: all values past the year are optional and will default to the lowest possible value.
  14299. // [year, month, day , hour, minute, second, millisecond]
  14300. function configFromArray (config) {
  14301. var i, date, input = [], currentDate, expectedWeekday, yearToUse;
  14302. if (config._d) {
  14303. return;
  14304. }
  14305. currentDate = currentDateArray(config);
  14306. //compute day of the year from weeks and weekdays
  14307. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  14308. dayOfYearFromWeekInfo(config);
  14309. }
  14310. //if the day of the year is set, figure out what it is
  14311. if (config._dayOfYear != null) {
  14312. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  14313. if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
  14314. getParsingFlags(config)._overflowDayOfYear = true;
  14315. }
  14316. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  14317. config._a[MONTH] = date.getUTCMonth();
  14318. config._a[DATE] = date.getUTCDate();
  14319. }
  14320. // Default to current date.
  14321. // * if no year, month, day of month are given, default to today
  14322. // * if day of month is given, default month and year
  14323. // * if month is given, default only year
  14324. // * if year is given, don't default anything
  14325. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  14326. config._a[i] = input[i] = currentDate[i];
  14327. }
  14328. // Zero out whatever was not defaulted, including time
  14329. for (; i < 7; i++) {
  14330. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  14331. }
  14332. // Check for 24:00:00.000
  14333. if (config._a[HOUR] === 24 &&
  14334. config._a[MINUTE] === 0 &&
  14335. config._a[SECOND] === 0 &&
  14336. config._a[MILLISECOND] === 0) {
  14337. config._nextDay = true;
  14338. config._a[HOUR] = 0;
  14339. }
  14340. config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
  14341. expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
  14342. // Apply timezone offset from input. The actual utcOffset can be changed
  14343. // with parseZone.
  14344. if (config._tzm != null) {
  14345. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  14346. }
  14347. if (config._nextDay) {
  14348. config._a[HOUR] = 24;
  14349. }
  14350. // check for mismatching day of week
  14351. if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
  14352. getParsingFlags(config).weekdayMismatch = true;
  14353. }
  14354. }
  14355. function dayOfYearFromWeekInfo(config) {
  14356. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
  14357. w = config._w;
  14358. if (w.GG != null || w.W != null || w.E != null) {
  14359. dow = 1;
  14360. doy = 4;
  14361. // TODO: We need to take the current isoWeekYear, but that depends on
  14362. // how we interpret now (local, utc, fixed offset). So create
  14363. // a now version of current config (take local/utc/offset flags, and
  14364. // create now).
  14365. weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
  14366. week = defaults(w.W, 1);
  14367. weekday = defaults(w.E, 1);
  14368. if (weekday < 1 || weekday > 7) {
  14369. weekdayOverflow = true;
  14370. }
  14371. } else {
  14372. dow = config._locale._week.dow;
  14373. doy = config._locale._week.doy;
  14374. var curWeek = weekOfYear(createLocal(), dow, doy);
  14375. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  14376. // Default to current week.
  14377. week = defaults(w.w, curWeek.week);
  14378. if (w.d != null) {
  14379. // weekday -- low day numbers are considered next week
  14380. weekday = w.d;
  14381. if (weekday < 0 || weekday > 6) {
  14382. weekdayOverflow = true;
  14383. }
  14384. } else if (w.e != null) {
  14385. // local weekday -- counting starts from beginning of week
  14386. weekday = w.e + dow;
  14387. if (w.e < 0 || w.e > 6) {
  14388. weekdayOverflow = true;
  14389. }
  14390. } else {
  14391. // default to beginning of week
  14392. weekday = dow;
  14393. }
  14394. }
  14395. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  14396. getParsingFlags(config)._overflowWeeks = true;
  14397. } else if (weekdayOverflow != null) {
  14398. getParsingFlags(config)._overflowWeekday = true;
  14399. } else {
  14400. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  14401. config._a[YEAR] = temp.year;
  14402. config._dayOfYear = temp.dayOfYear;
  14403. }
  14404. }
  14405. // iso 8601 regex
  14406. // 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)
  14407. 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)?)?$/;
  14408. 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)?)?$/;
  14409. var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
  14410. var isoDates = [
  14411. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  14412. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  14413. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  14414. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  14415. ['YYYY-DDD', /\d{4}-\d{3}/],
  14416. ['YYYY-MM', /\d{4}-\d\d/, false],
  14417. ['YYYYYYMMDD', /[+-]\d{10}/],
  14418. ['YYYYMMDD', /\d{8}/],
  14419. // YYYYMM is NOT allowed by the standard
  14420. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  14421. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  14422. ['YYYYDDD', /\d{7}/]
  14423. ];
  14424. // iso time formats and regexes
  14425. var isoTimes = [
  14426. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  14427. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  14428. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  14429. ['HH:mm', /\d\d:\d\d/],
  14430. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  14431. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  14432. ['HHmmss', /\d\d\d\d\d\d/],
  14433. ['HHmm', /\d\d\d\d/],
  14434. ['HH', /\d\d/]
  14435. ];
  14436. var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
  14437. // date from iso format
  14438. function configFromISO(config) {
  14439. var i, l,
  14440. string = config._i,
  14441. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  14442. allowTime, dateFormat, timeFormat, tzFormat;
  14443. if (match) {
  14444. getParsingFlags(config).iso = true;
  14445. for (i = 0, l = isoDates.length; i < l; i++) {
  14446. if (isoDates[i][1].exec(match[1])) {
  14447. dateFormat = isoDates[i][0];
  14448. allowTime = isoDates[i][2] !== false;
  14449. break;
  14450. }
  14451. }
  14452. if (dateFormat == null) {
  14453. config._isValid = false;
  14454. return;
  14455. }
  14456. if (match[3]) {
  14457. for (i = 0, l = isoTimes.length; i < l; i++) {
  14458. if (isoTimes[i][1].exec(match[3])) {
  14459. // match[2] should be 'T' or space
  14460. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  14461. break;
  14462. }
  14463. }
  14464. if (timeFormat == null) {
  14465. config._isValid = false;
  14466. return;
  14467. }
  14468. }
  14469. if (!allowTime && timeFormat != null) {
  14470. config._isValid = false;
  14471. return;
  14472. }
  14473. if (match[4]) {
  14474. if (tzRegex.exec(match[4])) {
  14475. tzFormat = 'Z';
  14476. } else {
  14477. config._isValid = false;
  14478. return;
  14479. }
  14480. }
  14481. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  14482. configFromStringAndFormat(config);
  14483. } else {
  14484. config._isValid = false;
  14485. }
  14486. }
  14487. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  14488. 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}))$/;
  14489. function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  14490. var result = [
  14491. untruncateYear(yearStr),
  14492. defaultLocaleMonthsShort.indexOf(monthStr),
  14493. parseInt(dayStr, 10),
  14494. parseInt(hourStr, 10),
  14495. parseInt(minuteStr, 10)
  14496. ];
  14497. if (secondStr) {
  14498. result.push(parseInt(secondStr, 10));
  14499. }
  14500. return result;
  14501. }
  14502. function untruncateYear(yearStr) {
  14503. var year = parseInt(yearStr, 10);
  14504. if (year <= 49) {
  14505. return 2000 + year;
  14506. } else if (year <= 999) {
  14507. return 1900 + year;
  14508. }
  14509. return year;
  14510. }
  14511. function preprocessRFC2822(s) {
  14512. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  14513. return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  14514. }
  14515. function checkWeekday(weekdayStr, parsedInput, config) {
  14516. if (weekdayStr) {
  14517. // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
  14518. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  14519. weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
  14520. if (weekdayProvided !== weekdayActual) {
  14521. getParsingFlags(config).weekdayMismatch = true;
  14522. config._isValid = false;
  14523. return false;
  14524. }
  14525. }
  14526. return true;
  14527. }
  14528. var obsOffsets = {
  14529. UT: 0,
  14530. GMT: 0,
  14531. EDT: -4 * 60,
  14532. EST: -5 * 60,
  14533. CDT: -5 * 60,
  14534. CST: -6 * 60,
  14535. MDT: -6 * 60,
  14536. MST: -7 * 60,
  14537. PDT: -7 * 60,
  14538. PST: -8 * 60
  14539. };
  14540. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  14541. if (obsOffset) {
  14542. return obsOffsets[obsOffset];
  14543. } else if (militaryOffset) {
  14544. // the only allowed military tz is Z
  14545. return 0;
  14546. } else {
  14547. var hm = parseInt(numOffset, 10);
  14548. var m = hm % 100, h = (hm - m) / 100;
  14549. return h * 60 + m;
  14550. }
  14551. }
  14552. // date and time from ref 2822 format
  14553. function configFromRFC2822(config) {
  14554. var match = rfc2822.exec(preprocessRFC2822(config._i));
  14555. if (match) {
  14556. var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
  14557. if (!checkWeekday(match[1], parsedArray, config)) {
  14558. return;
  14559. }
  14560. config._a = parsedArray;
  14561. config._tzm = calculateOffset(match[8], match[9], match[10]);
  14562. config._d = createUTCDate.apply(null, config._a);
  14563. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  14564. getParsingFlags(config).rfc2822 = true;
  14565. } else {
  14566. config._isValid = false;
  14567. }
  14568. }
  14569. // date from iso format or fallback
  14570. function configFromString(config) {
  14571. var matched = aspNetJsonRegex.exec(config._i);
  14572. if (matched !== null) {
  14573. config._d = new Date(+matched[1]);
  14574. return;
  14575. }
  14576. configFromISO(config);
  14577. if (config._isValid === false) {
  14578. delete config._isValid;
  14579. } else {
  14580. return;
  14581. }
  14582. configFromRFC2822(config);
  14583. if (config._isValid === false) {
  14584. delete config._isValid;
  14585. } else {
  14586. return;
  14587. }
  14588. // Final attempt, use Input Fallback
  14589. hooks.createFromInputFallback(config);
  14590. }
  14591. hooks.createFromInputFallback = deprecate(
  14592. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  14593. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  14594. 'discouraged and will be removed in an upcoming major release. Please refer to ' +
  14595. 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  14596. function (config) {
  14597. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  14598. }
  14599. );
  14600. // constant that refers to the ISO standard
  14601. hooks.ISO_8601 = function () {};
  14602. // constant that refers to the RFC 2822 form
  14603. hooks.RFC_2822 = function () {};
  14604. // date from string and format string
  14605. function configFromStringAndFormat(config) {
  14606. // TODO: Move this to another part of the creation flow to prevent circular deps
  14607. if (config._f === hooks.ISO_8601) {
  14608. configFromISO(config);
  14609. return;
  14610. }
  14611. if (config._f === hooks.RFC_2822) {
  14612. configFromRFC2822(config);
  14613. return;
  14614. }
  14615. config._a = [];
  14616. getParsingFlags(config).empty = true;
  14617. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  14618. var string = '' + config._i,
  14619. i, parsedInput, tokens, token, skipped,
  14620. stringLength = string.length,
  14621. totalParsedInputLength = 0;
  14622. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  14623. for (i = 0; i < tokens.length; i++) {
  14624. token = tokens[i];
  14625. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  14626. // console.log('token', token, 'parsedInput', parsedInput,
  14627. // 'regex', getParseRegexForToken(token, config));
  14628. if (parsedInput) {
  14629. skipped = string.substr(0, string.indexOf(parsedInput));
  14630. if (skipped.length > 0) {
  14631. getParsingFlags(config).unusedInput.push(skipped);
  14632. }
  14633. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  14634. totalParsedInputLength += parsedInput.length;
  14635. }
  14636. // don't parse if it's not a known token
  14637. if (formatTokenFunctions[token]) {
  14638. if (parsedInput) {
  14639. getParsingFlags(config).empty = false;
  14640. }
  14641. else {
  14642. getParsingFlags(config).unusedTokens.push(token);
  14643. }
  14644. addTimeToArrayFromToken(token, parsedInput, config);
  14645. }
  14646. else if (config._strict && !parsedInput) {
  14647. getParsingFlags(config).unusedTokens.push(token);
  14648. }
  14649. }
  14650. // add remaining unparsed input length to the string
  14651. getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
  14652. if (string.length > 0) {
  14653. getParsingFlags(config).unusedInput.push(string);
  14654. }
  14655. // clear _12h flag if hour is <= 12
  14656. if (config._a[HOUR] <= 12 &&
  14657. getParsingFlags(config).bigHour === true &&
  14658. config._a[HOUR] > 0) {
  14659. getParsingFlags(config).bigHour = undefined;
  14660. }
  14661. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  14662. getParsingFlags(config).meridiem = config._meridiem;
  14663. // handle meridiem
  14664. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
  14665. configFromArray(config);
  14666. checkOverflow(config);
  14667. }
  14668. function meridiemFixWrap (locale, hour, meridiem) {
  14669. var isPm;
  14670. if (meridiem == null) {
  14671. // nothing to do
  14672. return hour;
  14673. }
  14674. if (locale.meridiemHour != null) {
  14675. return locale.meridiemHour(hour, meridiem);
  14676. } else if (locale.isPM != null) {
  14677. // Fallback
  14678. isPm = locale.isPM(meridiem);
  14679. if (isPm && hour < 12) {
  14680. hour += 12;
  14681. }
  14682. if (!isPm && hour === 12) {
  14683. hour = 0;
  14684. }
  14685. return hour;
  14686. } else {
  14687. // this is not supposed to happen
  14688. return hour;
  14689. }
  14690. }
  14691. // date from string and array of format strings
  14692. function configFromStringAndArray(config) {
  14693. var tempConfig,
  14694. bestMoment,
  14695. scoreToBeat,
  14696. i,
  14697. currentScore;
  14698. if (config._f.length === 0) {
  14699. getParsingFlags(config).invalidFormat = true;
  14700. config._d = new Date(NaN);
  14701. return;
  14702. }
  14703. for (i = 0; i < config._f.length; i++) {
  14704. currentScore = 0;
  14705. tempConfig = copyConfig({}, config);
  14706. if (config._useUTC != null) {
  14707. tempConfig._useUTC = config._useUTC;
  14708. }
  14709. tempConfig._f = config._f[i];
  14710. configFromStringAndFormat(tempConfig);
  14711. if (!isValid(tempConfig)) {
  14712. continue;
  14713. }
  14714. // if there is any input that was not parsed add a penalty for that format
  14715. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  14716. //or tokens
  14717. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  14718. getParsingFlags(tempConfig).score = currentScore;
  14719. if (scoreToBeat == null || currentScore < scoreToBeat) {
  14720. scoreToBeat = currentScore;
  14721. bestMoment = tempConfig;
  14722. }
  14723. }
  14724. extend(config, bestMoment || tempConfig);
  14725. }
  14726. function configFromObject(config) {
  14727. if (config._d) {
  14728. return;
  14729. }
  14730. var i = normalizeObjectUnits(config._i);
  14731. config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
  14732. return obj && parseInt(obj, 10);
  14733. });
  14734. configFromArray(config);
  14735. }
  14736. function createFromConfig (config) {
  14737. var res = new Moment(checkOverflow(prepareConfig(config)));
  14738. if (res._nextDay) {
  14739. // Adding is smart enough around DST
  14740. res.add(1, 'd');
  14741. res._nextDay = undefined;
  14742. }
  14743. return res;
  14744. }
  14745. function prepareConfig (config) {
  14746. var input = config._i,
  14747. format = config._f;
  14748. config._locale = config._locale || getLocale(config._l);
  14749. if (input === null || (format === undefined && input === '')) {
  14750. return createInvalid({nullInput: true});
  14751. }
  14752. if (typeof input === 'string') {
  14753. config._i = input = config._locale.preparse(input);
  14754. }
  14755. if (isMoment(input)) {
  14756. return new Moment(checkOverflow(input));
  14757. } else if (isDate(input)) {
  14758. config._d = input;
  14759. } else if (isArray(format)) {
  14760. configFromStringAndArray(config);
  14761. } else if (format) {
  14762. configFromStringAndFormat(config);
  14763. } else {
  14764. configFromInput(config);
  14765. }
  14766. if (!isValid(config)) {
  14767. config._d = null;
  14768. }
  14769. return config;
  14770. }
  14771. function configFromInput(config) {
  14772. var input = config._i;
  14773. if (isUndefined(input)) {
  14774. config._d = new Date(hooks.now());
  14775. } else if (isDate(input)) {
  14776. config._d = new Date(input.valueOf());
  14777. } else if (typeof input === 'string') {
  14778. configFromString(config);
  14779. } else if (isArray(input)) {
  14780. config._a = map(input.slice(0), function (obj) {
  14781. return parseInt(obj, 10);
  14782. });
  14783. configFromArray(config);
  14784. } else if (isObject(input)) {
  14785. configFromObject(config);
  14786. } else if (isNumber(input)) {
  14787. // from milliseconds
  14788. config._d = new Date(input);
  14789. } else {
  14790. hooks.createFromInputFallback(config);
  14791. }
  14792. }
  14793. function createLocalOrUTC (input, format, locale, strict, isUTC) {
  14794. var c = {};
  14795. if (locale === true || locale === false) {
  14796. strict = locale;
  14797. locale = undefined;
  14798. }
  14799. if ((isObject(input) && isObjectEmpty(input)) ||
  14800. (isArray(input) && input.length === 0)) {
  14801. input = undefined;
  14802. }
  14803. // object construction must be done this way.
  14804. // https://github.com/moment/moment/issues/1423
  14805. c._isAMomentObject = true;
  14806. c._useUTC = c._isUTC = isUTC;
  14807. c._l = locale;
  14808. c._i = input;
  14809. c._f = format;
  14810. c._strict = strict;
  14811. return createFromConfig(c);
  14812. }
  14813. function createLocal (input, format, locale, strict) {
  14814. return createLocalOrUTC(input, format, locale, strict, false);
  14815. }
  14816. var prototypeMin = deprecate(
  14817. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  14818. function () {
  14819. var other = createLocal.apply(null, arguments);
  14820. if (this.isValid() && other.isValid()) {
  14821. return other < this ? this : other;
  14822. } else {
  14823. return createInvalid();
  14824. }
  14825. }
  14826. );
  14827. var prototypeMax = deprecate(
  14828. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  14829. function () {
  14830. var other = createLocal.apply(null, arguments);
  14831. if (this.isValid() && other.isValid()) {
  14832. return other > this ? this : other;
  14833. } else {
  14834. return createInvalid();
  14835. }
  14836. }
  14837. );
  14838. // Pick a moment m from moments so that m[fn](other) is true for all
  14839. // other. This relies on the function fn to be transitive.
  14840. //
  14841. // moments should either be an array of moment objects or an array, whose
  14842. // first element is an array of moment objects.
  14843. function pickBy(fn, moments) {
  14844. var res, i;
  14845. if (moments.length === 1 && isArray(moments[0])) {
  14846. moments = moments[0];
  14847. }
  14848. if (!moments.length) {
  14849. return createLocal();
  14850. }
  14851. res = moments[0];
  14852. for (i = 1; i < moments.length; ++i) {
  14853. if (!moments[i].isValid() || moments[i][fn](res)) {
  14854. res = moments[i];
  14855. }
  14856. }
  14857. return res;
  14858. }
  14859. // TODO: Use [].sort instead?
  14860. function min () {
  14861. var args = [].slice.call(arguments, 0);
  14862. return pickBy('isBefore', args);
  14863. }
  14864. function max () {
  14865. var args = [].slice.call(arguments, 0);
  14866. return pickBy('isAfter', args);
  14867. }
  14868. var now = function () {
  14869. return Date.now ? Date.now() : +(new Date());
  14870. };
  14871. var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
  14872. function isDurationValid(m) {
  14873. for (var key in m) {
  14874. if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
  14875. return false;
  14876. }
  14877. }
  14878. var unitHasDecimal = false;
  14879. for (var i = 0; i < ordering.length; ++i) {
  14880. if (m[ordering[i]]) {
  14881. if (unitHasDecimal) {
  14882. return false; // only allow non-integers for smallest unit
  14883. }
  14884. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  14885. unitHasDecimal = true;
  14886. }
  14887. }
  14888. }
  14889. return true;
  14890. }
  14891. function isValid$1() {
  14892. return this._isValid;
  14893. }
  14894. function createInvalid$1() {
  14895. return createDuration(NaN);
  14896. }
  14897. function Duration (duration) {
  14898. var normalizedInput = normalizeObjectUnits(duration),
  14899. years = normalizedInput.year || 0,
  14900. quarters = normalizedInput.quarter || 0,
  14901. months = normalizedInput.month || 0,
  14902. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  14903. days = normalizedInput.day || 0,
  14904. hours = normalizedInput.hour || 0,
  14905. minutes = normalizedInput.minute || 0,
  14906. seconds = normalizedInput.second || 0,
  14907. milliseconds = normalizedInput.millisecond || 0;
  14908. this._isValid = isDurationValid(normalizedInput);
  14909. // representation for dateAddRemove
  14910. this._milliseconds = +milliseconds +
  14911. seconds * 1e3 + // 1000
  14912. minutes * 6e4 + // 1000 * 60
  14913. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  14914. // Because of dateAddRemove treats 24 hours as different from a
  14915. // day when working around DST, we need to store them separately
  14916. this._days = +days +
  14917. weeks * 7;
  14918. // It is impossible to translate months into days without knowing
  14919. // which months you are are talking about, so we have to store
  14920. // it separately.
  14921. this._months = +months +
  14922. quarters * 3 +
  14923. years * 12;
  14924. this._data = {};
  14925. this._locale = getLocale();
  14926. this._bubble();
  14927. }
  14928. function isDuration (obj) {
  14929. return obj instanceof Duration;
  14930. }
  14931. function absRound (number) {
  14932. if (number < 0) {
  14933. return Math.round(-1 * number) * -1;
  14934. } else {
  14935. return Math.round(number);
  14936. }
  14937. }
  14938. // FORMATTING
  14939. function offset (token, separator) {
  14940. addFormatToken(token, 0, 0, function () {
  14941. var offset = this.utcOffset();
  14942. var sign = '+';
  14943. if (offset < 0) {
  14944. offset = -offset;
  14945. sign = '-';
  14946. }
  14947. return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
  14948. });
  14949. }
  14950. offset('Z', ':');
  14951. offset('ZZ', '');
  14952. // PARSING
  14953. addRegexToken('Z', matchShortOffset);
  14954. addRegexToken('ZZ', matchShortOffset);
  14955. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  14956. config._useUTC = true;
  14957. config._tzm = offsetFromString(matchShortOffset, input);
  14958. });
  14959. // HELPERS
  14960. // timezone chunker
  14961. // '+10:00' > ['10', '00']
  14962. // '-1530' > ['-15', '30']
  14963. var chunkOffset = /([\+\-]|\d\d)/gi;
  14964. function offsetFromString(matcher, string) {
  14965. var matches = (string || '').match(matcher);
  14966. if (matches === null) {
  14967. return null;
  14968. }
  14969. var chunk = matches[matches.length - 1] || [];
  14970. var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  14971. var minutes = +(parts[1] * 60) + toInt(parts[2]);
  14972. return minutes === 0 ?
  14973. 0 :
  14974. parts[0] === '+' ? minutes : -minutes;
  14975. }
  14976. // Return a moment from input, that is local/utc/zone equivalent to model.
  14977. function cloneWithOffset(input, model) {
  14978. var res, diff;
  14979. if (model._isUTC) {
  14980. res = model.clone();
  14981. diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
  14982. // Use low-level api, because this fn is low-level api.
  14983. res._d.setTime(res._d.valueOf() + diff);
  14984. hooks.updateOffset(res, false);
  14985. return res;
  14986. } else {
  14987. return createLocal(input).local();
  14988. }
  14989. }
  14990. function getDateOffset (m) {
  14991. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  14992. // https://github.com/moment/moment/pull/1871
  14993. return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
  14994. }
  14995. // HOOKS
  14996. // This function will be called whenever a moment is mutated.
  14997. // It is intended to keep the offset in sync with the timezone.
  14998. hooks.updateOffset = function () {};
  14999. // MOMENTS
  15000. // keepLocalTime = true means only change the timezone, without
  15001. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  15002. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  15003. // +0200, so we adjust the time as needed, to be valid.
  15004. //
  15005. // Keeping the time actually adds/subtracts (one hour)
  15006. // from the actual represented time. That is why we call updateOffset
  15007. // a second time. In case it wants us to change the offset again
  15008. // _changeInProgress == true case, then we have to adjust, because
  15009. // there is no such time in the given timezone.
  15010. function getSetOffset (input, keepLocalTime, keepMinutes) {
  15011. var offset = this._offset || 0,
  15012. localAdjust;
  15013. if (!this.isValid()) {
  15014. return input != null ? this : NaN;
  15015. }
  15016. if (input != null) {
  15017. if (typeof input === 'string') {
  15018. input = offsetFromString(matchShortOffset, input);
  15019. if (input === null) {
  15020. return this;
  15021. }
  15022. } else if (Math.abs(input) < 16 && !keepMinutes) {
  15023. input = input * 60;
  15024. }
  15025. if (!this._isUTC && keepLocalTime) {
  15026. localAdjust = getDateOffset(this);
  15027. }
  15028. this._offset = input;
  15029. this._isUTC = true;
  15030. if (localAdjust != null) {
  15031. this.add(localAdjust, 'm');
  15032. }
  15033. if (offset !== input) {
  15034. if (!keepLocalTime || this._changeInProgress) {
  15035. addSubtract(this, createDuration(input - offset, 'm'), 1, false);
  15036. } else if (!this._changeInProgress) {
  15037. this._changeInProgress = true;
  15038. hooks.updateOffset(this, true);
  15039. this._changeInProgress = null;
  15040. }
  15041. }
  15042. return this;
  15043. } else {
  15044. return this._isUTC ? offset : getDateOffset(this);
  15045. }
  15046. }
  15047. function getSetZone (input, keepLocalTime) {
  15048. if (input != null) {
  15049. if (typeof input !== 'string') {
  15050. input = -input;
  15051. }
  15052. this.utcOffset(input, keepLocalTime);
  15053. return this;
  15054. } else {
  15055. return -this.utcOffset();
  15056. }
  15057. }
  15058. function setOffsetToUTC (keepLocalTime) {
  15059. return this.utcOffset(0, keepLocalTime);
  15060. }
  15061. function setOffsetToLocal (keepLocalTime) {
  15062. if (this._isUTC) {
  15063. this.utcOffset(0, keepLocalTime);
  15064. this._isUTC = false;
  15065. if (keepLocalTime) {
  15066. this.subtract(getDateOffset(this), 'm');
  15067. }
  15068. }
  15069. return this;
  15070. }
  15071. function setOffsetToParsedOffset () {
  15072. if (this._tzm != null) {
  15073. this.utcOffset(this._tzm, false, true);
  15074. } else if (typeof this._i === 'string') {
  15075. var tZone = offsetFromString(matchOffset, this._i);
  15076. if (tZone != null) {
  15077. this.utcOffset(tZone);
  15078. }
  15079. else {
  15080. this.utcOffset(0, true);
  15081. }
  15082. }
  15083. return this;
  15084. }
  15085. function hasAlignedHourOffset (input) {
  15086. if (!this.isValid()) {
  15087. return false;
  15088. }
  15089. input = input ? createLocal(input).utcOffset() : 0;
  15090. return (this.utcOffset() - input) % 60 === 0;
  15091. }
  15092. function isDaylightSavingTime () {
  15093. return (
  15094. this.utcOffset() > this.clone().month(0).utcOffset() ||
  15095. this.utcOffset() > this.clone().month(5).utcOffset()
  15096. );
  15097. }
  15098. function isDaylightSavingTimeShifted () {
  15099. if (!isUndefined(this._isDSTShifted)) {
  15100. return this._isDSTShifted;
  15101. }
  15102. var c = {};
  15103. copyConfig(c, this);
  15104. c = prepareConfig(c);
  15105. if (c._a) {
  15106. var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  15107. this._isDSTShifted = this.isValid() &&
  15108. compareArrays(c._a, other.toArray()) > 0;
  15109. } else {
  15110. this._isDSTShifted = false;
  15111. }
  15112. return this._isDSTShifted;
  15113. }
  15114. function isLocal () {
  15115. return this.isValid() ? !this._isUTC : false;
  15116. }
  15117. function isUtcOffset () {
  15118. return this.isValid() ? this._isUTC : false;
  15119. }
  15120. function isUtc () {
  15121. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  15122. }
  15123. // ASP.NET json date format regex
  15124. var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
  15125. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  15126. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  15127. // and further modified to allow for strings containing both week and day
  15128. 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)?)?$/;
  15129. function createDuration (input, key) {
  15130. var duration = input,
  15131. // matching against regexp is expensive, do it on demand
  15132. match = null,
  15133. sign,
  15134. ret,
  15135. diffRes;
  15136. if (isDuration(input)) {
  15137. duration = {
  15138. ms : input._milliseconds,
  15139. d : input._days,
  15140. M : input._months
  15141. };
  15142. } else if (isNumber(input)) {
  15143. duration = {};
  15144. if (key) {
  15145. duration[key] = input;
  15146. } else {
  15147. duration.milliseconds = input;
  15148. }
  15149. } else if (!!(match = aspNetRegex.exec(input))) {
  15150. sign = (match[1] === '-') ? -1 : 1;
  15151. duration = {
  15152. y : 0,
  15153. d : toInt(match[DATE]) * sign,
  15154. h : toInt(match[HOUR]) * sign,
  15155. m : toInt(match[MINUTE]) * sign,
  15156. s : toInt(match[SECOND]) * sign,
  15157. ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
  15158. };
  15159. } else if (!!(match = isoRegex.exec(input))) {
  15160. sign = (match[1] === '-') ? -1 : 1;
  15161. duration = {
  15162. y : parseIso(match[2], sign),
  15163. M : parseIso(match[3], sign),
  15164. w : parseIso(match[4], sign),
  15165. d : parseIso(match[5], sign),
  15166. h : parseIso(match[6], sign),
  15167. m : parseIso(match[7], sign),
  15168. s : parseIso(match[8], sign)
  15169. };
  15170. } else if (duration == null) {// checks for null or undefined
  15171. duration = {};
  15172. } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
  15173. diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
  15174. duration = {};
  15175. duration.ms = diffRes.milliseconds;
  15176. duration.M = diffRes.months;
  15177. }
  15178. ret = new Duration(duration);
  15179. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  15180. ret._locale = input._locale;
  15181. }
  15182. return ret;
  15183. }
  15184. createDuration.fn = Duration.prototype;
  15185. createDuration.invalid = createInvalid$1;
  15186. function parseIso (inp, sign) {
  15187. // We'd normally use ~~inp for this, but unfortunately it also
  15188. // converts floats to ints.
  15189. // inp may be undefined, so careful calling replace on it.
  15190. var res = inp && parseFloat(inp.replace(',', '.'));
  15191. // apply sign while we're at it
  15192. return (isNaN(res) ? 0 : res) * sign;
  15193. }
  15194. function positiveMomentsDifference(base, other) {
  15195. var res = {};
  15196. res.months = other.month() - base.month() +
  15197. (other.year() - base.year()) * 12;
  15198. if (base.clone().add(res.months, 'M').isAfter(other)) {
  15199. --res.months;
  15200. }
  15201. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  15202. return res;
  15203. }
  15204. function momentsDifference(base, other) {
  15205. var res;
  15206. if (!(base.isValid() && other.isValid())) {
  15207. return {milliseconds: 0, months: 0};
  15208. }
  15209. other = cloneWithOffset(other, base);
  15210. if (base.isBefore(other)) {
  15211. res = positiveMomentsDifference(base, other);
  15212. } else {
  15213. res = positiveMomentsDifference(other, base);
  15214. res.milliseconds = -res.milliseconds;
  15215. res.months = -res.months;
  15216. }
  15217. return res;
  15218. }
  15219. // TODO: remove 'name' arg after deprecation is removed
  15220. function createAdder(direction, name) {
  15221. return function (val, period) {
  15222. var dur, tmp;
  15223. //invert the arguments, but complain about it
  15224. if (period !== null && !isNaN(+period)) {
  15225. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
  15226. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
  15227. tmp = val; val = period; period = tmp;
  15228. }
  15229. val = typeof val === 'string' ? +val : val;
  15230. dur = createDuration(val, period);
  15231. addSubtract(this, dur, direction);
  15232. return this;
  15233. };
  15234. }
  15235. function addSubtract (mom, duration, isAdding, updateOffset) {
  15236. var milliseconds = duration._milliseconds,
  15237. days = absRound(duration._days),
  15238. months = absRound(duration._months);
  15239. if (!mom.isValid()) {
  15240. // No op
  15241. return;
  15242. }
  15243. updateOffset = updateOffset == null ? true : updateOffset;
  15244. if (months) {
  15245. setMonth(mom, get(mom, 'Month') + months * isAdding);
  15246. }
  15247. if (days) {
  15248. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  15249. }
  15250. if (milliseconds) {
  15251. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  15252. }
  15253. if (updateOffset) {
  15254. hooks.updateOffset(mom, days || months);
  15255. }
  15256. }
  15257. var add = createAdder(1, 'add');
  15258. var subtract = createAdder(-1, 'subtract');
  15259. function getCalendarFormat(myMoment, now) {
  15260. var diff = myMoment.diff(now, 'days', true);
  15261. return diff < -6 ? 'sameElse' :
  15262. diff < -1 ? 'lastWeek' :
  15263. diff < 0 ? 'lastDay' :
  15264. diff < 1 ? 'sameDay' :
  15265. diff < 2 ? 'nextDay' :
  15266. diff < 7 ? 'nextWeek' : 'sameElse';
  15267. }
  15268. function calendar$1 (time, formats) {
  15269. // We want to compare the start of today, vs this.
  15270. // Getting start-of-today depends on whether we're local/utc/offset or not.
  15271. var now = time || createLocal(),
  15272. sod = cloneWithOffset(now, this).startOf('day'),
  15273. format = hooks.calendarFormat(this, sod) || 'sameElse';
  15274. var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
  15275. return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
  15276. }
  15277. function clone () {
  15278. return new Moment(this);
  15279. }
  15280. function isAfter (input, units) {
  15281. var localInput = isMoment(input) ? input : createLocal(input);
  15282. if (!(this.isValid() && localInput.isValid())) {
  15283. return false;
  15284. }
  15285. units = normalizeUnits(units) || 'millisecond';
  15286. if (units === 'millisecond') {
  15287. return this.valueOf() > localInput.valueOf();
  15288. } else {
  15289. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  15290. }
  15291. }
  15292. function isBefore (input, units) {
  15293. var localInput = isMoment(input) ? input : createLocal(input);
  15294. if (!(this.isValid() && localInput.isValid())) {
  15295. return false;
  15296. }
  15297. units = normalizeUnits(units) || 'millisecond';
  15298. if (units === 'millisecond') {
  15299. return this.valueOf() < localInput.valueOf();
  15300. } else {
  15301. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  15302. }
  15303. }
  15304. function isBetween (from, to, units, inclusivity) {
  15305. var localFrom = isMoment(from) ? from : createLocal(from),
  15306. localTo = isMoment(to) ? to : createLocal(to);
  15307. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  15308. return false;
  15309. }
  15310. inclusivity = inclusivity || '()';
  15311. return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) &&
  15312. (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
  15313. }
  15314. function isSame (input, units) {
  15315. var localInput = isMoment(input) ? input : createLocal(input),
  15316. inputMs;
  15317. if (!(this.isValid() && localInput.isValid())) {
  15318. return false;
  15319. }
  15320. units = normalizeUnits(units) || 'millisecond';
  15321. if (units === 'millisecond') {
  15322. return this.valueOf() === localInput.valueOf();
  15323. } else {
  15324. inputMs = localInput.valueOf();
  15325. return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
  15326. }
  15327. }
  15328. function isSameOrAfter (input, units) {
  15329. return this.isSame(input, units) || this.isAfter(input, units);
  15330. }
  15331. function isSameOrBefore (input, units) {
  15332. return this.isSame(input, units) || this.isBefore(input, units);
  15333. }
  15334. function diff (input, units, asFloat) {
  15335. var that,
  15336. zoneDelta,
  15337. output;
  15338. if (!this.isValid()) {
  15339. return NaN;
  15340. }
  15341. that = cloneWithOffset(input, this);
  15342. if (!that.isValid()) {
  15343. return NaN;
  15344. }
  15345. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  15346. units = normalizeUnits(units);
  15347. switch (units) {
  15348. case 'year': output = monthDiff(this, that) / 12; break;
  15349. case 'month': output = monthDiff(this, that); break;
  15350. case 'quarter': output = monthDiff(this, that) / 3; break;
  15351. case 'second': output = (this - that) / 1e3; break; // 1000
  15352. case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
  15353. case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
  15354. case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
  15355. case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
  15356. default: output = this - that;
  15357. }
  15358. return asFloat ? output : absFloor(output);
  15359. }
  15360. function monthDiff (a, b) {
  15361. // difference in months
  15362. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  15363. // b is in (anchor - 1 month, anchor + 1 month)
  15364. anchor = a.clone().add(wholeMonthDiff, 'months'),
  15365. anchor2, adjust;
  15366. if (b - anchor < 0) {
  15367. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  15368. // linear across the month
  15369. adjust = (b - anchor) / (anchor - anchor2);
  15370. } else {
  15371. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  15372. // linear across the month
  15373. adjust = (b - anchor) / (anchor2 - anchor);
  15374. }
  15375. //check for negative zero, return zero if negative zero
  15376. return -(wholeMonthDiff + adjust) || 0;
  15377. }
  15378. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  15379. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  15380. function toString () {
  15381. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  15382. }
  15383. function toISOString(keepOffset) {
  15384. if (!this.isValid()) {
  15385. return null;
  15386. }
  15387. var utc = keepOffset !== true;
  15388. var m = utc ? this.clone().utc() : this;
  15389. if (m.year() < 0 || m.year() > 9999) {
  15390. return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
  15391. }
  15392. if (isFunction(Date.prototype.toISOString)) {
  15393. // native implementation is ~50x faster, use it when we can
  15394. if (utc) {
  15395. return this.toDate().toISOString();
  15396. } else {
  15397. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
  15398. }
  15399. }
  15400. return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
  15401. }
  15402. /**
  15403. * Return a human readable representation of a moment that can
  15404. * also be evaluated to get a new moment which is the same
  15405. *
  15406. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  15407. */
  15408. function inspect () {
  15409. if (!this.isValid()) {
  15410. return 'moment.invalid(/* ' + this._i + ' */)';
  15411. }
  15412. var func = 'moment';
  15413. var zone = '';
  15414. if (!this.isLocal()) {
  15415. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  15416. zone = 'Z';
  15417. }
  15418. var prefix = '[' + func + '("]';
  15419. var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
  15420. var datetime = '-MM-DD[T]HH:mm:ss.SSS';
  15421. var suffix = zone + '[")]';
  15422. return this.format(prefix + year + datetime + suffix);
  15423. }
  15424. function format (inputString) {
  15425. if (!inputString) {
  15426. inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
  15427. }
  15428. var output = formatMoment(this, inputString);
  15429. return this.localeData().postformat(output);
  15430. }
  15431. function from (time, withoutSuffix) {
  15432. if (this.isValid() &&
  15433. ((isMoment(time) && time.isValid()) ||
  15434. createLocal(time).isValid())) {
  15435. return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  15436. } else {
  15437. return this.localeData().invalidDate();
  15438. }
  15439. }
  15440. function fromNow (withoutSuffix) {
  15441. return this.from(createLocal(), withoutSuffix);
  15442. }
  15443. function to (time, withoutSuffix) {
  15444. if (this.isValid() &&
  15445. ((isMoment(time) && time.isValid()) ||
  15446. createLocal(time).isValid())) {
  15447. return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
  15448. } else {
  15449. return this.localeData().invalidDate();
  15450. }
  15451. }
  15452. function toNow (withoutSuffix) {
  15453. return this.to(createLocal(), withoutSuffix);
  15454. }
  15455. // If passed a locale key, it will set the locale for this
  15456. // instance. Otherwise, it will return the locale configuration
  15457. // variables for this instance.
  15458. function locale (key) {
  15459. var newLocaleData;
  15460. if (key === undefined) {
  15461. return this._locale._abbr;
  15462. } else {
  15463. newLocaleData = getLocale(key);
  15464. if (newLocaleData != null) {
  15465. this._locale = newLocaleData;
  15466. }
  15467. return this;
  15468. }
  15469. }
  15470. var lang = deprecate(
  15471. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  15472. function (key) {
  15473. if (key === undefined) {
  15474. return this.localeData();
  15475. } else {
  15476. return this.locale(key);
  15477. }
  15478. }
  15479. );
  15480. function localeData () {
  15481. return this._locale;
  15482. }
  15483. var MS_PER_SECOND = 1000;
  15484. var MS_PER_MINUTE = 60 * MS_PER_SECOND;
  15485. var MS_PER_HOUR = 60 * MS_PER_MINUTE;
  15486. var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  15487. // actual modulo - handles negative numbers (for dates before 1970):
  15488. function mod$1(dividend, divisor) {
  15489. return (dividend % divisor + divisor) % divisor;
  15490. }
  15491. function localStartOfDate(y, m, d) {
  15492. // the date constructor remaps years 0-99 to 1900-1999
  15493. if (y < 100 && y >= 0) {
  15494. // preserve leap years using a full 400 year cycle, then reset
  15495. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  15496. } else {
  15497. return new Date(y, m, d).valueOf();
  15498. }
  15499. }
  15500. function utcStartOfDate(y, m, d) {
  15501. // Date.UTC remaps years 0-99 to 1900-1999
  15502. if (y < 100 && y >= 0) {
  15503. // preserve leap years using a full 400 year cycle, then reset
  15504. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  15505. } else {
  15506. return Date.UTC(y, m, d);
  15507. }
  15508. }
  15509. function startOf (units) {
  15510. var time;
  15511. units = normalizeUnits(units);
  15512. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  15513. return this;
  15514. }
  15515. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  15516. switch (units) {
  15517. case 'year':
  15518. time = startOfDate(this.year(), 0, 1);
  15519. break;
  15520. case 'quarter':
  15521. time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
  15522. break;
  15523. case 'month':
  15524. time = startOfDate(this.year(), this.month(), 1);
  15525. break;
  15526. case 'week':
  15527. time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
  15528. break;
  15529. case 'isoWeek':
  15530. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
  15531. break;
  15532. case 'day':
  15533. case 'date':
  15534. time = startOfDate(this.year(), this.month(), this.date());
  15535. break;
  15536. case 'hour':
  15537. time = this._d.valueOf();
  15538. time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
  15539. break;
  15540. case 'minute':
  15541. time = this._d.valueOf();
  15542. time -= mod$1(time, MS_PER_MINUTE);
  15543. break;
  15544. case 'second':
  15545. time = this._d.valueOf();
  15546. time -= mod$1(time, MS_PER_SECOND);
  15547. break;
  15548. }
  15549. this._d.setTime(time);
  15550. hooks.updateOffset(this, true);
  15551. return this;
  15552. }
  15553. function endOf (units) {
  15554. var time;
  15555. units = normalizeUnits(units);
  15556. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  15557. return this;
  15558. }
  15559. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  15560. switch (units) {
  15561. case 'year':
  15562. time = startOfDate(this.year() + 1, 0, 1) - 1;
  15563. break;
  15564. case 'quarter':
  15565. time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
  15566. break;
  15567. case 'month':
  15568. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  15569. break;
  15570. case 'week':
  15571. time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
  15572. break;
  15573. case 'isoWeek':
  15574. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
  15575. break;
  15576. case 'day':
  15577. case 'date':
  15578. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  15579. break;
  15580. case 'hour':
  15581. time = this._d.valueOf();
  15582. time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
  15583. break;
  15584. case 'minute':
  15585. time = this._d.valueOf();
  15586. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  15587. break;
  15588. case 'second':
  15589. time = this._d.valueOf();
  15590. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  15591. break;
  15592. }
  15593. this._d.setTime(time);
  15594. hooks.updateOffset(this, true);
  15595. return this;
  15596. }
  15597. function valueOf () {
  15598. return this._d.valueOf() - ((this._offset || 0) * 60000);
  15599. }
  15600. function unix () {
  15601. return Math.floor(this.valueOf() / 1000);
  15602. }
  15603. function toDate () {
  15604. return new Date(this.valueOf());
  15605. }
  15606. function toArray () {
  15607. var m = this;
  15608. return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
  15609. }
  15610. function toObject () {
  15611. var m = this;
  15612. return {
  15613. years: m.year(),
  15614. months: m.month(),
  15615. date: m.date(),
  15616. hours: m.hours(),
  15617. minutes: m.minutes(),
  15618. seconds: m.seconds(),
  15619. milliseconds: m.milliseconds()
  15620. };
  15621. }
  15622. function toJSON () {
  15623. // new Date(NaN).toJSON() === null
  15624. return this.isValid() ? this.toISOString() : null;
  15625. }
  15626. function isValid$2 () {
  15627. return isValid(this);
  15628. }
  15629. function parsingFlags () {
  15630. return extend({}, getParsingFlags(this));
  15631. }
  15632. function invalidAt () {
  15633. return getParsingFlags(this).overflow;
  15634. }
  15635. function creationData() {
  15636. return {
  15637. input: this._i,
  15638. format: this._f,
  15639. locale: this._locale,
  15640. isUTC: this._isUTC,
  15641. strict: this._strict
  15642. };
  15643. }
  15644. // FORMATTING
  15645. addFormatToken(0, ['gg', 2], 0, function () {
  15646. return this.weekYear() % 100;
  15647. });
  15648. addFormatToken(0, ['GG', 2], 0, function () {
  15649. return this.isoWeekYear() % 100;
  15650. });
  15651. function addWeekYearFormatToken (token, getter) {
  15652. addFormatToken(0, [token, token.length], 0, getter);
  15653. }
  15654. addWeekYearFormatToken('gggg', 'weekYear');
  15655. addWeekYearFormatToken('ggggg', 'weekYear');
  15656. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  15657. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  15658. // ALIASES
  15659. addUnitAlias('weekYear', 'gg');
  15660. addUnitAlias('isoWeekYear', 'GG');
  15661. // PRIORITY
  15662. addUnitPriority('weekYear', 1);
  15663. addUnitPriority('isoWeekYear', 1);
  15664. // PARSING
  15665. addRegexToken('G', matchSigned);
  15666. addRegexToken('g', matchSigned);
  15667. addRegexToken('GG', match1to2, match2);
  15668. addRegexToken('gg', match1to2, match2);
  15669. addRegexToken('GGGG', match1to4, match4);
  15670. addRegexToken('gggg', match1to4, match4);
  15671. addRegexToken('GGGGG', match1to6, match6);
  15672. addRegexToken('ggggg', match1to6, match6);
  15673. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
  15674. week[token.substr(0, 2)] = toInt(input);
  15675. });
  15676. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  15677. week[token] = hooks.parseTwoDigitYear(input);
  15678. });
  15679. // MOMENTS
  15680. function getSetWeekYear (input) {
  15681. return getSetWeekYearHelper.call(this,
  15682. input,
  15683. this.week(),
  15684. this.weekday(),
  15685. this.localeData()._week.dow,
  15686. this.localeData()._week.doy);
  15687. }
  15688. function getSetISOWeekYear (input) {
  15689. return getSetWeekYearHelper.call(this,
  15690. input, this.isoWeek(), this.isoWeekday(), 1, 4);
  15691. }
  15692. function getISOWeeksInYear () {
  15693. return weeksInYear(this.year(), 1, 4);
  15694. }
  15695. function getWeeksInYear () {
  15696. var weekInfo = this.localeData()._week;
  15697. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  15698. }
  15699. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  15700. var weeksTarget;
  15701. if (input == null) {
  15702. return weekOfYear(this, dow, doy).year;
  15703. } else {
  15704. weeksTarget = weeksInYear(input, dow, doy);
  15705. if (week > weeksTarget) {
  15706. week = weeksTarget;
  15707. }
  15708. return setWeekAll.call(this, input, week, weekday, dow, doy);
  15709. }
  15710. }
  15711. function setWeekAll(weekYear, week, weekday, dow, doy) {
  15712. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  15713. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  15714. this.year(date.getUTCFullYear());
  15715. this.month(date.getUTCMonth());
  15716. this.date(date.getUTCDate());
  15717. return this;
  15718. }
  15719. // FORMATTING
  15720. addFormatToken('Q', 0, 'Qo', 'quarter');
  15721. // ALIASES
  15722. addUnitAlias('quarter', 'Q');
  15723. // PRIORITY
  15724. addUnitPriority('quarter', 7);
  15725. // PARSING
  15726. addRegexToken('Q', match1);
  15727. addParseToken('Q', function (input, array) {
  15728. array[MONTH] = (toInt(input) - 1) * 3;
  15729. });
  15730. // MOMENTS
  15731. function getSetQuarter (input) {
  15732. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  15733. }
  15734. // FORMATTING
  15735. addFormatToken('D', ['DD', 2], 'Do', 'date');
  15736. // ALIASES
  15737. addUnitAlias('date', 'D');
  15738. // PRIORITY
  15739. addUnitPriority('date', 9);
  15740. // PARSING
  15741. addRegexToken('D', match1to2);
  15742. addRegexToken('DD', match1to2, match2);
  15743. addRegexToken('Do', function (isStrict, locale) {
  15744. // TODO: Remove "ordinalParse" fallback in next major release.
  15745. return isStrict ?
  15746. (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
  15747. locale._dayOfMonthOrdinalParseLenient;
  15748. });
  15749. addParseToken(['D', 'DD'], DATE);
  15750. addParseToken('Do', function (input, array) {
  15751. array[DATE] = toInt(input.match(match1to2)[0]);
  15752. });
  15753. // MOMENTS
  15754. var getSetDayOfMonth = makeGetSet('Date', true);
  15755. // FORMATTING
  15756. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  15757. // ALIASES
  15758. addUnitAlias('dayOfYear', 'DDD');
  15759. // PRIORITY
  15760. addUnitPriority('dayOfYear', 4);
  15761. // PARSING
  15762. addRegexToken('DDD', match1to3);
  15763. addRegexToken('DDDD', match3);
  15764. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  15765. config._dayOfYear = toInt(input);
  15766. });
  15767. // HELPERS
  15768. // MOMENTS
  15769. function getSetDayOfYear (input) {
  15770. var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
  15771. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  15772. }
  15773. // FORMATTING
  15774. addFormatToken('m', ['mm', 2], 0, 'minute');
  15775. // ALIASES
  15776. addUnitAlias('minute', 'm');
  15777. // PRIORITY
  15778. addUnitPriority('minute', 14);
  15779. // PARSING
  15780. addRegexToken('m', match1to2);
  15781. addRegexToken('mm', match1to2, match2);
  15782. addParseToken(['m', 'mm'], MINUTE);
  15783. // MOMENTS
  15784. var getSetMinute = makeGetSet('Minutes', false);
  15785. // FORMATTING
  15786. addFormatToken('s', ['ss', 2], 0, 'second');
  15787. // ALIASES
  15788. addUnitAlias('second', 's');
  15789. // PRIORITY
  15790. addUnitPriority('second', 15);
  15791. // PARSING
  15792. addRegexToken('s', match1to2);
  15793. addRegexToken('ss', match1to2, match2);
  15794. addParseToken(['s', 'ss'], SECOND);
  15795. // MOMENTS
  15796. var getSetSecond = makeGetSet('Seconds', false);
  15797. // FORMATTING
  15798. addFormatToken('S', 0, 0, function () {
  15799. return ~~(this.millisecond() / 100);
  15800. });
  15801. addFormatToken(0, ['SS', 2], 0, function () {
  15802. return ~~(this.millisecond() / 10);
  15803. });
  15804. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  15805. addFormatToken(0, ['SSSS', 4], 0, function () {
  15806. return this.millisecond() * 10;
  15807. });
  15808. addFormatToken(0, ['SSSSS', 5], 0, function () {
  15809. return this.millisecond() * 100;
  15810. });
  15811. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  15812. return this.millisecond() * 1000;
  15813. });
  15814. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  15815. return this.millisecond() * 10000;
  15816. });
  15817. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  15818. return this.millisecond() * 100000;
  15819. });
  15820. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  15821. return this.millisecond() * 1000000;
  15822. });
  15823. // ALIASES
  15824. addUnitAlias('millisecond', 'ms');
  15825. // PRIORITY
  15826. addUnitPriority('millisecond', 16);
  15827. // PARSING
  15828. addRegexToken('S', match1to3, match1);
  15829. addRegexToken('SS', match1to3, match2);
  15830. addRegexToken('SSS', match1to3, match3);
  15831. var token;
  15832. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  15833. addRegexToken(token, matchUnsigned);
  15834. }
  15835. function parseMs(input, array) {
  15836. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  15837. }
  15838. for (token = 'S'; token.length <= 9; token += 'S') {
  15839. addParseToken(token, parseMs);
  15840. }
  15841. // MOMENTS
  15842. var getSetMillisecond = makeGetSet('Milliseconds', false);
  15843. // FORMATTING
  15844. addFormatToken('z', 0, 0, 'zoneAbbr');
  15845. addFormatToken('zz', 0, 0, 'zoneName');
  15846. // MOMENTS
  15847. function getZoneAbbr () {
  15848. return this._isUTC ? 'UTC' : '';
  15849. }
  15850. function getZoneName () {
  15851. return this._isUTC ? 'Coordinated Universal Time' : '';
  15852. }
  15853. var proto = Moment.prototype;
  15854. proto.add = add;
  15855. proto.calendar = calendar$1;
  15856. proto.clone = clone;
  15857. proto.diff = diff;
  15858. proto.endOf = endOf;
  15859. proto.format = format;
  15860. proto.from = from;
  15861. proto.fromNow = fromNow;
  15862. proto.to = to;
  15863. proto.toNow = toNow;
  15864. proto.get = stringGet;
  15865. proto.invalidAt = invalidAt;
  15866. proto.isAfter = isAfter;
  15867. proto.isBefore = isBefore;
  15868. proto.isBetween = isBetween;
  15869. proto.isSame = isSame;
  15870. proto.isSameOrAfter = isSameOrAfter;
  15871. proto.isSameOrBefore = isSameOrBefore;
  15872. proto.isValid = isValid$2;
  15873. proto.lang = lang;
  15874. proto.locale = locale;
  15875. proto.localeData = localeData;
  15876. proto.max = prototypeMax;
  15877. proto.min = prototypeMin;
  15878. proto.parsingFlags = parsingFlags;
  15879. proto.set = stringSet;
  15880. proto.startOf = startOf;
  15881. proto.subtract = subtract;
  15882. proto.toArray = toArray;
  15883. proto.toObject = toObject;
  15884. proto.toDate = toDate;
  15885. proto.toISOString = toISOString;
  15886. proto.inspect = inspect;
  15887. proto.toJSON = toJSON;
  15888. proto.toString = toString;
  15889. proto.unix = unix;
  15890. proto.valueOf = valueOf;
  15891. proto.creationData = creationData;
  15892. proto.year = getSetYear;
  15893. proto.isLeapYear = getIsLeapYear;
  15894. proto.weekYear = getSetWeekYear;
  15895. proto.isoWeekYear = getSetISOWeekYear;
  15896. proto.quarter = proto.quarters = getSetQuarter;
  15897. proto.month = getSetMonth;
  15898. proto.daysInMonth = getDaysInMonth;
  15899. proto.week = proto.weeks = getSetWeek;
  15900. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  15901. proto.weeksInYear = getWeeksInYear;
  15902. proto.isoWeeksInYear = getISOWeeksInYear;
  15903. proto.date = getSetDayOfMonth;
  15904. proto.day = proto.days = getSetDayOfWeek;
  15905. proto.weekday = getSetLocaleDayOfWeek;
  15906. proto.isoWeekday = getSetISODayOfWeek;
  15907. proto.dayOfYear = getSetDayOfYear;
  15908. proto.hour = proto.hours = getSetHour;
  15909. proto.minute = proto.minutes = getSetMinute;
  15910. proto.second = proto.seconds = getSetSecond;
  15911. proto.millisecond = proto.milliseconds = getSetMillisecond;
  15912. proto.utcOffset = getSetOffset;
  15913. proto.utc = setOffsetToUTC;
  15914. proto.local = setOffsetToLocal;
  15915. proto.parseZone = setOffsetToParsedOffset;
  15916. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  15917. proto.isDST = isDaylightSavingTime;
  15918. proto.isLocal = isLocal;
  15919. proto.isUtcOffset = isUtcOffset;
  15920. proto.isUtc = isUtc;
  15921. proto.isUTC = isUtc;
  15922. proto.zoneAbbr = getZoneAbbr;
  15923. proto.zoneName = getZoneName;
  15924. proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
  15925. proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
  15926. proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
  15927. proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
  15928. proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
  15929. function createUnix (input) {
  15930. return createLocal(input * 1000);
  15931. }
  15932. function createInZone () {
  15933. return createLocal.apply(null, arguments).parseZone();
  15934. }
  15935. function preParsePostFormat (string) {
  15936. return string;
  15937. }
  15938. var proto$1 = Locale.prototype;
  15939. proto$1.calendar = calendar;
  15940. proto$1.longDateFormat = longDateFormat;
  15941. proto$1.invalidDate = invalidDate;
  15942. proto$1.ordinal = ordinal;
  15943. proto$1.preparse = preParsePostFormat;
  15944. proto$1.postformat = preParsePostFormat;
  15945. proto$1.relativeTime = relativeTime;
  15946. proto$1.pastFuture = pastFuture;
  15947. proto$1.set = set;
  15948. proto$1.months = localeMonths;
  15949. proto$1.monthsShort = localeMonthsShort;
  15950. proto$1.monthsParse = localeMonthsParse;
  15951. proto$1.monthsRegex = monthsRegex;
  15952. proto$1.monthsShortRegex = monthsShortRegex;
  15953. proto$1.week = localeWeek;
  15954. proto$1.firstDayOfYear = localeFirstDayOfYear;
  15955. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  15956. proto$1.weekdays = localeWeekdays;
  15957. proto$1.weekdaysMin = localeWeekdaysMin;
  15958. proto$1.weekdaysShort = localeWeekdaysShort;
  15959. proto$1.weekdaysParse = localeWeekdaysParse;
  15960. proto$1.weekdaysRegex = weekdaysRegex;
  15961. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  15962. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  15963. proto$1.isPM = localeIsPM;
  15964. proto$1.meridiem = localeMeridiem;
  15965. function get$1 (format, index, field, setter) {
  15966. var locale = getLocale();
  15967. var utc = createUTC().set(setter, index);
  15968. return locale[field](utc, format);
  15969. }
  15970. function listMonthsImpl (format, index, field) {
  15971. if (isNumber(format)) {
  15972. index = format;
  15973. format = undefined;
  15974. }
  15975. format = format || '';
  15976. if (index != null) {
  15977. return get$1(format, index, field, 'month');
  15978. }
  15979. var i;
  15980. var out = [];
  15981. for (i = 0; i < 12; i++) {
  15982. out[i] = get$1(format, i, field, 'month');
  15983. }
  15984. return out;
  15985. }
  15986. // ()
  15987. // (5)
  15988. // (fmt, 5)
  15989. // (fmt)
  15990. // (true)
  15991. // (true, 5)
  15992. // (true, fmt, 5)
  15993. // (true, fmt)
  15994. function listWeekdaysImpl (localeSorted, format, index, field) {
  15995. if (typeof localeSorted === 'boolean') {
  15996. if (isNumber(format)) {
  15997. index = format;
  15998. format = undefined;
  15999. }
  16000. format = format || '';
  16001. } else {
  16002. format = localeSorted;
  16003. index = format;
  16004. localeSorted = false;
  16005. if (isNumber(format)) {
  16006. index = format;
  16007. format = undefined;
  16008. }
  16009. format = format || '';
  16010. }
  16011. var locale = getLocale(),
  16012. shift = localeSorted ? locale._week.dow : 0;
  16013. if (index != null) {
  16014. return get$1(format, (index + shift) % 7, field, 'day');
  16015. }
  16016. var i;
  16017. var out = [];
  16018. for (i = 0; i < 7; i++) {
  16019. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  16020. }
  16021. return out;
  16022. }
  16023. function listMonths (format, index) {
  16024. return listMonthsImpl(format, index, 'months');
  16025. }
  16026. function listMonthsShort (format, index) {
  16027. return listMonthsImpl(format, index, 'monthsShort');
  16028. }
  16029. function listWeekdays (localeSorted, format, index) {
  16030. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  16031. }
  16032. function listWeekdaysShort (localeSorted, format, index) {
  16033. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  16034. }
  16035. function listWeekdaysMin (localeSorted, format, index) {
  16036. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  16037. }
  16038. getSetGlobalLocale('en', {
  16039. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  16040. ordinal : function (number) {
  16041. var b = number % 10,
  16042. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  16043. (b === 1) ? 'st' :
  16044. (b === 2) ? 'nd' :
  16045. (b === 3) ? 'rd' : 'th';
  16046. return number + output;
  16047. }
  16048. });
  16049. // Side effect imports
  16050. hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
  16051. hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
  16052. var mathAbs = Math.abs;
  16053. function abs () {
  16054. var data = this._data;
  16055. this._milliseconds = mathAbs(this._milliseconds);
  16056. this._days = mathAbs(this._days);
  16057. this._months = mathAbs(this._months);
  16058. data.milliseconds = mathAbs(data.milliseconds);
  16059. data.seconds = mathAbs(data.seconds);
  16060. data.minutes = mathAbs(data.minutes);
  16061. data.hours = mathAbs(data.hours);
  16062. data.months = mathAbs(data.months);
  16063. data.years = mathAbs(data.years);
  16064. return this;
  16065. }
  16066. function addSubtract$1 (duration, input, value, direction) {
  16067. var other = createDuration(input, value);
  16068. duration._milliseconds += direction * other._milliseconds;
  16069. duration._days += direction * other._days;
  16070. duration._months += direction * other._months;
  16071. return duration._bubble();
  16072. }
  16073. // supports only 2.0-style add(1, 's') or add(duration)
  16074. function add$1 (input, value) {
  16075. return addSubtract$1(this, input, value, 1);
  16076. }
  16077. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  16078. function subtract$1 (input, value) {
  16079. return addSubtract$1(this, input, value, -1);
  16080. }
  16081. function absCeil (number) {
  16082. if (number < 0) {
  16083. return Math.floor(number);
  16084. } else {
  16085. return Math.ceil(number);
  16086. }
  16087. }
  16088. function bubble () {
  16089. var milliseconds = this._milliseconds;
  16090. var days = this._days;
  16091. var months = this._months;
  16092. var data = this._data;
  16093. var seconds, minutes, hours, years, monthsFromDays;
  16094. // if we have a mix of positive and negative values, bubble down first
  16095. // check: https://github.com/moment/moment/issues/2166
  16096. if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
  16097. (milliseconds <= 0 && days <= 0 && months <= 0))) {
  16098. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  16099. days = 0;
  16100. months = 0;
  16101. }
  16102. // The following code bubbles up values, see the tests for
  16103. // examples of what that means.
  16104. data.milliseconds = milliseconds % 1000;
  16105. seconds = absFloor(milliseconds / 1000);
  16106. data.seconds = seconds % 60;
  16107. minutes = absFloor(seconds / 60);
  16108. data.minutes = minutes % 60;
  16109. hours = absFloor(minutes / 60);
  16110. data.hours = hours % 24;
  16111. days += absFloor(hours / 24);
  16112. // convert days to months
  16113. monthsFromDays = absFloor(daysToMonths(days));
  16114. months += monthsFromDays;
  16115. days -= absCeil(monthsToDays(monthsFromDays));
  16116. // 12 months -> 1 year
  16117. years = absFloor(months / 12);
  16118. months %= 12;
  16119. data.days = days;
  16120. data.months = months;
  16121. data.years = years;
  16122. return this;
  16123. }
  16124. function daysToMonths (days) {
  16125. // 400 years have 146097 days (taking into account leap year rules)
  16126. // 400 years have 12 months === 4800
  16127. return days * 4800 / 146097;
  16128. }
  16129. function monthsToDays (months) {
  16130. // the reverse of daysToMonths
  16131. return months * 146097 / 4800;
  16132. }
  16133. function as (units) {
  16134. if (!this.isValid()) {
  16135. return NaN;
  16136. }
  16137. var days;
  16138. var months;
  16139. var milliseconds = this._milliseconds;
  16140. units = normalizeUnits(units);
  16141. if (units === 'month' || units === 'quarter' || units === 'year') {
  16142. days = this._days + milliseconds / 864e5;
  16143. months = this._months + daysToMonths(days);
  16144. switch (units) {
  16145. case 'month': return months;
  16146. case 'quarter': return months / 3;
  16147. case 'year': return months / 12;
  16148. }
  16149. } else {
  16150. // handle milliseconds separately because of floating point math errors (issue #1867)
  16151. days = this._days + Math.round(monthsToDays(this._months));
  16152. switch (units) {
  16153. case 'week' : return days / 7 + milliseconds / 6048e5;
  16154. case 'day' : return days + milliseconds / 864e5;
  16155. case 'hour' : return days * 24 + milliseconds / 36e5;
  16156. case 'minute' : return days * 1440 + milliseconds / 6e4;
  16157. case 'second' : return days * 86400 + milliseconds / 1000;
  16158. // Math.floor prevents floating point math errors here
  16159. case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
  16160. default: throw new Error('Unknown unit ' + units);
  16161. }
  16162. }
  16163. }
  16164. // TODO: Use this.as('ms')?
  16165. function valueOf$1 () {
  16166. if (!this.isValid()) {
  16167. return NaN;
  16168. }
  16169. return (
  16170. this._milliseconds +
  16171. this._days * 864e5 +
  16172. (this._months % 12) * 2592e6 +
  16173. toInt(this._months / 12) * 31536e6
  16174. );
  16175. }
  16176. function makeAs (alias) {
  16177. return function () {
  16178. return this.as(alias);
  16179. };
  16180. }
  16181. var asMilliseconds = makeAs('ms');
  16182. var asSeconds = makeAs('s');
  16183. var asMinutes = makeAs('m');
  16184. var asHours = makeAs('h');
  16185. var asDays = makeAs('d');
  16186. var asWeeks = makeAs('w');
  16187. var asMonths = makeAs('M');
  16188. var asQuarters = makeAs('Q');
  16189. var asYears = makeAs('y');
  16190. function clone$1 () {
  16191. return createDuration(this);
  16192. }
  16193. function get$2 (units) {
  16194. units = normalizeUnits(units);
  16195. return this.isValid() ? this[units + 's']() : NaN;
  16196. }
  16197. function makeGetter(name) {
  16198. return function () {
  16199. return this.isValid() ? this._data[name] : NaN;
  16200. };
  16201. }
  16202. var milliseconds = makeGetter('milliseconds');
  16203. var seconds = makeGetter('seconds');
  16204. var minutes = makeGetter('minutes');
  16205. var hours = makeGetter('hours');
  16206. var days = makeGetter('days');
  16207. var months = makeGetter('months');
  16208. var years = makeGetter('years');
  16209. function weeks () {
  16210. return absFloor(this.days() / 7);
  16211. }
  16212. var round = Math.round;
  16213. var thresholds = {
  16214. ss: 44, // a few seconds to seconds
  16215. s : 45, // seconds to minute
  16216. m : 45, // minutes to hour
  16217. h : 22, // hours to day
  16218. d : 26, // days to month
  16219. M : 11 // months to year
  16220. };
  16221. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  16222. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  16223. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  16224. }
  16225. function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
  16226. var duration = createDuration(posNegDuration).abs();
  16227. var seconds = round(duration.as('s'));
  16228. var minutes = round(duration.as('m'));
  16229. var hours = round(duration.as('h'));
  16230. var days = round(duration.as('d'));
  16231. var months = round(duration.as('M'));
  16232. var years = round(duration.as('y'));
  16233. var a = seconds <= thresholds.ss && ['s', seconds] ||
  16234. seconds < thresholds.s && ['ss', seconds] ||
  16235. minutes <= 1 && ['m'] ||
  16236. minutes < thresholds.m && ['mm', minutes] ||
  16237. hours <= 1 && ['h'] ||
  16238. hours < thresholds.h && ['hh', hours] ||
  16239. days <= 1 && ['d'] ||
  16240. days < thresholds.d && ['dd', days] ||
  16241. months <= 1 && ['M'] ||
  16242. months < thresholds.M && ['MM', months] ||
  16243. years <= 1 && ['y'] || ['yy', years];
  16244. a[2] = withoutSuffix;
  16245. a[3] = +posNegDuration > 0;
  16246. a[4] = locale;
  16247. return substituteTimeAgo.apply(null, a);
  16248. }
  16249. // This function allows you to set the rounding function for relative time strings
  16250. function getSetRelativeTimeRounding (roundingFunction) {
  16251. if (roundingFunction === undefined) {
  16252. return round;
  16253. }
  16254. if (typeof(roundingFunction) === 'function') {
  16255. round = roundingFunction;
  16256. return true;
  16257. }
  16258. return false;
  16259. }
  16260. // This function allows you to set a threshold for relative time strings
  16261. function getSetRelativeTimeThreshold (threshold, limit) {
  16262. if (thresholds[threshold] === undefined) {
  16263. return false;
  16264. }
  16265. if (limit === undefined) {
  16266. return thresholds[threshold];
  16267. }
  16268. thresholds[threshold] = limit;
  16269. if (threshold === 's') {
  16270. thresholds.ss = limit - 1;
  16271. }
  16272. return true;
  16273. }
  16274. function humanize (withSuffix) {
  16275. if (!this.isValid()) {
  16276. return this.localeData().invalidDate();
  16277. }
  16278. var locale = this.localeData();
  16279. var output = relativeTime$1(this, !withSuffix, locale);
  16280. if (withSuffix) {
  16281. output = locale.pastFuture(+this, output);
  16282. }
  16283. return locale.postformat(output);
  16284. }
  16285. var abs$1 = Math.abs;
  16286. function sign(x) {
  16287. return ((x > 0) - (x < 0)) || +x;
  16288. }
  16289. function toISOString$1() {
  16290. // for ISO strings we do not use the normal bubbling rules:
  16291. // * milliseconds bubble up until they become hours
  16292. // * days do not bubble at all
  16293. // * months bubble up until they become years
  16294. // This is because there is no context-free conversion between hours and days
  16295. // (think of clock changes)
  16296. // and also not between days and months (28-31 days per month)
  16297. if (!this.isValid()) {
  16298. return this.localeData().invalidDate();
  16299. }
  16300. var seconds = abs$1(this._milliseconds) / 1000;
  16301. var days = abs$1(this._days);
  16302. var months = abs$1(this._months);
  16303. var minutes, hours, years;
  16304. // 3600 seconds -> 60 minutes -> 1 hour
  16305. minutes = absFloor(seconds / 60);
  16306. hours = absFloor(minutes / 60);
  16307. seconds %= 60;
  16308. minutes %= 60;
  16309. // 12 months -> 1 year
  16310. years = absFloor(months / 12);
  16311. months %= 12;
  16312. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  16313. var Y = years;
  16314. var M = months;
  16315. var D = days;
  16316. var h = hours;
  16317. var m = minutes;
  16318. var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  16319. var total = this.asSeconds();
  16320. if (!total) {
  16321. // this is the same as C#'s (Noda) and python (isodate)...
  16322. // but not other JS (goog.date)
  16323. return 'P0D';
  16324. }
  16325. var totalSign = total < 0 ? '-' : '';
  16326. var ymSign = sign(this._months) !== sign(total) ? '-' : '';
  16327. var daysSign = sign(this._days) !== sign(total) ? '-' : '';
  16328. var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  16329. return totalSign + 'P' +
  16330. (Y ? ymSign + Y + 'Y' : '') +
  16331. (M ? ymSign + M + 'M' : '') +
  16332. (D ? daysSign + D + 'D' : '') +
  16333. ((h || m || s) ? 'T' : '') +
  16334. (h ? hmsSign + h + 'H' : '') +
  16335. (m ? hmsSign + m + 'M' : '') +
  16336. (s ? hmsSign + s + 'S' : '');
  16337. }
  16338. var proto$2 = Duration.prototype;
  16339. proto$2.isValid = isValid$1;
  16340. proto$2.abs = abs;
  16341. proto$2.add = add$1;
  16342. proto$2.subtract = subtract$1;
  16343. proto$2.as = as;
  16344. proto$2.asMilliseconds = asMilliseconds;
  16345. proto$2.asSeconds = asSeconds;
  16346. proto$2.asMinutes = asMinutes;
  16347. proto$2.asHours = asHours;
  16348. proto$2.asDays = asDays;
  16349. proto$2.asWeeks = asWeeks;
  16350. proto$2.asMonths = asMonths;
  16351. proto$2.asQuarters = asQuarters;
  16352. proto$2.asYears = asYears;
  16353. proto$2.valueOf = valueOf$1;
  16354. proto$2._bubble = bubble;
  16355. proto$2.clone = clone$1;
  16356. proto$2.get = get$2;
  16357. proto$2.milliseconds = milliseconds;
  16358. proto$2.seconds = seconds;
  16359. proto$2.minutes = minutes;
  16360. proto$2.hours = hours;
  16361. proto$2.days = days;
  16362. proto$2.weeks = weeks;
  16363. proto$2.months = months;
  16364. proto$2.years = years;
  16365. proto$2.humanize = humanize;
  16366. proto$2.toISOString = toISOString$1;
  16367. proto$2.toString = toISOString$1;
  16368. proto$2.toJSON = toISOString$1;
  16369. proto$2.locale = locale;
  16370. proto$2.localeData = localeData;
  16371. proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
  16372. proto$2.lang = lang;
  16373. // Side effect imports
  16374. // FORMATTING
  16375. addFormatToken('X', 0, 0, 'unix');
  16376. addFormatToken('x', 0, 0, 'valueOf');
  16377. // PARSING
  16378. addRegexToken('x', matchSigned);
  16379. addRegexToken('X', matchTimestamp);
  16380. addParseToken('X', function (input, array, config) {
  16381. config._d = new Date(parseFloat(input, 10) * 1000);
  16382. });
  16383. addParseToken('x', function (input, array, config) {
  16384. config._d = new Date(toInt(input));
  16385. });
  16386. // Side effect imports
  16387. hooks.version = '2.24.0';
  16388. setHookCallback(createLocal);
  16389. hooks.fn = proto;
  16390. hooks.min = min;
  16391. hooks.max = max;
  16392. hooks.now = now;
  16393. hooks.utc = createUTC;
  16394. hooks.unix = createUnix;
  16395. hooks.months = listMonths;
  16396. hooks.isDate = isDate;
  16397. hooks.locale = getSetGlobalLocale;
  16398. hooks.invalid = createInvalid;
  16399. hooks.duration = createDuration;
  16400. hooks.isMoment = isMoment;
  16401. hooks.weekdays = listWeekdays;
  16402. hooks.parseZone = createInZone;
  16403. hooks.localeData = getLocale;
  16404. hooks.isDuration = isDuration;
  16405. hooks.monthsShort = listMonthsShort;
  16406. hooks.weekdaysMin = listWeekdaysMin;
  16407. hooks.defineLocale = defineLocale;
  16408. hooks.updateLocale = updateLocale;
  16409. hooks.locales = listLocales;
  16410. hooks.weekdaysShort = listWeekdaysShort;
  16411. hooks.normalizeUnits = normalizeUnits;
  16412. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  16413. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  16414. hooks.calendarFormat = getCalendarFormat;
  16415. hooks.prototype = proto;
  16416. // currently HTML5 input type only supports 24-hour formats
  16417. hooks.HTML5_FMT = {
  16418. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  16419. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  16420. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  16421. DATE: 'YYYY-MM-DD', // <input type="date" />
  16422. TIME: 'HH:mm', // <input type="time" />
  16423. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  16424. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  16425. WEEK: 'GGGG-[W]WW', // <input type="week" />
  16426. MONTH: 'YYYY-MM' // <input type="month" />
  16427. };
  16428. return hooks;
  16429. })));
  16430. });
  16431. var FORMATS = {
  16432. datetime: 'MMM D, YYYY, h:mm:ss a',
  16433. millisecond: 'h:mm:ss.SSS a',
  16434. second: 'h:mm:ss a',
  16435. minute: 'h:mm a',
  16436. hour: 'hA',
  16437. day: 'MMM D',
  16438. week: 'll',
  16439. month: 'MMM YYYY',
  16440. quarter: '[Q]Q - YYYY',
  16441. year: 'YYYY'
  16442. };
  16443. core_adapters._date.override(typeof moment === 'function' ? {
  16444. _id: 'moment', // DEBUG ONLY
  16445. formats: function() {
  16446. return FORMATS;
  16447. },
  16448. parse: function(value, format) {
  16449. if (typeof value === 'string' && typeof format === 'string') {
  16450. value = moment(value, format);
  16451. } else if (!(value instanceof moment)) {
  16452. value = moment(value);
  16453. }
  16454. return value.isValid() ? value.valueOf() : null;
  16455. },
  16456. format: function(time, format) {
  16457. return moment(time).format(format);
  16458. },
  16459. add: function(time, amount, unit) {
  16460. return moment(time).add(amount, unit).valueOf();
  16461. },
  16462. diff: function(max, min, unit) {
  16463. return moment(max).diff(moment(min), unit);
  16464. },
  16465. startOf: function(time, unit, weekday) {
  16466. time = moment(time);
  16467. if (unit === 'isoWeek') {
  16468. return time.isoWeekday(weekday).valueOf();
  16469. }
  16470. return time.startOf(unit).valueOf();
  16471. },
  16472. endOf: function(time, unit) {
  16473. return moment(time).endOf(unit).valueOf();
  16474. },
  16475. // DEPRECATIONS
  16476. /**
  16477. * Provided for backward compatibility with scale.getValueForPixel().
  16478. * @deprecated since version 2.8.0
  16479. * @todo remove at version 3
  16480. * @private
  16481. */
  16482. _create: function(time) {
  16483. return moment(time);
  16484. },
  16485. } : {});
  16486. core_defaults._set('global', {
  16487. plugins: {
  16488. filler: {
  16489. propagate: true
  16490. }
  16491. }
  16492. });
  16493. var mappers = {
  16494. dataset: function(source) {
  16495. var index = source.fill;
  16496. var chart = source.chart;
  16497. var meta = chart.getDatasetMeta(index);
  16498. var visible = meta && chart.isDatasetVisible(index);
  16499. var points = (visible && meta.dataset._children) || [];
  16500. var length = points.length || 0;
  16501. return !length ? null : function(point, i) {
  16502. return (i < length && points[i]._view) || null;
  16503. };
  16504. },
  16505. boundary: function(source) {
  16506. var boundary = source.boundary;
  16507. var x = boundary ? boundary.x : null;
  16508. var y = boundary ? boundary.y : null;
  16509. if (helpers$1.isArray(boundary)) {
  16510. return function(point, i) {
  16511. return boundary[i];
  16512. };
  16513. }
  16514. return function(point) {
  16515. return {
  16516. x: x === null ? point.x : x,
  16517. y: y === null ? point.y : y,
  16518. };
  16519. };
  16520. }
  16521. };
  16522. // @todo if (fill[0] === '#')
  16523. function decodeFill(el, index, count) {
  16524. var model = el._model || {};
  16525. var fill = model.fill;
  16526. var target;
  16527. if (fill === undefined) {
  16528. fill = !!model.backgroundColor;
  16529. }
  16530. if (fill === false || fill === null) {
  16531. return false;
  16532. }
  16533. if (fill === true) {
  16534. return 'origin';
  16535. }
  16536. target = parseFloat(fill, 10);
  16537. if (isFinite(target) && Math.floor(target) === target) {
  16538. if (fill[0] === '-' || fill[0] === '+') {
  16539. target = index + target;
  16540. }
  16541. if (target === index || target < 0 || target >= count) {
  16542. return false;
  16543. }
  16544. return target;
  16545. }
  16546. switch (fill) {
  16547. // compatibility
  16548. case 'bottom':
  16549. return 'start';
  16550. case 'top':
  16551. return 'end';
  16552. case 'zero':
  16553. return 'origin';
  16554. // supported boundaries
  16555. case 'origin':
  16556. case 'start':
  16557. case 'end':
  16558. return fill;
  16559. // invalid fill values
  16560. default:
  16561. return false;
  16562. }
  16563. }
  16564. function computeLinearBoundary(source) {
  16565. var model = source.el._model || {};
  16566. var scale = source.el._scale || {};
  16567. var fill = source.fill;
  16568. var target = null;
  16569. var horizontal;
  16570. if (isFinite(fill)) {
  16571. return null;
  16572. }
  16573. // Backward compatibility: until v3, we still need to support boundary values set on
  16574. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  16575. // controllers might still use it (e.g. the Smith chart).
  16576. if (fill === 'start') {
  16577. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  16578. } else if (fill === 'end') {
  16579. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  16580. } else if (model.scaleZero !== undefined) {
  16581. target = model.scaleZero;
  16582. } else if (scale.getBasePixel) {
  16583. target = scale.getBasePixel();
  16584. }
  16585. if (target !== undefined && target !== null) {
  16586. if (target.x !== undefined && target.y !== undefined) {
  16587. return target;
  16588. }
  16589. if (helpers$1.isFinite(target)) {
  16590. horizontal = scale.isHorizontal();
  16591. return {
  16592. x: horizontal ? target : null,
  16593. y: horizontal ? null : target
  16594. };
  16595. }
  16596. }
  16597. return null;
  16598. }
  16599. function computeCircularBoundary(source) {
  16600. var scale = source.el._scale;
  16601. var options = scale.options;
  16602. var length = scale.chart.data.labels.length;
  16603. var fill = source.fill;
  16604. var target = [];
  16605. var start, end, center, i, point;
  16606. if (!length) {
  16607. return null;
  16608. }
  16609. start = options.ticks.reverse ? scale.max : scale.min;
  16610. end = options.ticks.reverse ? scale.min : scale.max;
  16611. center = scale.getPointPositionForValue(0, start);
  16612. for (i = 0; i < length; ++i) {
  16613. point = fill === 'start' || fill === 'end'
  16614. ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)
  16615. : scale.getBasePosition(i);
  16616. if (options.gridLines.circular) {
  16617. point.cx = center.x;
  16618. point.cy = center.y;
  16619. point.angle = scale.getIndexAngle(i) - Math.PI / 2;
  16620. }
  16621. target.push(point);
  16622. }
  16623. return target;
  16624. }
  16625. function computeBoundary(source) {
  16626. var scale = source.el._scale || {};
  16627. if (scale.getPointPositionForValue) {
  16628. return computeCircularBoundary(source);
  16629. }
  16630. return computeLinearBoundary(source);
  16631. }
  16632. function resolveTarget(sources, index, propagate) {
  16633. var source = sources[index];
  16634. var fill = source.fill;
  16635. var visited = [index];
  16636. var target;
  16637. if (!propagate) {
  16638. return fill;
  16639. }
  16640. while (fill !== false && visited.indexOf(fill) === -1) {
  16641. if (!isFinite(fill)) {
  16642. return fill;
  16643. }
  16644. target = sources[fill];
  16645. if (!target) {
  16646. return false;
  16647. }
  16648. if (target.visible) {
  16649. return fill;
  16650. }
  16651. visited.push(fill);
  16652. fill = target.fill;
  16653. }
  16654. return false;
  16655. }
  16656. function createMapper(source) {
  16657. var fill = source.fill;
  16658. var type = 'dataset';
  16659. if (fill === false) {
  16660. return null;
  16661. }
  16662. if (!isFinite(fill)) {
  16663. type = 'boundary';
  16664. }
  16665. return mappers[type](source);
  16666. }
  16667. function isDrawable(point) {
  16668. return point && !point.skip;
  16669. }
  16670. function drawArea(ctx, curve0, curve1, len0, len1) {
  16671. var i, cx, cy, r;
  16672. if (!len0 || !len1) {
  16673. return;
  16674. }
  16675. // building first area curve (normal)
  16676. ctx.moveTo(curve0[0].x, curve0[0].y);
  16677. for (i = 1; i < len0; ++i) {
  16678. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  16679. }
  16680. if (curve1[0].angle !== undefined) {
  16681. cx = curve1[0].cx;
  16682. cy = curve1[0].cy;
  16683. r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));
  16684. for (i = len1 - 1; i > 0; --i) {
  16685. ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);
  16686. }
  16687. return;
  16688. }
  16689. // joining the two area curves
  16690. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  16691. // building opposite area curve (reverse)
  16692. for (i = len1 - 1; i > 0; --i) {
  16693. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  16694. }
  16695. }
  16696. function doFill(ctx, points, mapper, view, color, loop) {
  16697. var count = points.length;
  16698. var span = view.spanGaps;
  16699. var curve0 = [];
  16700. var curve1 = [];
  16701. var len0 = 0;
  16702. var len1 = 0;
  16703. var i, ilen, index, p0, p1, d0, d1, loopOffset;
  16704. ctx.beginPath();
  16705. for (i = 0, ilen = count; i < ilen; ++i) {
  16706. index = i % count;
  16707. p0 = points[index]._view;
  16708. p1 = mapper(p0, index, view);
  16709. d0 = isDrawable(p0);
  16710. d1 = isDrawable(p1);
  16711. if (loop && loopOffset === undefined && d0) {
  16712. loopOffset = i + 1;
  16713. ilen = count + loopOffset;
  16714. }
  16715. if (d0 && d1) {
  16716. len0 = curve0.push(p0);
  16717. len1 = curve1.push(p1);
  16718. } else if (len0 && len1) {
  16719. if (!span) {
  16720. drawArea(ctx, curve0, curve1, len0, len1);
  16721. len0 = len1 = 0;
  16722. curve0 = [];
  16723. curve1 = [];
  16724. } else {
  16725. if (d0) {
  16726. curve0.push(p0);
  16727. }
  16728. if (d1) {
  16729. curve1.push(p1);
  16730. }
  16731. }
  16732. }
  16733. }
  16734. drawArea(ctx, curve0, curve1, len0, len1);
  16735. ctx.closePath();
  16736. ctx.fillStyle = color;
  16737. ctx.fill();
  16738. }
  16739. var plugin_filler = {
  16740. id: 'filler',
  16741. afterDatasetsUpdate: function(chart, options) {
  16742. var count = (chart.data.datasets || []).length;
  16743. var propagate = options.propagate;
  16744. var sources = [];
  16745. var meta, i, el, source;
  16746. for (i = 0; i < count; ++i) {
  16747. meta = chart.getDatasetMeta(i);
  16748. el = meta.dataset;
  16749. source = null;
  16750. if (el && el._model && el instanceof elements.Line) {
  16751. source = {
  16752. visible: chart.isDatasetVisible(i),
  16753. fill: decodeFill(el, i, count),
  16754. chart: chart,
  16755. el: el
  16756. };
  16757. }
  16758. meta.$filler = source;
  16759. sources.push(source);
  16760. }
  16761. for (i = 0; i < count; ++i) {
  16762. source = sources[i];
  16763. if (!source) {
  16764. continue;
  16765. }
  16766. source.fill = resolveTarget(sources, i, propagate);
  16767. source.boundary = computeBoundary(source);
  16768. source.mapper = createMapper(source);
  16769. }
  16770. },
  16771. beforeDatasetsDraw: function(chart) {
  16772. var metasets = chart._getSortedVisibleDatasetMetas();
  16773. var ctx = chart.ctx;
  16774. var meta, i, el, view, points, mapper, color;
  16775. for (i = metasets.length - 1; i >= 0; --i) {
  16776. meta = metasets[i].$filler;
  16777. if (!meta || !meta.visible) {
  16778. continue;
  16779. }
  16780. el = meta.el;
  16781. view = el._view;
  16782. points = el._children || [];
  16783. mapper = meta.mapper;
  16784. color = view.backgroundColor || core_defaults.global.defaultColor;
  16785. if (mapper && color && points.length) {
  16786. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  16787. doFill(ctx, points, mapper, view, color, el._loop);
  16788. helpers$1.canvas.unclipArea(ctx);
  16789. }
  16790. }
  16791. }
  16792. };
  16793. var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;
  16794. var noop$1 = helpers$1.noop;
  16795. var valueOrDefault$e = helpers$1.valueOrDefault;
  16796. core_defaults._set('global', {
  16797. legend: {
  16798. display: true,
  16799. position: 'top',
  16800. align: 'center',
  16801. fullWidth: true,
  16802. reverse: false,
  16803. weight: 1000,
  16804. // a callback that will handle
  16805. onClick: function(e, legendItem) {
  16806. var index = legendItem.datasetIndex;
  16807. var ci = this.chart;
  16808. var meta = ci.getDatasetMeta(index);
  16809. // See controller.isDatasetVisible comment
  16810. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  16811. // We hid a dataset ... rerender the chart
  16812. ci.update();
  16813. },
  16814. onHover: null,
  16815. onLeave: null,
  16816. labels: {
  16817. boxWidth: 40,
  16818. padding: 10,
  16819. // Generates labels shown in the legend
  16820. // Valid properties to return:
  16821. // text : text to display
  16822. // fillStyle : fill of coloured box
  16823. // strokeStyle: stroke of coloured box
  16824. // hidden : if this legend item refers to a hidden item
  16825. // lineCap : cap style for line
  16826. // lineDash
  16827. // lineDashOffset :
  16828. // lineJoin :
  16829. // lineWidth :
  16830. generateLabels: function(chart) {
  16831. var datasets = chart.data.datasets;
  16832. var options = chart.options.legend || {};
  16833. var usePointStyle = options.labels && options.labels.usePointStyle;
  16834. return chart._getSortedDatasetMetas().map(function(meta) {
  16835. var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  16836. return {
  16837. text: datasets[meta.index].label,
  16838. fillStyle: style.backgroundColor,
  16839. hidden: !chart.isDatasetVisible(meta.index),
  16840. lineCap: style.borderCapStyle,
  16841. lineDash: style.borderDash,
  16842. lineDashOffset: style.borderDashOffset,
  16843. lineJoin: style.borderJoinStyle,
  16844. lineWidth: style.borderWidth,
  16845. strokeStyle: style.borderColor,
  16846. pointStyle: style.pointStyle,
  16847. rotation: style.rotation,
  16848. // Below is extra data used for toggling the datasets
  16849. datasetIndex: meta.index
  16850. };
  16851. }, this);
  16852. }
  16853. }
  16854. },
  16855. legendCallback: function(chart) {
  16856. var list = document.createElement('ul');
  16857. var datasets = chart.data.datasets;
  16858. var i, ilen, listItem, listItemSpan;
  16859. list.setAttribute('class', chart.id + '-legend');
  16860. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  16861. listItem = list.appendChild(document.createElement('li'));
  16862. listItemSpan = listItem.appendChild(document.createElement('span'));
  16863. listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
  16864. if (datasets[i].label) {
  16865. listItem.appendChild(document.createTextNode(datasets[i].label));
  16866. }
  16867. }
  16868. return list.outerHTML;
  16869. }
  16870. });
  16871. /**
  16872. * Helper function to get the box width based on the usePointStyle option
  16873. * @param {object} labelopts - the label options on the legend
  16874. * @param {number} fontSize - the label font size
  16875. * @return {number} width of the color box area
  16876. */
  16877. function getBoxWidth(labelOpts, fontSize) {
  16878. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  16879. fontSize :
  16880. labelOpts.boxWidth;
  16881. }
  16882. /**
  16883. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  16884. */
  16885. var Legend = core_element.extend({
  16886. initialize: function(config) {
  16887. var me = this;
  16888. helpers$1.extend(me, config);
  16889. // Contains hit boxes for each dataset (in dataset order)
  16890. me.legendHitBoxes = [];
  16891. /**
  16892. * @private
  16893. */
  16894. me._hoveredItem = null;
  16895. // Are we in doughnut mode which has a different data type
  16896. me.doughnutMode = false;
  16897. },
  16898. // These methods are ordered by lifecycle. Utilities then follow.
  16899. // Any function defined here is inherited by all legend types.
  16900. // Any function can be extended by the legend type
  16901. beforeUpdate: noop$1,
  16902. update: function(maxWidth, maxHeight, margins) {
  16903. var me = this;
  16904. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  16905. me.beforeUpdate();
  16906. // Absorb the master measurements
  16907. me.maxWidth = maxWidth;
  16908. me.maxHeight = maxHeight;
  16909. me.margins = margins;
  16910. // Dimensions
  16911. me.beforeSetDimensions();
  16912. me.setDimensions();
  16913. me.afterSetDimensions();
  16914. // Labels
  16915. me.beforeBuildLabels();
  16916. me.buildLabels();
  16917. me.afterBuildLabels();
  16918. // Fit
  16919. me.beforeFit();
  16920. me.fit();
  16921. me.afterFit();
  16922. //
  16923. me.afterUpdate();
  16924. return me.minSize;
  16925. },
  16926. afterUpdate: noop$1,
  16927. //
  16928. beforeSetDimensions: noop$1,
  16929. setDimensions: function() {
  16930. var me = this;
  16931. // Set the unconstrained dimension before label rotation
  16932. if (me.isHorizontal()) {
  16933. // Reset position before calculating rotation
  16934. me.width = me.maxWidth;
  16935. me.left = 0;
  16936. me.right = me.width;
  16937. } else {
  16938. me.height = me.maxHeight;
  16939. // Reset position before calculating rotation
  16940. me.top = 0;
  16941. me.bottom = me.height;
  16942. }
  16943. // Reset padding
  16944. me.paddingLeft = 0;
  16945. me.paddingTop = 0;
  16946. me.paddingRight = 0;
  16947. me.paddingBottom = 0;
  16948. // Reset minSize
  16949. me.minSize = {
  16950. width: 0,
  16951. height: 0
  16952. };
  16953. },
  16954. afterSetDimensions: noop$1,
  16955. //
  16956. beforeBuildLabels: noop$1,
  16957. buildLabels: function() {
  16958. var me = this;
  16959. var labelOpts = me.options.labels || {};
  16960. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  16961. if (labelOpts.filter) {
  16962. legendItems = legendItems.filter(function(item) {
  16963. return labelOpts.filter(item, me.chart.data);
  16964. });
  16965. }
  16966. if (me.options.reverse) {
  16967. legendItems.reverse();
  16968. }
  16969. me.legendItems = legendItems;
  16970. },
  16971. afterBuildLabels: noop$1,
  16972. //
  16973. beforeFit: noop$1,
  16974. fit: function() {
  16975. var me = this;
  16976. var opts = me.options;
  16977. var labelOpts = opts.labels;
  16978. var display = opts.display;
  16979. var ctx = me.ctx;
  16980. var labelFont = helpers$1.options._parseFont(labelOpts);
  16981. var fontSize = labelFont.size;
  16982. // Reset hit boxes
  16983. var hitboxes = me.legendHitBoxes = [];
  16984. var minSize = me.minSize;
  16985. var isHorizontal = me.isHorizontal();
  16986. if (isHorizontal) {
  16987. minSize.width = me.maxWidth; // fill all the width
  16988. minSize.height = display ? 10 : 0;
  16989. } else {
  16990. minSize.width = display ? 10 : 0;
  16991. minSize.height = me.maxHeight; // fill all the height
  16992. }
  16993. // Increase sizes here
  16994. if (!display) {
  16995. me.width = minSize.width = me.height = minSize.height = 0;
  16996. return;
  16997. }
  16998. ctx.font = labelFont.string;
  16999. if (isHorizontal) {
  17000. // Labels
  17001. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  17002. var lineWidths = me.lineWidths = [0];
  17003. var totalHeight = 0;
  17004. ctx.textAlign = 'left';
  17005. ctx.textBaseline = 'middle';
  17006. helpers$1.each(me.legendItems, function(legendItem, i) {
  17007. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17008. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  17009. if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {
  17010. totalHeight += fontSize + labelOpts.padding;
  17011. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  17012. }
  17013. // Store the hitbox width and height here. Final position will be updated in `draw`
  17014. hitboxes[i] = {
  17015. left: 0,
  17016. top: 0,
  17017. width: width,
  17018. height: fontSize
  17019. };
  17020. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  17021. });
  17022. minSize.height += totalHeight;
  17023. } else {
  17024. var vPadding = labelOpts.padding;
  17025. var columnWidths = me.columnWidths = [];
  17026. var columnHeights = me.columnHeights = [];
  17027. var totalWidth = labelOpts.padding;
  17028. var currentColWidth = 0;
  17029. var currentColHeight = 0;
  17030. helpers$1.each(me.legendItems, function(legendItem, i) {
  17031. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17032. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  17033. // If too tall, go to new column
  17034. if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) {
  17035. totalWidth += currentColWidth + labelOpts.padding;
  17036. columnWidths.push(currentColWidth); // previous column width
  17037. columnHeights.push(currentColHeight);
  17038. currentColWidth = 0;
  17039. currentColHeight = 0;
  17040. }
  17041. // Get max width
  17042. currentColWidth = Math.max(currentColWidth, itemWidth);
  17043. currentColHeight += fontSize + vPadding;
  17044. // Store the hitbox width and height here. Final position will be updated in `draw`
  17045. hitboxes[i] = {
  17046. left: 0,
  17047. top: 0,
  17048. width: itemWidth,
  17049. height: fontSize
  17050. };
  17051. });
  17052. totalWidth += currentColWidth;
  17053. columnWidths.push(currentColWidth);
  17054. columnHeights.push(currentColHeight);
  17055. minSize.width += totalWidth;
  17056. }
  17057. me.width = minSize.width;
  17058. me.height = minSize.height;
  17059. },
  17060. afterFit: noop$1,
  17061. // Shared Methods
  17062. isHorizontal: function() {
  17063. return this.options.position === 'top' || this.options.position === 'bottom';
  17064. },
  17065. // Actually draw the legend on the canvas
  17066. draw: function() {
  17067. var me = this;
  17068. var opts = me.options;
  17069. var labelOpts = opts.labels;
  17070. var globalDefaults = core_defaults.global;
  17071. var defaultColor = globalDefaults.defaultColor;
  17072. var lineDefault = globalDefaults.elements.line;
  17073. var legendHeight = me.height;
  17074. var columnHeights = me.columnHeights;
  17075. var legendWidth = me.width;
  17076. var lineWidths = me.lineWidths;
  17077. if (!opts.display) {
  17078. return;
  17079. }
  17080. var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);
  17081. var ctx = me.ctx;
  17082. var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);
  17083. var labelFont = helpers$1.options._parseFont(labelOpts);
  17084. var fontSize = labelFont.size;
  17085. var cursor;
  17086. // Canvas setup
  17087. ctx.textAlign = rtlHelper.textAlign('left');
  17088. ctx.textBaseline = 'middle';
  17089. ctx.lineWidth = 0.5;
  17090. ctx.strokeStyle = fontColor; // for strikethrough effect
  17091. ctx.fillStyle = fontColor; // render in correct colour
  17092. ctx.font = labelFont.string;
  17093. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17094. var hitboxes = me.legendHitBoxes;
  17095. var labelFontSize = 16;
  17096. // current position
  17097. var drawLegendBox = function(x, y, legendItem) {
  17098. if (isNaN(boxWidth) || boxWidth <= 0) {
  17099. return;
  17100. }
  17101. // Set the ctx for the box
  17102. ctx.save();
  17103. var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);
  17104. ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);
  17105. ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);
  17106. ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  17107. ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);
  17108. ctx.lineWidth = lineWidth;
  17109. ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);
  17110. if (ctx.setLineDash) {
  17111. // IE 9 and 10 do not support line dash
  17112. ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));
  17113. }
  17114. // if (labelOpts && labelOpts.usePointStyle) {
  17115. if (true) {
  17116. // Recalculate x and y for drawPoint() because its expecting
  17117. // x and y to be center of figure (instead of top left)
  17118. boxWidth = labelFontSize - 5;
  17119. var radius = boxWidth * Math.SQRT2 / 2;
  17120. var centerX = rtlHelper.xPlus(x, boxWidth / 2);
  17121. var centerY = y + fontSize / 2;
  17122. // Draw pointStyle as legend symbol
  17123. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
  17124. } else {
  17125. // Draw box as legend symbol
  17126. ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  17127. if (lineWidth !== 0) {
  17128. ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  17129. }
  17130. }
  17131. ctx.restore();
  17132. };
  17133. var fillText = function(x, y, legendItem, textWidth) {
  17134. var halfFontSize = labelFontSize / 2;
  17135. var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
  17136. var yMiddle = y + halfFontSize;
  17137. let font_ = ctx.font
  17138. ctx.font = ctx.font.replace(/12px/g, labelFontSize + "px")
  17139. ctx.fillText(legendItem.text, xLeft, yMiddle);
  17140. ctx.font = font_
  17141. if (legendItem.hidden) {
  17142. // Strikethrough the text if hidden
  17143. ctx.beginPath();
  17144. ctx.lineWidth = 2;
  17145. ctx.moveTo(xLeft, yMiddle);
  17146. ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);
  17147. ctx.stroke();
  17148. }
  17149. };
  17150. var alignmentOffset = function(dimension, blockSize) {
  17151. switch (opts.align) {
  17152. case 'start':
  17153. return labelOpts.padding;
  17154. case 'end':
  17155. return dimension - blockSize;
  17156. default: // center
  17157. return (dimension - blockSize + labelOpts.padding) / 2;
  17158. }
  17159. };
  17160. // Horizontal
  17161. var isHorizontal = me.isHorizontal();
  17162. if (isHorizontal) {
  17163. cursor = {
  17164. x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
  17165. y: me.top + labelOpts.padding,
  17166. line: 0
  17167. };
  17168. } else {
  17169. cursor = {
  17170. x: me.left + labelOpts.padding,
  17171. y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
  17172. line: 0
  17173. };
  17174. }
  17175. helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);
  17176. var itemHeight = fontSize + labelOpts.padding;
  17177. helpers$1.each(me.legendItems, function(legendItem, i) {
  17178. let font_ = ctx.font
  17179. ctx.font = ctx.font.replace(/12px/g, labelFontSize + "px")
  17180. var textWidth = ctx.measureText(legendItem.text).width;
  17181. ctx.font = font_
  17182. var width = boxWidth + (fontSize / 2) + textWidth;
  17183. var x = cursor.x;
  17184. var y = cursor.y;
  17185. rtlHelper.setWidth(me.minSize.width);
  17186. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  17187. // instead of me.right and me.bottom because me.width and me.height
  17188. // may have been changed since me.minSize was calculated
  17189. if (isHorizontal) {
  17190. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  17191. y = cursor.y += itemHeight;
  17192. cursor.line++;
  17193. x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
  17194. }
  17195. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  17196. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  17197. cursor.line++;
  17198. y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
  17199. }
  17200. if (i === 0)
  17201. x += 28
  17202. var realX = rtlHelper.x(x);
  17203. drawLegendBox(realX, y, legendItem);
  17204. hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);
  17205. hitboxes[i].top = y;
  17206. // Fill the actual label
  17207. fillText(realX, y, legendItem, textWidth);
  17208. if (isHorizontal) {
  17209. cursor.x += width + labelOpts.padding;
  17210. } else {
  17211. cursor.y += itemHeight;
  17212. }
  17213. });
  17214. helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);
  17215. },
  17216. /**
  17217. * @private
  17218. */
  17219. _getLegendItemAt: function(x, y) {
  17220. var me = this;
  17221. var i, hitBox, lh;
  17222. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  17223. // See if we are touching one of the dataset boxes
  17224. lh = me.legendHitBoxes;
  17225. for (i = 0; i < lh.length; ++i) {
  17226. hitBox = lh[i];
  17227. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  17228. // Touching an element
  17229. return me.legendItems[i];
  17230. }
  17231. }
  17232. }
  17233. return null;
  17234. },
  17235. /**
  17236. * Handle an event
  17237. * @private
  17238. * @param {IEvent} event - The event to handle
  17239. */
  17240. handleEvent: function(e) {
  17241. var me = this;
  17242. var opts = me.options;
  17243. var type = e.type === 'mouseup' ? 'click' : e.type;
  17244. var hoveredItem;
  17245. if (type === 'mousemove') {
  17246. if (!opts.onHover && !opts.onLeave) {
  17247. return;
  17248. }
  17249. } else if (type === 'click') {
  17250. if (!opts.onClick) {
  17251. return;
  17252. }
  17253. } else {
  17254. return;
  17255. }
  17256. // Chart event already has relative position in it
  17257. hoveredItem = me._getLegendItemAt(e.x, e.y);
  17258. if (type === 'click') {
  17259. if (hoveredItem && opts.onClick) {
  17260. // use e.native for backwards compatibility
  17261. opts.onClick.call(me, e.native, hoveredItem);
  17262. }
  17263. } else {
  17264. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  17265. if (me._hoveredItem) {
  17266. opts.onLeave.call(me, e.native, me._hoveredItem);
  17267. }
  17268. me._hoveredItem = hoveredItem;
  17269. }
  17270. if (opts.onHover && hoveredItem) {
  17271. // use e.native for backwards compatibility
  17272. opts.onHover.call(me, e.native, hoveredItem);
  17273. }
  17274. }
  17275. }
  17276. });
  17277. function createNewLegendAndAttach(chart, legendOpts) {
  17278. var legend = new Legend({
  17279. ctx: chart.ctx,
  17280. options: legendOpts,
  17281. chart: chart
  17282. });
  17283. core_layouts.configure(chart, legend, legendOpts);
  17284. core_layouts.addBox(chart, legend);
  17285. chart.legend = legend;
  17286. }
  17287. var plugin_legend = {
  17288. id: 'legend',
  17289. /**
  17290. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  17291. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  17292. * the plugin, which one will be re-exposed in the chart.js file.
  17293. * https://github.com/chartjs/Chart.js/pull/2640
  17294. * @private
  17295. */
  17296. _element: Legend,
  17297. beforeInit: function(chart) {
  17298. var legendOpts = chart.options.legend;
  17299. if (legendOpts) {
  17300. createNewLegendAndAttach(chart, legendOpts);
  17301. }
  17302. },
  17303. beforeUpdate: function(chart) {
  17304. var legendOpts = chart.options.legend;
  17305. var legend = chart.legend;
  17306. if (legendOpts) {
  17307. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  17308. if (legend) {
  17309. core_layouts.configure(chart, legend, legendOpts);
  17310. legend.options = legendOpts;
  17311. } else {
  17312. createNewLegendAndAttach(chart, legendOpts);
  17313. }
  17314. } else if (legend) {
  17315. core_layouts.removeBox(chart, legend);
  17316. delete chart.legend;
  17317. }
  17318. },
  17319. afterEvent: function(chart, e) {
  17320. var legend = chart.legend;
  17321. if (legend) {
  17322. legend.handleEvent(e);
  17323. }
  17324. }
  17325. };
  17326. var noop$2 = helpers$1.noop;
  17327. core_defaults._set('global', {
  17328. title: {
  17329. display: false,
  17330. fontStyle: 'bold',
  17331. fullWidth: true,
  17332. padding: 10,
  17333. position: 'top',
  17334. text: '',
  17335. weight: 2000 // by default greater than legend (1000) to be above
  17336. }
  17337. });
  17338. /**
  17339. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  17340. */
  17341. var Title = core_element.extend({
  17342. initialize: function(config) {
  17343. var me = this;
  17344. helpers$1.extend(me, config);
  17345. // Contains hit boxes for each dataset (in dataset order)
  17346. me.legendHitBoxes = [];
  17347. },
  17348. // These methods are ordered by lifecycle. Utilities then follow.
  17349. beforeUpdate: noop$2,
  17350. update: function(maxWidth, maxHeight, margins) {
  17351. var me = this;
  17352. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  17353. me.beforeUpdate();
  17354. // Absorb the master measurements
  17355. me.maxWidth = maxWidth;
  17356. me.maxHeight = maxHeight;
  17357. me.margins = margins;
  17358. // Dimensions
  17359. me.beforeSetDimensions();
  17360. me.setDimensions();
  17361. me.afterSetDimensions();
  17362. // Labels
  17363. me.beforeBuildLabels();
  17364. me.buildLabels();
  17365. me.afterBuildLabels();
  17366. // Fit
  17367. me.beforeFit();
  17368. me.fit();
  17369. me.afterFit();
  17370. //
  17371. me.afterUpdate();
  17372. return me.minSize;
  17373. },
  17374. afterUpdate: noop$2,
  17375. //
  17376. beforeSetDimensions: noop$2,
  17377. setDimensions: function() {
  17378. var me = this;
  17379. // Set the unconstrained dimension before label rotation
  17380. if (me.isHorizontal()) {
  17381. // Reset position before calculating rotation
  17382. me.width = me.maxWidth;
  17383. me.left = 0;
  17384. me.right = me.width;
  17385. } else {
  17386. me.height = me.maxHeight;
  17387. // Reset position before calculating rotation
  17388. me.top = 0;
  17389. me.bottom = me.height;
  17390. }
  17391. // Reset padding
  17392. me.paddingLeft = 0;
  17393. me.paddingTop = 0;
  17394. me.paddingRight = 0;
  17395. me.paddingBottom = 0;
  17396. // Reset minSize
  17397. me.minSize = {
  17398. width: 0,
  17399. height: 0
  17400. };
  17401. },
  17402. afterSetDimensions: noop$2,
  17403. //
  17404. beforeBuildLabels: noop$2,
  17405. buildLabels: noop$2,
  17406. afterBuildLabels: noop$2,
  17407. //
  17408. beforeFit: noop$2,
  17409. fit: function() {
  17410. var me = this;
  17411. var opts = me.options;
  17412. var minSize = me.minSize = {};
  17413. var isHorizontal = me.isHorizontal();
  17414. var lineCount, textSize;
  17415. if (!opts.display) {
  17416. me.width = minSize.width = me.height = minSize.height = 0;
  17417. return;
  17418. }
  17419. lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  17420. textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;
  17421. me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
  17422. me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
  17423. },
  17424. afterFit: noop$2,
  17425. // Shared Methods
  17426. isHorizontal: function() {
  17427. var pos = this.options.position;
  17428. return pos === 'top' || pos === 'bottom';
  17429. },
  17430. // Actually draw the title block on the canvas
  17431. draw: function() {
  17432. var me = this;
  17433. var ctx = me.ctx;
  17434. var opts = me.options;
  17435. if (!opts.display) {
  17436. return;
  17437. }
  17438. var fontOpts = helpers$1.options._parseFont(opts);
  17439. var lineHeight = fontOpts.lineHeight;
  17440. var offset = lineHeight / 2 + opts.padding;
  17441. var rotation = 0;
  17442. var top = me.top;
  17443. var left = me.left;
  17444. var bottom = me.bottom;
  17445. var right = me.right;
  17446. var maxWidth, titleX, titleY;
  17447. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  17448. ctx.font = fontOpts.string;
  17449. // Horizontal
  17450. if (me.isHorizontal()) {
  17451. titleX = left + ((right - left) / 2); // midpoint of the width
  17452. titleY = top + offset;
  17453. maxWidth = right - left;
  17454. } else {
  17455. titleX = opts.position === 'left' ? left + offset : right - offset;
  17456. titleY = top + ((bottom - top) / 2);
  17457. maxWidth = bottom - top;
  17458. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  17459. }
  17460. ctx.save();
  17461. ctx.translate(titleX, titleY);
  17462. ctx.rotate(rotation);
  17463. ctx.textAlign = 'center';
  17464. ctx.textBaseline = 'middle';
  17465. var text = opts.text;
  17466. if (helpers$1.isArray(text)) {
  17467. var y = 0;
  17468. for (var i = 0; i < text.length; ++i) {
  17469. ctx.fillText(text[i], 0, y, maxWidth);
  17470. y += lineHeight;
  17471. }
  17472. } else {
  17473. ctx.fillText(text, 0, 0, maxWidth);
  17474. }
  17475. ctx.restore();
  17476. }
  17477. });
  17478. function createNewTitleBlockAndAttach(chart, titleOpts) {
  17479. var title = new Title({
  17480. ctx: chart.ctx,
  17481. options: titleOpts,
  17482. chart: chart
  17483. });
  17484. core_layouts.configure(chart, title, titleOpts);
  17485. core_layouts.addBox(chart, title);
  17486. chart.titleBlock = title;
  17487. }
  17488. var plugin_title = {
  17489. id: 'title',
  17490. /**
  17491. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  17492. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  17493. * the plugin, which one will be re-exposed in the chart.js file.
  17494. * https://github.com/chartjs/Chart.js/pull/2640
  17495. * @private
  17496. */
  17497. _element: Title,
  17498. beforeInit: function(chart) {
  17499. var titleOpts = chart.options.title;
  17500. if (titleOpts) {
  17501. createNewTitleBlockAndAttach(chart, titleOpts);
  17502. }
  17503. },
  17504. beforeUpdate: function(chart) {
  17505. var titleOpts = chart.options.title;
  17506. var titleBlock = chart.titleBlock;
  17507. if (titleOpts) {
  17508. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  17509. if (titleBlock) {
  17510. core_layouts.configure(chart, titleBlock, titleOpts);
  17511. titleBlock.options = titleOpts;
  17512. } else {
  17513. createNewTitleBlockAndAttach(chart, titleOpts);
  17514. }
  17515. } else if (titleBlock) {
  17516. core_layouts.removeBox(chart, titleBlock);
  17517. delete chart.titleBlock;
  17518. }
  17519. }
  17520. };
  17521. var plugins = {};
  17522. var filler = plugin_filler;
  17523. var legend = plugin_legend;
  17524. var title = plugin_title;
  17525. plugins.filler = filler;
  17526. plugins.legend = legend;
  17527. plugins.title = title;
  17528. /**
  17529. * @namespace Chart
  17530. */
  17531. core_controller.helpers = helpers$1;
  17532. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  17533. core_helpers();
  17534. core_controller._adapters = core_adapters;
  17535. core_controller.Animation = core_animation;
  17536. core_controller.animationService = core_animations;
  17537. core_controller.controllers = controllers;
  17538. core_controller.DatasetController = core_datasetController;
  17539. core_controller.defaults = core_defaults;
  17540. core_controller.Element = core_element;
  17541. core_controller.elements = elements;
  17542. core_controller.Interaction = core_interaction;
  17543. core_controller.layouts = core_layouts;
  17544. core_controller.platform = platform;
  17545. core_controller.plugins = core_plugins;
  17546. core_controller.Scale = core_scale;
  17547. core_controller.scaleService = core_scaleService;
  17548. core_controller.Ticks = core_ticks;
  17549. core_controller.Tooltip = core_tooltip;
  17550. // Register built-in scales
  17551. core_controller.helpers.each(scales, function(scale, type) {
  17552. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  17553. });
  17554. // Load to register built-in adapters (as side effects)
  17555. // Loading built-in plugins
  17556. for (var k in plugins) {
  17557. if (plugins.hasOwnProperty(k)) {
  17558. core_controller.plugins.register(plugins[k]);
  17559. }
  17560. }
  17561. core_controller.platform.initialize();
  17562. var src = core_controller;
  17563. if (typeof window !== 'undefined') {
  17564. window.Chart = core_controller;
  17565. }
  17566. // DEPRECATIONS
  17567. /**
  17568. * Provided for backward compatibility, not available anymore
  17569. * @namespace Chart.Chart
  17570. * @deprecated since version 2.8.0
  17571. * @todo remove at version 3
  17572. * @private
  17573. */
  17574. core_controller.Chart = core_controller;
  17575. /**
  17576. * Provided for backward compatibility, not available anymore
  17577. * @namespace Chart.Legend
  17578. * @deprecated since version 2.1.5
  17579. * @todo remove at version 3
  17580. * @private
  17581. */
  17582. core_controller.Legend = plugins.legend._element;
  17583. /**
  17584. * Provided for backward compatibility, not available anymore
  17585. * @namespace Chart.Title
  17586. * @deprecated since version 2.1.5
  17587. * @todo remove at version 3
  17588. * @private
  17589. */
  17590. core_controller.Title = plugins.title._element;
  17591. /**
  17592. * Provided for backward compatibility, use Chart.plugins instead
  17593. * @namespace Chart.pluginService
  17594. * @deprecated since version 2.1.5
  17595. * @todo remove at version 3
  17596. * @private
  17597. */
  17598. core_controller.pluginService = core_controller.plugins;
  17599. /**
  17600. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  17601. * effect, instead simply create/register plugins via plain JavaScript objects.
  17602. * @interface Chart.PluginBase
  17603. * @deprecated since version 2.5.0
  17604. * @todo remove at version 3
  17605. * @private
  17606. */
  17607. core_controller.PluginBase = core_controller.Element.extend({});
  17608. /**
  17609. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  17610. * @namespace Chart.canvasHelpers
  17611. * @deprecated since version 2.6.0
  17612. * @todo remove at version 3
  17613. * @private
  17614. */
  17615. core_controller.canvasHelpers = core_controller.helpers.canvas;
  17616. /**
  17617. * Provided for backward compatibility, use Chart.layouts instead.
  17618. * @namespace Chart.layoutService
  17619. * @deprecated since version 2.7.3
  17620. * @todo remove at version 3
  17621. * @private
  17622. */
  17623. core_controller.layoutService = core_controller.layouts;
  17624. /**
  17625. * Provided for backward compatibility, not available anymore.
  17626. * @namespace Chart.LinearScaleBase
  17627. * @deprecated since version 2.8
  17628. * @todo remove at version 3
  17629. * @private
  17630. */
  17631. core_controller.LinearScaleBase = scale_linearbase;
  17632. /**
  17633. * Provided for backward compatibility, instead we should create a new Chart
  17634. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  17635. * @deprecated since version 2.8.0
  17636. * @todo remove at version 3
  17637. */
  17638. core_controller.helpers.each(
  17639. [
  17640. 'Bar',
  17641. 'Bubble',
  17642. 'Doughnut',
  17643. 'Line',
  17644. 'PolarArea',
  17645. 'Radar',
  17646. 'Scatter'
  17647. ],
  17648. function(klass) {
  17649. core_controller[klass] = function(ctx, cfg) {
  17650. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  17651. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  17652. }));
  17653. };
  17654. }
  17655. );
  17656. return src;
  17657. })));