Chart.js 387 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681
  1. /*!
  2. * Chart.js v2.8.0
  3. * https://www.chartjs.org
  4. * (c) 2019 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(function() { try { return require('moment'); } catch(e) { } }()) :
  9. typeof define === 'function' && define.amd ? define(['require'], function(require) { return factory(function() { try { return require('moment'); } catch(e) { } }()); }) :
  10. (global.Chart = factory(global.moment));
  11. }(this, (function (moment) { 'use strict';
  12. moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;
  13. /* MIT license */
  14. var conversions = {
  15. rgb2hsl: rgb2hsl,
  16. rgb2hsv: rgb2hsv,
  17. rgb2hwb: rgb2hwb,
  18. rgb2cmyk: rgb2cmyk,
  19. rgb2keyword: rgb2keyword,
  20. rgb2xyz: rgb2xyz,
  21. rgb2lab: rgb2lab,
  22. rgb2lch: rgb2lch,
  23. hsl2rgb: hsl2rgb,
  24. hsl2hsv: hsl2hsv,
  25. hsl2hwb: hsl2hwb,
  26. hsl2cmyk: hsl2cmyk,
  27. hsl2keyword: hsl2keyword,
  28. hsv2rgb: hsv2rgb,
  29. hsv2hsl: hsv2hsl,
  30. hsv2hwb: hsv2hwb,
  31. hsv2cmyk: hsv2cmyk,
  32. hsv2keyword: hsv2keyword,
  33. hwb2rgb: hwb2rgb,
  34. hwb2hsl: hwb2hsl,
  35. hwb2hsv: hwb2hsv,
  36. hwb2cmyk: hwb2cmyk,
  37. hwb2keyword: hwb2keyword,
  38. cmyk2rgb: cmyk2rgb,
  39. cmyk2hsl: cmyk2hsl,
  40. cmyk2hsv: cmyk2hsv,
  41. cmyk2hwb: cmyk2hwb,
  42. cmyk2keyword: cmyk2keyword,
  43. keyword2rgb: keyword2rgb,
  44. keyword2hsl: keyword2hsl,
  45. keyword2hsv: keyword2hsv,
  46. keyword2hwb: keyword2hwb,
  47. keyword2cmyk: keyword2cmyk,
  48. keyword2lab: keyword2lab,
  49. keyword2xyz: keyword2xyz,
  50. xyz2rgb: xyz2rgb,
  51. xyz2lab: xyz2lab,
  52. xyz2lch: xyz2lch,
  53. lab2xyz: lab2xyz,
  54. lab2rgb: lab2rgb,
  55. lab2lch: lab2lch,
  56. lch2lab: lch2lab,
  57. lch2xyz: lch2xyz,
  58. lch2rgb: lch2rgb
  59. };
  60. function rgb2hsl(rgb) {
  61. var r = rgb[0]/255,
  62. g = rgb[1]/255,
  63. b = rgb[2]/255,
  64. min = Math.min(r, g, b),
  65. max = Math.max(r, g, b),
  66. delta = max - min,
  67. h, s, l;
  68. if (max == min)
  69. h = 0;
  70. else if (r == max)
  71. h = (g - b) / delta;
  72. else if (g == max)
  73. h = 2 + (b - r) / delta;
  74. else if (b == max)
  75. h = 4 + (r - g)/ delta;
  76. h = Math.min(h * 60, 360);
  77. if (h < 0)
  78. h += 360;
  79. l = (min + max) / 2;
  80. if (max == min)
  81. s = 0;
  82. else if (l <= 0.5)
  83. s = delta / (max + min);
  84. else
  85. s = delta / (2 - max - min);
  86. return [h, s * 100, l * 100];
  87. }
  88. function rgb2hsv(rgb) {
  89. var r = rgb[0],
  90. g = rgb[1],
  91. b = rgb[2],
  92. min = Math.min(r, g, b),
  93. max = Math.max(r, g, b),
  94. delta = max - min,
  95. h, s, v;
  96. if (max == 0)
  97. s = 0;
  98. else
  99. s = (delta/max * 1000)/10;
  100. if (max == min)
  101. h = 0;
  102. else if (r == max)
  103. h = (g - b) / delta;
  104. else if (g == max)
  105. h = 2 + (b - r) / delta;
  106. else if (b == max)
  107. h = 4 + (r - g) / delta;
  108. h = Math.min(h * 60, 360);
  109. if (h < 0)
  110. h += 360;
  111. v = ((max / 255) * 1000) / 10;
  112. return [h, s, v];
  113. }
  114. function rgb2hwb(rgb) {
  115. var r = rgb[0],
  116. g = rgb[1],
  117. b = rgb[2],
  118. h = rgb2hsl(rgb)[0],
  119. w = 1/255 * Math.min(r, Math.min(g, b)),
  120. b = 1 - 1/255 * Math.max(r, Math.max(g, b));
  121. return [h, w * 100, b * 100];
  122. }
  123. function rgb2cmyk(rgb) {
  124. var r = rgb[0] / 255,
  125. g = rgb[1] / 255,
  126. b = rgb[2] / 255,
  127. c, m, y, k;
  128. k = Math.min(1 - r, 1 - g, 1 - b);
  129. c = (1 - r - k) / (1 - k) || 0;
  130. m = (1 - g - k) / (1 - k) || 0;
  131. y = (1 - b - k) / (1 - k) || 0;
  132. return [c * 100, m * 100, y * 100, k * 100];
  133. }
  134. function rgb2keyword(rgb) {
  135. return reverseKeywords[JSON.stringify(rgb)];
  136. }
  137. function rgb2xyz(rgb) {
  138. var r = rgb[0] / 255,
  139. g = rgb[1] / 255,
  140. b = rgb[2] / 255;
  141. // assume sRGB
  142. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  143. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  144. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  145. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  146. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  147. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  148. return [x * 100, y *100, z * 100];
  149. }
  150. function rgb2lab(rgb) {
  151. var xyz = rgb2xyz(rgb),
  152. x = xyz[0],
  153. y = xyz[1],
  154. z = xyz[2],
  155. l, a, b;
  156. x /= 95.047;
  157. y /= 100;
  158. z /= 108.883;
  159. x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
  160. y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
  161. z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
  162. l = (116 * y) - 16;
  163. a = 500 * (x - y);
  164. b = 200 * (y - z);
  165. return [l, a, b];
  166. }
  167. function rgb2lch(args) {
  168. return lab2lch(rgb2lab(args));
  169. }
  170. function hsl2rgb(hsl) {
  171. var h = hsl[0] / 360,
  172. s = hsl[1] / 100,
  173. l = hsl[2] / 100,
  174. t1, t2, t3, rgb, val;
  175. if (s == 0) {
  176. val = l * 255;
  177. return [val, val, val];
  178. }
  179. if (l < 0.5)
  180. t2 = l * (1 + s);
  181. else
  182. t2 = l + s - l * s;
  183. t1 = 2 * l - t2;
  184. rgb = [0, 0, 0];
  185. for (var i = 0; i < 3; i++) {
  186. t3 = h + 1 / 3 * - (i - 1);
  187. t3 < 0 && t3++;
  188. t3 > 1 && t3--;
  189. if (6 * t3 < 1)
  190. val = t1 + (t2 - t1) * 6 * t3;
  191. else if (2 * t3 < 1)
  192. val = t2;
  193. else if (3 * t3 < 2)
  194. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  195. else
  196. val = t1;
  197. rgb[i] = val * 255;
  198. }
  199. return rgb;
  200. }
  201. function hsl2hsv(hsl) {
  202. var h = hsl[0],
  203. s = hsl[1] / 100,
  204. l = hsl[2] / 100,
  205. sv, v;
  206. if(l === 0) {
  207. // no need to do calc on black
  208. // also avoids divide by 0 error
  209. return [0, 0, 0];
  210. }
  211. l *= 2;
  212. s *= (l <= 1) ? l : 2 - l;
  213. v = (l + s) / 2;
  214. sv = (2 * s) / (l + s);
  215. return [h, sv * 100, v * 100];
  216. }
  217. function hsl2hwb(args) {
  218. return rgb2hwb(hsl2rgb(args));
  219. }
  220. function hsl2cmyk(args) {
  221. return rgb2cmyk(hsl2rgb(args));
  222. }
  223. function hsl2keyword(args) {
  224. return rgb2keyword(hsl2rgb(args));
  225. }
  226. function hsv2rgb(hsv) {
  227. var h = hsv[0] / 60,
  228. s = hsv[1] / 100,
  229. v = hsv[2] / 100,
  230. hi = Math.floor(h) % 6;
  231. var f = h - Math.floor(h),
  232. p = 255 * v * (1 - s),
  233. q = 255 * v * (1 - (s * f)),
  234. t = 255 * v * (1 - (s * (1 - f))),
  235. v = 255 * v;
  236. switch(hi) {
  237. case 0:
  238. return [v, t, p];
  239. case 1:
  240. return [q, v, p];
  241. case 2:
  242. return [p, v, t];
  243. case 3:
  244. return [p, q, v];
  245. case 4:
  246. return [t, p, v];
  247. case 5:
  248. return [v, p, q];
  249. }
  250. }
  251. function hsv2hsl(hsv) {
  252. var h = hsv[0],
  253. s = hsv[1] / 100,
  254. v = hsv[2] / 100,
  255. sl, l;
  256. l = (2 - s) * v;
  257. sl = s * v;
  258. sl /= (l <= 1) ? l : 2 - l;
  259. sl = sl || 0;
  260. l /= 2;
  261. return [h, sl * 100, l * 100];
  262. }
  263. function hsv2hwb(args) {
  264. return rgb2hwb(hsv2rgb(args))
  265. }
  266. function hsv2cmyk(args) {
  267. return rgb2cmyk(hsv2rgb(args));
  268. }
  269. function hsv2keyword(args) {
  270. return rgb2keyword(hsv2rgb(args));
  271. }
  272. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  273. function hwb2rgb(hwb) {
  274. var h = hwb[0] / 360,
  275. wh = hwb[1] / 100,
  276. bl = hwb[2] / 100,
  277. ratio = wh + bl,
  278. i, v, f, n;
  279. // wh + bl cant be > 1
  280. if (ratio > 1) {
  281. wh /= ratio;
  282. bl /= ratio;
  283. }
  284. i = Math.floor(6 * h);
  285. v = 1 - bl;
  286. f = 6 * h - i;
  287. if ((i & 0x01) != 0) {
  288. f = 1 - f;
  289. }
  290. n = wh + f * (v - wh); // linear interpolation
  291. switch (i) {
  292. default:
  293. case 6:
  294. case 0: r = v; g = n; b = wh; break;
  295. case 1: r = n; g = v; b = wh; break;
  296. case 2: r = wh; g = v; b = n; break;
  297. case 3: r = wh; g = n; b = v; break;
  298. case 4: r = n; g = wh; b = v; break;
  299. case 5: r = v; g = wh; b = n; break;
  300. }
  301. return [r * 255, g * 255, b * 255];
  302. }
  303. function hwb2hsl(args) {
  304. return rgb2hsl(hwb2rgb(args));
  305. }
  306. function hwb2hsv(args) {
  307. return rgb2hsv(hwb2rgb(args));
  308. }
  309. function hwb2cmyk(args) {
  310. return rgb2cmyk(hwb2rgb(args));
  311. }
  312. function hwb2keyword(args) {
  313. return rgb2keyword(hwb2rgb(args));
  314. }
  315. function cmyk2rgb(cmyk) {
  316. var c = cmyk[0] / 100,
  317. m = cmyk[1] / 100,
  318. y = cmyk[2] / 100,
  319. k = cmyk[3] / 100,
  320. r, g, b;
  321. r = 1 - Math.min(1, c * (1 - k) + k);
  322. g = 1 - Math.min(1, m * (1 - k) + k);
  323. b = 1 - Math.min(1, y * (1 - k) + k);
  324. return [r * 255, g * 255, b * 255];
  325. }
  326. function cmyk2hsl(args) {
  327. return rgb2hsl(cmyk2rgb(args));
  328. }
  329. function cmyk2hsv(args) {
  330. return rgb2hsv(cmyk2rgb(args));
  331. }
  332. function cmyk2hwb(args) {
  333. return rgb2hwb(cmyk2rgb(args));
  334. }
  335. function cmyk2keyword(args) {
  336. return rgb2keyword(cmyk2rgb(args));
  337. }
  338. function xyz2rgb(xyz) {
  339. var x = xyz[0] / 100,
  340. y = xyz[1] / 100,
  341. z = xyz[2] / 100,
  342. r, g, b;
  343. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  344. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  345. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  346. // assume sRGB
  347. r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  348. : r = (r * 12.92);
  349. g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  350. : g = (g * 12.92);
  351. b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  352. : b = (b * 12.92);
  353. r = Math.min(Math.max(0, r), 1);
  354. g = Math.min(Math.max(0, g), 1);
  355. b = Math.min(Math.max(0, b), 1);
  356. return [r * 255, g * 255, b * 255];
  357. }
  358. function xyz2lab(xyz) {
  359. var x = xyz[0],
  360. y = xyz[1],
  361. z = xyz[2],
  362. l, a, b;
  363. x /= 95.047;
  364. y /= 100;
  365. z /= 108.883;
  366. x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
  367. y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
  368. z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
  369. l = (116 * y) - 16;
  370. a = 500 * (x - y);
  371. b = 200 * (y - z);
  372. return [l, a, b];
  373. }
  374. function xyz2lch(args) {
  375. return lab2lch(xyz2lab(args));
  376. }
  377. function lab2xyz(lab) {
  378. var l = lab[0],
  379. a = lab[1],
  380. b = lab[2],
  381. x, y, z, y2;
  382. if (l <= 8) {
  383. y = (l * 100) / 903.3;
  384. y2 = (7.787 * (y / 100)) + (16 / 116);
  385. } else {
  386. y = 100 * Math.pow((l + 16) / 116, 3);
  387. y2 = Math.pow(y / 100, 1/3);
  388. }
  389. x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
  390. z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
  391. return [x, y, z];
  392. }
  393. function lab2lch(lab) {
  394. var l = lab[0],
  395. a = lab[1],
  396. b = lab[2],
  397. hr, h, c;
  398. hr = Math.atan2(b, a);
  399. h = hr * 360 / 2 / Math.PI;
  400. if (h < 0) {
  401. h += 360;
  402. }
  403. c = Math.sqrt(a * a + b * b);
  404. return [l, c, h];
  405. }
  406. function lab2rgb(args) {
  407. return xyz2rgb(lab2xyz(args));
  408. }
  409. function lch2lab(lch) {
  410. var l = lch[0],
  411. c = lch[1],
  412. h = lch[2],
  413. a, b, hr;
  414. hr = h / 360 * 2 * Math.PI;
  415. a = c * Math.cos(hr);
  416. b = c * Math.sin(hr);
  417. return [l, a, b];
  418. }
  419. function lch2xyz(args) {
  420. return lab2xyz(lch2lab(args));
  421. }
  422. function lch2rgb(args) {
  423. return lab2rgb(lch2lab(args));
  424. }
  425. function keyword2rgb(keyword) {
  426. return cssKeywords[keyword];
  427. }
  428. function keyword2hsl(args) {
  429. return rgb2hsl(keyword2rgb(args));
  430. }
  431. function keyword2hsv(args) {
  432. return rgb2hsv(keyword2rgb(args));
  433. }
  434. function keyword2hwb(args) {
  435. return rgb2hwb(keyword2rgb(args));
  436. }
  437. function keyword2cmyk(args) {
  438. return rgb2cmyk(keyword2rgb(args));
  439. }
  440. function keyword2lab(args) {
  441. return rgb2lab(keyword2rgb(args));
  442. }
  443. function keyword2xyz(args) {
  444. return rgb2xyz(keyword2rgb(args));
  445. }
  446. var cssKeywords = {
  447. aliceblue: [240,248,255],
  448. antiquewhite: [250,235,215],
  449. aqua: [0,255,255],
  450. aquamarine: [127,255,212],
  451. azure: [240,255,255],
  452. beige: [245,245,220],
  453. bisque: [255,228,196],
  454. black: [0,0,0],
  455. blanchedalmond: [255,235,205],
  456. blue: [0,0,255],
  457. blueviolet: [138,43,226],
  458. brown: [165,42,42],
  459. burlywood: [222,184,135],
  460. cadetblue: [95,158,160],
  461. chartreuse: [127,255,0],
  462. chocolate: [210,105,30],
  463. coral: [255,127,80],
  464. cornflowerblue: [100,149,237],
  465. cornsilk: [255,248,220],
  466. crimson: [220,20,60],
  467. cyan: [0,255,255],
  468. darkblue: [0,0,139],
  469. darkcyan: [0,139,139],
  470. darkgoldenrod: [184,134,11],
  471. darkgray: [169,169,169],
  472. darkgreen: [0,100,0],
  473. darkgrey: [169,169,169],
  474. darkkhaki: [189,183,107],
  475. darkmagenta: [139,0,139],
  476. darkolivegreen: [85,107,47],
  477. darkorange: [255,140,0],
  478. darkorchid: [153,50,204],
  479. darkred: [139,0,0],
  480. darksalmon: [233,150,122],
  481. darkseagreen: [143,188,143],
  482. darkslateblue: [72,61,139],
  483. darkslategray: [47,79,79],
  484. darkslategrey: [47,79,79],
  485. darkturquoise: [0,206,209],
  486. darkviolet: [148,0,211],
  487. deeppink: [255,20,147],
  488. deepskyblue: [0,191,255],
  489. dimgray: [105,105,105],
  490. dimgrey: [105,105,105],
  491. dodgerblue: [30,144,255],
  492. firebrick: [178,34,34],
  493. floralwhite: [255,250,240],
  494. forestgreen: [34,139,34],
  495. fuchsia: [255,0,255],
  496. gainsboro: [220,220,220],
  497. ghostwhite: [248,248,255],
  498. gold: [255,215,0],
  499. goldenrod: [218,165,32],
  500. gray: [128,128,128],
  501. green: [0,128,0],
  502. greenyellow: [173,255,47],
  503. grey: [128,128,128],
  504. honeydew: [240,255,240],
  505. hotpink: [255,105,180],
  506. indianred: [205,92,92],
  507. indigo: [75,0,130],
  508. ivory: [255,255,240],
  509. khaki: [240,230,140],
  510. lavender: [230,230,250],
  511. lavenderblush: [255,240,245],
  512. lawngreen: [124,252,0],
  513. lemonchiffon: [255,250,205],
  514. lightblue: [173,216,230],
  515. lightcoral: [240,128,128],
  516. lightcyan: [224,255,255],
  517. lightgoldenrodyellow: [250,250,210],
  518. lightgray: [211,211,211],
  519. lightgreen: [144,238,144],
  520. lightgrey: [211,211,211],
  521. lightpink: [255,182,193],
  522. lightsalmon: [255,160,122],
  523. lightseagreen: [32,178,170],
  524. lightskyblue: [135,206,250],
  525. lightslategray: [119,136,153],
  526. lightslategrey: [119,136,153],
  527. lightsteelblue: [176,196,222],
  528. lightyellow: [255,255,224],
  529. lime: [0,255,0],
  530. limegreen: [50,205,50],
  531. linen: [250,240,230],
  532. magenta: [255,0,255],
  533. maroon: [128,0,0],
  534. mediumaquamarine: [102,205,170],
  535. mediumblue: [0,0,205],
  536. mediumorchid: [186,85,211],
  537. mediumpurple: [147,112,219],
  538. mediumseagreen: [60,179,113],
  539. mediumslateblue: [123,104,238],
  540. mediumspringgreen: [0,250,154],
  541. mediumturquoise: [72,209,204],
  542. mediumvioletred: [199,21,133],
  543. midnightblue: [25,25,112],
  544. mintcream: [245,255,250],
  545. mistyrose: [255,228,225],
  546. moccasin: [255,228,181],
  547. navajowhite: [255,222,173],
  548. navy: [0,0,128],
  549. oldlace: [253,245,230],
  550. olive: [128,128,0],
  551. olivedrab: [107,142,35],
  552. orange: [255,165,0],
  553. orangered: [255,69,0],
  554. orchid: [218,112,214],
  555. palegoldenrod: [238,232,170],
  556. palegreen: [152,251,152],
  557. paleturquoise: [175,238,238],
  558. palevioletred: [219,112,147],
  559. papayawhip: [255,239,213],
  560. peachpuff: [255,218,185],
  561. peru: [205,133,63],
  562. pink: [255,192,203],
  563. plum: [221,160,221],
  564. powderblue: [176,224,230],
  565. purple: [128,0,128],
  566. rebeccapurple: [102, 51, 153],
  567. red: [255,0,0],
  568. rosybrown: [188,143,143],
  569. royalblue: [65,105,225],
  570. saddlebrown: [139,69,19],
  571. salmon: [250,128,114],
  572. sandybrown: [244,164,96],
  573. seagreen: [46,139,87],
  574. seashell: [255,245,238],
  575. sienna: [160,82,45],
  576. silver: [192,192,192],
  577. skyblue: [135,206,235],
  578. slateblue: [106,90,205],
  579. slategray: [112,128,144],
  580. slategrey: [112,128,144],
  581. snow: [255,250,250],
  582. springgreen: [0,255,127],
  583. steelblue: [70,130,180],
  584. tan: [210,180,140],
  585. teal: [0,128,128],
  586. thistle: [216,191,216],
  587. tomato: [255,99,71],
  588. turquoise: [64,224,208],
  589. violet: [238,130,238],
  590. wheat: [245,222,179],
  591. white: [255,255,255],
  592. whitesmoke: [245,245,245],
  593. yellow: [255,255,0],
  594. yellowgreen: [154,205,50]
  595. };
  596. var reverseKeywords = {};
  597. for (var key in cssKeywords) {
  598. reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
  599. }
  600. var convert = function() {
  601. return new Converter();
  602. };
  603. for (var func in conversions) {
  604. // export Raw versions
  605. convert[func + "Raw"] = (function(func) {
  606. // accept array or plain args
  607. return function(arg) {
  608. if (typeof arg == "number")
  609. arg = Array.prototype.slice.call(arguments);
  610. return conversions[func](arg);
  611. }
  612. })(func);
  613. var pair = /(\w+)2(\w+)/.exec(func),
  614. from = pair[1],
  615. to = pair[2];
  616. // export rgb2hsl and ["rgb"]["hsl"]
  617. convert[from] = convert[from] || {};
  618. convert[from][to] = convert[func] = (function(func) {
  619. return function(arg) {
  620. if (typeof arg == "number")
  621. arg = Array.prototype.slice.call(arguments);
  622. var val = conversions[func](arg);
  623. if (typeof val == "string" || val === undefined)
  624. return val; // keyword
  625. for (var i = 0; i < val.length; i++)
  626. val[i] = Math.round(val[i]);
  627. return val;
  628. }
  629. })(func);
  630. }
  631. /* Converter does lazy conversion and caching */
  632. var Converter = function() {
  633. this.convs = {};
  634. };
  635. /* Either get the values for a space or
  636. set the values for a space, depending on args */
  637. Converter.prototype.routeSpace = function(space, args) {
  638. var values = args[0];
  639. if (values === undefined) {
  640. // color.rgb()
  641. return this.getValues(space);
  642. }
  643. // color.rgb(10, 10, 10)
  644. if (typeof values == "number") {
  645. values = Array.prototype.slice.call(args);
  646. }
  647. return this.setValues(space, values);
  648. };
  649. /* Set the values for a space, invalidating cache */
  650. Converter.prototype.setValues = function(space, values) {
  651. this.space = space;
  652. this.convs = {};
  653. this.convs[space] = values;
  654. return this;
  655. };
  656. /* Get the values for a space. If there's already
  657. a conversion for the space, fetch it, otherwise
  658. compute it */
  659. Converter.prototype.getValues = function(space) {
  660. var vals = this.convs[space];
  661. if (!vals) {
  662. var fspace = this.space,
  663. from = this.convs[fspace];
  664. vals = convert[fspace][space](from);
  665. this.convs[space] = vals;
  666. }
  667. return vals;
  668. };
  669. ["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
  670. Converter.prototype[space] = function(vals) {
  671. return this.routeSpace(space, arguments);
  672. };
  673. });
  674. var colorConvert = convert;
  675. var colorName = {
  676. "aliceblue": [240, 248, 255],
  677. "antiquewhite": [250, 235, 215],
  678. "aqua": [0, 255, 255],
  679. "aquamarine": [127, 255, 212],
  680. "azure": [240, 255, 255],
  681. "beige": [245, 245, 220],
  682. "bisque": [255, 228, 196],
  683. "black": [0, 0, 0],
  684. "blanchedalmond": [255, 235, 205],
  685. "blue": [0, 0, 255],
  686. "blueviolet": [138, 43, 226],
  687. "brown": [165, 42, 42],
  688. "burlywood": [222, 184, 135],
  689. "cadetblue": [95, 158, 160],
  690. "chartreuse": [127, 255, 0],
  691. "chocolate": [210, 105, 30],
  692. "coral": [255, 127, 80],
  693. "cornflowerblue": [100, 149, 237],
  694. "cornsilk": [255, 248, 220],
  695. "crimson": [220, 20, 60],
  696. "cyan": [0, 255, 255],
  697. "darkblue": [0, 0, 139],
  698. "darkcyan": [0, 139, 139],
  699. "darkgoldenrod": [184, 134, 11],
  700. "darkgray": [169, 169, 169],
  701. "darkgreen": [0, 100, 0],
  702. "darkgrey": [169, 169, 169],
  703. "darkkhaki": [189, 183, 107],
  704. "darkmagenta": [139, 0, 139],
  705. "darkolivegreen": [85, 107, 47],
  706. "darkorange": [255, 140, 0],
  707. "darkorchid": [153, 50, 204],
  708. "darkred": [139, 0, 0],
  709. "darksalmon": [233, 150, 122],
  710. "darkseagreen": [143, 188, 143],
  711. "darkslateblue": [72, 61, 139],
  712. "darkslategray": [47, 79, 79],
  713. "darkslategrey": [47, 79, 79],
  714. "darkturquoise": [0, 206, 209],
  715. "darkviolet": [148, 0, 211],
  716. "deeppink": [255, 20, 147],
  717. "deepskyblue": [0, 191, 255],
  718. "dimgray": [105, 105, 105],
  719. "dimgrey": [105, 105, 105],
  720. "dodgerblue": [30, 144, 255],
  721. "firebrick": [178, 34, 34],
  722. "floralwhite": [255, 250, 240],
  723. "forestgreen": [34, 139, 34],
  724. "fuchsia": [255, 0, 255],
  725. "gainsboro": [220, 220, 220],
  726. "ghostwhite": [248, 248, 255],
  727. "gold": [255, 215, 0],
  728. "goldenrod": [218, 165, 32],
  729. "gray": [128, 128, 128],
  730. "green": [0, 128, 0],
  731. "greenyellow": [173, 255, 47],
  732. "grey": [128, 128, 128],
  733. "honeydew": [240, 255, 240],
  734. "hotpink": [255, 105, 180],
  735. "indianred": [205, 92, 92],
  736. "indigo": [75, 0, 130],
  737. "ivory": [255, 255, 240],
  738. "khaki": [240, 230, 140],
  739. "lavender": [230, 230, 250],
  740. "lavenderblush": [255, 240, 245],
  741. "lawngreen": [124, 252, 0],
  742. "lemonchiffon": [255, 250, 205],
  743. "lightblue": [173, 216, 230],
  744. "lightcoral": [240, 128, 128],
  745. "lightcyan": [224, 255, 255],
  746. "lightgoldenrodyellow": [250, 250, 210],
  747. "lightgray": [211, 211, 211],
  748. "lightgreen": [144, 238, 144],
  749. "lightgrey": [211, 211, 211],
  750. "lightpink": [255, 182, 193],
  751. "lightsalmon": [255, 160, 122],
  752. "lightseagreen": [32, 178, 170],
  753. "lightskyblue": [135, 206, 250],
  754. "lightslategray": [119, 136, 153],
  755. "lightslategrey": [119, 136, 153],
  756. "lightsteelblue": [176, 196, 222],
  757. "lightyellow": [255, 255, 224],
  758. "lime": [0, 255, 0],
  759. "limegreen": [50, 205, 50],
  760. "linen": [250, 240, 230],
  761. "magenta": [255, 0, 255],
  762. "maroon": [128, 0, 0],
  763. "mediumaquamarine": [102, 205, 170],
  764. "mediumblue": [0, 0, 205],
  765. "mediumorchid": [186, 85, 211],
  766. "mediumpurple": [147, 112, 219],
  767. "mediumseagreen": [60, 179, 113],
  768. "mediumslateblue": [123, 104, 238],
  769. "mediumspringgreen": [0, 250, 154],
  770. "mediumturquoise": [72, 209, 204],
  771. "mediumvioletred": [199, 21, 133],
  772. "midnightblue": [25, 25, 112],
  773. "mintcream": [245, 255, 250],
  774. "mistyrose": [255, 228, 225],
  775. "moccasin": [255, 228, 181],
  776. "navajowhite": [255, 222, 173],
  777. "navy": [0, 0, 128],
  778. "oldlace": [253, 245, 230],
  779. "olive": [128, 128, 0],
  780. "olivedrab": [107, 142, 35],
  781. "orange": [255, 165, 0],
  782. "orangered": [255, 69, 0],
  783. "orchid": [218, 112, 214],
  784. "palegoldenrod": [238, 232, 170],
  785. "palegreen": [152, 251, 152],
  786. "paleturquoise": [175, 238, 238],
  787. "palevioletred": [219, 112, 147],
  788. "papayawhip": [255, 239, 213],
  789. "peachpuff": [255, 218, 185],
  790. "peru": [205, 133, 63],
  791. "pink": [255, 192, 203],
  792. "plum": [221, 160, 221],
  793. "powderblue": [176, 224, 230],
  794. "purple": [128, 0, 128],
  795. "rebeccapurple": [102, 51, 153],
  796. "red": [255, 0, 0],
  797. "rosybrown": [188, 143, 143],
  798. "royalblue": [65, 105, 225],
  799. "saddlebrown": [139, 69, 19],
  800. "salmon": [250, 128, 114],
  801. "sandybrown": [244, 164, 96],
  802. "seagreen": [46, 139, 87],
  803. "seashell": [255, 245, 238],
  804. "sienna": [160, 82, 45],
  805. "silver": [192, 192, 192],
  806. "skyblue": [135, 206, 235],
  807. "slateblue": [106, 90, 205],
  808. "slategray": [112, 128, 144],
  809. "slategrey": [112, 128, 144],
  810. "snow": [255, 250, 250],
  811. "springgreen": [0, 255, 127],
  812. "steelblue": [70, 130, 180],
  813. "tan": [210, 180, 140],
  814. "teal": [0, 128, 128],
  815. "thistle": [216, 191, 216],
  816. "tomato": [255, 99, 71],
  817. "turquoise": [64, 224, 208],
  818. "violet": [238, 130, 238],
  819. "wheat": [245, 222, 179],
  820. "white": [255, 255, 255],
  821. "whitesmoke": [245, 245, 245],
  822. "yellow": [255, 255, 0],
  823. "yellowgreen": [154, 205, 50]
  824. };
  825. /* MIT license */
  826. var colorString = {
  827. getRgba: getRgba,
  828. getHsla: getHsla,
  829. getRgb: getRgb,
  830. getHsl: getHsl,
  831. getHwb: getHwb,
  832. getAlpha: getAlpha,
  833. hexString: hexString,
  834. rgbString: rgbString,
  835. rgbaString: rgbaString,
  836. percentString: percentString,
  837. percentaString: percentaString,
  838. hslString: hslString,
  839. hslaString: hslaString,
  840. hwbString: hwbString,
  841. keyword: keyword
  842. };
  843. function getRgba(string) {
  844. if (!string) {
  845. return;
  846. }
  847. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  848. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  849. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  850. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  851. keyword = /(\w+)/;
  852. var rgb = [0, 0, 0],
  853. a = 1,
  854. match = string.match(abbr),
  855. hexAlpha = "";
  856. if (match) {
  857. match = match[1];
  858. hexAlpha = match[3];
  859. for (var i = 0; i < rgb.length; i++) {
  860. rgb[i] = parseInt(match[i] + match[i], 16);
  861. }
  862. if (hexAlpha) {
  863. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  864. }
  865. }
  866. else if (match = string.match(hex)) {
  867. hexAlpha = match[2];
  868. match = match[1];
  869. for (var i = 0; i < rgb.length; i++) {
  870. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  871. }
  872. if (hexAlpha) {
  873. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  874. }
  875. }
  876. else if (match = string.match(rgba)) {
  877. for (var i = 0; i < rgb.length; i++) {
  878. rgb[i] = parseInt(match[i + 1]);
  879. }
  880. a = parseFloat(match[4]);
  881. }
  882. else if (match = string.match(per)) {
  883. for (var i = 0; i < rgb.length; i++) {
  884. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  885. }
  886. a = parseFloat(match[4]);
  887. }
  888. else if (match = string.match(keyword)) {
  889. if (match[1] == "transparent") {
  890. return [0, 0, 0, 0];
  891. }
  892. rgb = colorName[match[1]];
  893. if (!rgb) {
  894. return;
  895. }
  896. }
  897. for (var i = 0; i < rgb.length; i++) {
  898. rgb[i] = scale(rgb[i], 0, 255);
  899. }
  900. if (!a && a != 0) {
  901. a = 1;
  902. }
  903. else {
  904. a = scale(a, 0, 1);
  905. }
  906. rgb[3] = a;
  907. return rgb;
  908. }
  909. function getHsla(string) {
  910. if (!string) {
  911. return;
  912. }
  913. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  914. var match = string.match(hsl);
  915. if (match) {
  916. var alpha = parseFloat(match[4]);
  917. var h = scale(parseInt(match[1]), 0, 360),
  918. s = scale(parseFloat(match[2]), 0, 100),
  919. l = scale(parseFloat(match[3]), 0, 100),
  920. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  921. return [h, s, l, a];
  922. }
  923. }
  924. function getHwb(string) {
  925. if (!string) {
  926. return;
  927. }
  928. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  929. var match = string.match(hwb);
  930. if (match) {
  931. var alpha = parseFloat(match[4]);
  932. var h = scale(parseInt(match[1]), 0, 360),
  933. w = scale(parseFloat(match[2]), 0, 100),
  934. b = scale(parseFloat(match[3]), 0, 100),
  935. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  936. return [h, w, b, a];
  937. }
  938. }
  939. function getRgb(string) {
  940. var rgba = getRgba(string);
  941. return rgba && rgba.slice(0, 3);
  942. }
  943. function getHsl(string) {
  944. var hsla = getHsla(string);
  945. return hsla && hsla.slice(0, 3);
  946. }
  947. function getAlpha(string) {
  948. var vals = getRgba(string);
  949. if (vals) {
  950. return vals[3];
  951. }
  952. else if (vals = getHsla(string)) {
  953. return vals[3];
  954. }
  955. else if (vals = getHwb(string)) {
  956. return vals[3];
  957. }
  958. }
  959. // generators
  960. function hexString(rgba, a) {
  961. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  962. return "#" + hexDouble(rgba[0])
  963. + hexDouble(rgba[1])
  964. + hexDouble(rgba[2])
  965. + (
  966. (a >= 0 && a < 1)
  967. ? hexDouble(Math.round(a * 255))
  968. : ""
  969. );
  970. }
  971. function rgbString(rgba, alpha) {
  972. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  973. return rgbaString(rgba, alpha);
  974. }
  975. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  976. }
  977. function rgbaString(rgba, alpha) {
  978. if (alpha === undefined) {
  979. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  980. }
  981. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  982. + ", " + alpha + ")";
  983. }
  984. function percentString(rgba, alpha) {
  985. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  986. return percentaString(rgba, alpha);
  987. }
  988. var r = Math.round(rgba[0]/255 * 100),
  989. g = Math.round(rgba[1]/255 * 100),
  990. b = Math.round(rgba[2]/255 * 100);
  991. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  992. }
  993. function percentaString(rgba, alpha) {
  994. var r = Math.round(rgba[0]/255 * 100),
  995. g = Math.round(rgba[1]/255 * 100),
  996. b = Math.round(rgba[2]/255 * 100);
  997. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  998. }
  999. function hslString(hsla, alpha) {
  1000. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1001. return hslaString(hsla, alpha);
  1002. }
  1003. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1004. }
  1005. function hslaString(hsla, alpha) {
  1006. if (alpha === undefined) {
  1007. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1008. }
  1009. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1010. + alpha + ")";
  1011. }
  1012. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1013. // (hwb have alpha optional & 1 is default value)
  1014. function hwbString(hwb, alpha) {
  1015. if (alpha === undefined) {
  1016. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1017. }
  1018. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1019. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1020. }
  1021. function keyword(rgb) {
  1022. return reverseNames[rgb.slice(0, 3)];
  1023. }
  1024. // helpers
  1025. function scale(num, min, max) {
  1026. return Math.min(Math.max(min, num), max);
  1027. }
  1028. function hexDouble(num) {
  1029. var str = num.toString(16).toUpperCase();
  1030. return (str.length < 2) ? "0" + str : str;
  1031. }
  1032. //create a list of reverse color names
  1033. var reverseNames = {};
  1034. for (var name in colorName) {
  1035. reverseNames[colorName[name]] = name;
  1036. }
  1037. /* MIT license */
  1038. var Color = function (obj) {
  1039. if (obj instanceof Color) {
  1040. return obj;
  1041. }
  1042. if (!(this instanceof Color)) {
  1043. return new Color(obj);
  1044. }
  1045. this.valid = false;
  1046. this.values = {
  1047. rgb: [0, 0, 0],
  1048. hsl: [0, 0, 0],
  1049. hsv: [0, 0, 0],
  1050. hwb: [0, 0, 0],
  1051. cmyk: [0, 0, 0, 0],
  1052. alpha: 1
  1053. };
  1054. // parse Color() argument
  1055. var vals;
  1056. if (typeof obj === 'string') {
  1057. vals = colorString.getRgba(obj);
  1058. if (vals) {
  1059. this.setValues('rgb', vals);
  1060. } else if (vals = colorString.getHsla(obj)) {
  1061. this.setValues('hsl', vals);
  1062. } else if (vals = colorString.getHwb(obj)) {
  1063. this.setValues('hwb', vals);
  1064. }
  1065. } else if (typeof obj === 'object') {
  1066. vals = obj;
  1067. if (vals.r !== undefined || vals.red !== undefined) {
  1068. this.setValues('rgb', vals);
  1069. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1070. this.setValues('hsl', vals);
  1071. } else if (vals.v !== undefined || vals.value !== undefined) {
  1072. this.setValues('hsv', vals);
  1073. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1074. this.setValues('hwb', vals);
  1075. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1076. this.setValues('cmyk', vals);
  1077. }
  1078. }
  1079. };
  1080. Color.prototype = {
  1081. isValid: function () {
  1082. return this.valid;
  1083. },
  1084. rgb: function () {
  1085. return this.setSpace('rgb', arguments);
  1086. },
  1087. hsl: function () {
  1088. return this.setSpace('hsl', arguments);
  1089. },
  1090. hsv: function () {
  1091. return this.setSpace('hsv', arguments);
  1092. },
  1093. hwb: function () {
  1094. return this.setSpace('hwb', arguments);
  1095. },
  1096. cmyk: function () {
  1097. return this.setSpace('cmyk', arguments);
  1098. },
  1099. rgbArray: function () {
  1100. return this.values.rgb;
  1101. },
  1102. hslArray: function () {
  1103. return this.values.hsl;
  1104. },
  1105. hsvArray: function () {
  1106. return this.values.hsv;
  1107. },
  1108. hwbArray: function () {
  1109. var values = this.values;
  1110. if (values.alpha !== 1) {
  1111. return values.hwb.concat([values.alpha]);
  1112. }
  1113. return values.hwb;
  1114. },
  1115. cmykArray: function () {
  1116. return this.values.cmyk;
  1117. },
  1118. rgbaArray: function () {
  1119. var values = this.values;
  1120. return values.rgb.concat([values.alpha]);
  1121. },
  1122. hslaArray: function () {
  1123. var values = this.values;
  1124. return values.hsl.concat([values.alpha]);
  1125. },
  1126. alpha: function (val) {
  1127. if (val === undefined) {
  1128. return this.values.alpha;
  1129. }
  1130. this.setValues('alpha', val);
  1131. return this;
  1132. },
  1133. red: function (val) {
  1134. return this.setChannel('rgb', 0, val);
  1135. },
  1136. green: function (val) {
  1137. return this.setChannel('rgb', 1, val);
  1138. },
  1139. blue: function (val) {
  1140. return this.setChannel('rgb', 2, val);
  1141. },
  1142. hue: function (val) {
  1143. if (val) {
  1144. val %= 360;
  1145. val = val < 0 ? 360 + val : val;
  1146. }
  1147. return this.setChannel('hsl', 0, val);
  1148. },
  1149. saturation: function (val) {
  1150. return this.setChannel('hsl', 1, val);
  1151. },
  1152. lightness: function (val) {
  1153. return this.setChannel('hsl', 2, val);
  1154. },
  1155. saturationv: function (val) {
  1156. return this.setChannel('hsv', 1, val);
  1157. },
  1158. whiteness: function (val) {
  1159. return this.setChannel('hwb', 1, val);
  1160. },
  1161. blackness: function (val) {
  1162. return this.setChannel('hwb', 2, val);
  1163. },
  1164. value: function (val) {
  1165. return this.setChannel('hsv', 2, val);
  1166. },
  1167. cyan: function (val) {
  1168. return this.setChannel('cmyk', 0, val);
  1169. },
  1170. magenta: function (val) {
  1171. return this.setChannel('cmyk', 1, val);
  1172. },
  1173. yellow: function (val) {
  1174. return this.setChannel('cmyk', 2, val);
  1175. },
  1176. black: function (val) {
  1177. return this.setChannel('cmyk', 3, val);
  1178. },
  1179. hexString: function () {
  1180. return colorString.hexString(this.values.rgb);
  1181. },
  1182. rgbString: function () {
  1183. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1184. },
  1185. rgbaString: function () {
  1186. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1187. },
  1188. percentString: function () {
  1189. return colorString.percentString(this.values.rgb, this.values.alpha);
  1190. },
  1191. hslString: function () {
  1192. return colorString.hslString(this.values.hsl, this.values.alpha);
  1193. },
  1194. hslaString: function () {
  1195. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1196. },
  1197. hwbString: function () {
  1198. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1199. },
  1200. keyword: function () {
  1201. return colorString.keyword(this.values.rgb, this.values.alpha);
  1202. },
  1203. rgbNumber: function () {
  1204. var rgb = this.values.rgb;
  1205. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1206. },
  1207. luminosity: function () {
  1208. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1209. var rgb = this.values.rgb;
  1210. var lum = [];
  1211. for (var i = 0; i < rgb.length; i++) {
  1212. var chan = rgb[i] / 255;
  1213. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1214. }
  1215. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1216. },
  1217. contrast: function (color2) {
  1218. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1219. var lum1 = this.luminosity();
  1220. var lum2 = color2.luminosity();
  1221. if (lum1 > lum2) {
  1222. return (lum1 + 0.05) / (lum2 + 0.05);
  1223. }
  1224. return (lum2 + 0.05) / (lum1 + 0.05);
  1225. },
  1226. level: function (color2) {
  1227. var contrastRatio = this.contrast(color2);
  1228. if (contrastRatio >= 7.1) {
  1229. return 'AAA';
  1230. }
  1231. return (contrastRatio >= 4.5) ? 'AA' : '';
  1232. },
  1233. dark: function () {
  1234. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1235. var rgb = this.values.rgb;
  1236. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1237. return yiq < 128;
  1238. },
  1239. light: function () {
  1240. return !this.dark();
  1241. },
  1242. negate: function () {
  1243. var rgb = [];
  1244. for (var i = 0; i < 3; i++) {
  1245. rgb[i] = 255 - this.values.rgb[i];
  1246. }
  1247. this.setValues('rgb', rgb);
  1248. return this;
  1249. },
  1250. lighten: function (ratio) {
  1251. var hsl = this.values.hsl;
  1252. hsl[2] += hsl[2] * ratio;
  1253. this.setValues('hsl', hsl);
  1254. return this;
  1255. },
  1256. darken: function (ratio) {
  1257. var hsl = this.values.hsl;
  1258. hsl[2] -= hsl[2] * ratio;
  1259. this.setValues('hsl', hsl);
  1260. return this;
  1261. },
  1262. saturate: function (ratio) {
  1263. var hsl = this.values.hsl;
  1264. hsl[1] += hsl[1] * ratio;
  1265. this.setValues('hsl', hsl);
  1266. return this;
  1267. },
  1268. desaturate: function (ratio) {
  1269. var hsl = this.values.hsl;
  1270. hsl[1] -= hsl[1] * ratio;
  1271. this.setValues('hsl', hsl);
  1272. return this;
  1273. },
  1274. whiten: function (ratio) {
  1275. var hwb = this.values.hwb;
  1276. hwb[1] += hwb[1] * ratio;
  1277. this.setValues('hwb', hwb);
  1278. return this;
  1279. },
  1280. blacken: function (ratio) {
  1281. var hwb = this.values.hwb;
  1282. hwb[2] += hwb[2] * ratio;
  1283. this.setValues('hwb', hwb);
  1284. return this;
  1285. },
  1286. greyscale: function () {
  1287. var rgb = this.values.rgb;
  1288. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1289. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1290. this.setValues('rgb', [val, val, val]);
  1291. return this;
  1292. },
  1293. clearer: function (ratio) {
  1294. var alpha = this.values.alpha;
  1295. this.setValues('alpha', alpha - (alpha * ratio));
  1296. return this;
  1297. },
  1298. opaquer: function (ratio) {
  1299. var alpha = this.values.alpha;
  1300. this.setValues('alpha', alpha + (alpha * ratio));
  1301. return this;
  1302. },
  1303. rotate: function (degrees) {
  1304. var hsl = this.values.hsl;
  1305. var hue = (hsl[0] + degrees) % 360;
  1306. hsl[0] = hue < 0 ? 360 + hue : hue;
  1307. this.setValues('hsl', hsl);
  1308. return this;
  1309. },
  1310. /**
  1311. * Ported from sass implementation in C
  1312. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1313. */
  1314. mix: function (mixinColor, weight) {
  1315. var color1 = this;
  1316. var color2 = mixinColor;
  1317. var p = weight === undefined ? 0.5 : weight;
  1318. var w = 2 * p - 1;
  1319. var a = color1.alpha() - color2.alpha();
  1320. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1321. var w2 = 1 - w1;
  1322. return this
  1323. .rgb(
  1324. w1 * color1.red() + w2 * color2.red(),
  1325. w1 * color1.green() + w2 * color2.green(),
  1326. w1 * color1.blue() + w2 * color2.blue()
  1327. )
  1328. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1329. },
  1330. toJSON: function () {
  1331. return this.rgb();
  1332. },
  1333. clone: function () {
  1334. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1335. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1336. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1337. // except 'alpha' which is a number.
  1338. var result = new Color();
  1339. var source = this.values;
  1340. var target = result.values;
  1341. var value, type;
  1342. for (var prop in source) {
  1343. if (source.hasOwnProperty(prop)) {
  1344. value = source[prop];
  1345. type = ({}).toString.call(value);
  1346. if (type === '[object Array]') {
  1347. target[prop] = value.slice(0);
  1348. } else if (type === '[object Number]') {
  1349. target[prop] = value;
  1350. } else {
  1351. console.error('unexpected color value:', value);
  1352. }
  1353. }
  1354. }
  1355. return result;
  1356. }
  1357. };
  1358. Color.prototype.spaces = {
  1359. rgb: ['red', 'green', 'blue'],
  1360. hsl: ['hue', 'saturation', 'lightness'],
  1361. hsv: ['hue', 'saturation', 'value'],
  1362. hwb: ['hue', 'whiteness', 'blackness'],
  1363. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1364. };
  1365. Color.prototype.maxes = {
  1366. rgb: [255, 255, 255],
  1367. hsl: [360, 100, 100],
  1368. hsv: [360, 100, 100],
  1369. hwb: [360, 100, 100],
  1370. cmyk: [100, 100, 100, 100]
  1371. };
  1372. Color.prototype.getValues = function (space) {
  1373. var values = this.values;
  1374. var vals = {};
  1375. for (var i = 0; i < space.length; i++) {
  1376. vals[space.charAt(i)] = values[space][i];
  1377. }
  1378. if (values.alpha !== 1) {
  1379. vals.a = values.alpha;
  1380. }
  1381. // {r: 255, g: 255, b: 255, a: 0.4}
  1382. return vals;
  1383. };
  1384. Color.prototype.setValues = function (space, vals) {
  1385. var values = this.values;
  1386. var spaces = this.spaces;
  1387. var maxes = this.maxes;
  1388. var alpha = 1;
  1389. var i;
  1390. this.valid = true;
  1391. if (space === 'alpha') {
  1392. alpha = vals;
  1393. } else if (vals.length) {
  1394. // [10, 10, 10]
  1395. values[space] = vals.slice(0, space.length);
  1396. alpha = vals[space.length];
  1397. } else if (vals[space.charAt(0)] !== undefined) {
  1398. // {r: 10, g: 10, b: 10}
  1399. for (i = 0; i < space.length; i++) {
  1400. values[space][i] = vals[space.charAt(i)];
  1401. }
  1402. alpha = vals.a;
  1403. } else if (vals[spaces[space][0]] !== undefined) {
  1404. // {red: 10, green: 10, blue: 10}
  1405. var chans = spaces[space];
  1406. for (i = 0; i < space.length; i++) {
  1407. values[space][i] = vals[chans[i]];
  1408. }
  1409. alpha = vals.alpha;
  1410. }
  1411. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1412. if (space === 'alpha') {
  1413. return false;
  1414. }
  1415. var capped;
  1416. // cap values of the space prior converting all values
  1417. for (i = 0; i < space.length; i++) {
  1418. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1419. values[space][i] = Math.round(capped);
  1420. }
  1421. // convert to all the other color spaces
  1422. for (var sname in spaces) {
  1423. if (sname !== space) {
  1424. values[sname] = colorConvert[space][sname](values[space]);
  1425. }
  1426. }
  1427. return true;
  1428. };
  1429. Color.prototype.setSpace = function (space, args) {
  1430. var vals = args[0];
  1431. if (vals === undefined) {
  1432. // color.rgb()
  1433. return this.getValues(space);
  1434. }
  1435. // color.rgb(10, 10, 10)
  1436. if (typeof vals === 'number') {
  1437. vals = Array.prototype.slice.call(args);
  1438. }
  1439. this.setValues(space, vals);
  1440. return this;
  1441. };
  1442. Color.prototype.setChannel = function (space, index, val) {
  1443. var svalues = this.values[space];
  1444. if (val === undefined) {
  1445. // color.red()
  1446. return svalues[index];
  1447. } else if (val === svalues[index]) {
  1448. // color.red(color.red())
  1449. return this;
  1450. }
  1451. // color.red(100)
  1452. svalues[index] = val;
  1453. this.setValues(space, svalues);
  1454. return this;
  1455. };
  1456. if (typeof window !== 'undefined') {
  1457. window.Color = Color;
  1458. }
  1459. var chartjsColor = Color;
  1460. /**
  1461. * @namespace Chart.helpers
  1462. */
  1463. var helpers = {
  1464. /**
  1465. * An empty function that can be used, for example, for optional callback.
  1466. */
  1467. noop: function() {},
  1468. /**
  1469. * Returns a unique id, sequentially generated from a global variable.
  1470. * @returns {number}
  1471. * @function
  1472. */
  1473. uid: (function() {
  1474. var id = 0;
  1475. return function() {
  1476. return id++;
  1477. };
  1478. }()),
  1479. /**
  1480. * Returns true if `value` is neither null nor undefined, else returns false.
  1481. * @param {*} value - The value to test.
  1482. * @returns {boolean}
  1483. * @since 2.7.0
  1484. */
  1485. isNullOrUndef: function(value) {
  1486. return value === null || typeof value === 'undefined';
  1487. },
  1488. /**
  1489. * Returns true if `value` is an array (including typed arrays), else returns false.
  1490. * @param {*} value - The value to test.
  1491. * @returns {boolean}
  1492. * @function
  1493. */
  1494. isArray: function(value) {
  1495. if (Array.isArray && Array.isArray(value)) {
  1496. return true;
  1497. }
  1498. var type = Object.prototype.toString.call(value);
  1499. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1500. return true;
  1501. }
  1502. return false;
  1503. },
  1504. /**
  1505. * Returns true if `value` is an object (excluding null), else returns false.
  1506. * @param {*} value - The value to test.
  1507. * @returns {boolean}
  1508. * @since 2.7.0
  1509. */
  1510. isObject: function(value) {
  1511. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1512. },
  1513. /**
  1514. * Returns true if `value` is a finite number, else returns false
  1515. * @param {*} value - The value to test.
  1516. * @returns {boolean}
  1517. */
  1518. isFinite: function(value) {
  1519. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1520. },
  1521. /**
  1522. * Returns `value` if defined, else returns `defaultValue`.
  1523. * @param {*} value - The value to return if defined.
  1524. * @param {*} defaultValue - The value to return if `value` is undefined.
  1525. * @returns {*}
  1526. */
  1527. valueOrDefault: function(value, defaultValue) {
  1528. return typeof value === 'undefined' ? defaultValue : value;
  1529. },
  1530. /**
  1531. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1532. * @param {Array} value - The array to lookup for value at `index`.
  1533. * @param {number} index - The index in `value` to lookup for value.
  1534. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1535. * @returns {*}
  1536. */
  1537. valueAtIndexOrDefault: function(value, index, defaultValue) {
  1538. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1539. },
  1540. /**
  1541. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1542. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1543. * @param {function} fn - The function to call.
  1544. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1545. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1546. * @returns {*}
  1547. */
  1548. callback: function(fn, args, thisArg) {
  1549. if (fn && typeof fn.call === 'function') {
  1550. return fn.apply(thisArg, args);
  1551. }
  1552. },
  1553. /**
  1554. * Note(SB) for performance sake, this method should only be used when loopable type
  1555. * is unknown or in none intensive code (not called often and small loopable). Else
  1556. * it's preferable to use a regular for() loop and save extra function calls.
  1557. * @param {object|Array} loopable - The object or array to be iterated.
  1558. * @param {function} fn - The function to call for each item.
  1559. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1560. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1561. */
  1562. each: function(loopable, fn, thisArg, reverse) {
  1563. var i, len, keys;
  1564. if (helpers.isArray(loopable)) {
  1565. len = loopable.length;
  1566. if (reverse) {
  1567. for (i = len - 1; i >= 0; i--) {
  1568. fn.call(thisArg, loopable[i], i);
  1569. }
  1570. } else {
  1571. for (i = 0; i < len; i++) {
  1572. fn.call(thisArg, loopable[i], i);
  1573. }
  1574. }
  1575. } else if (helpers.isObject(loopable)) {
  1576. keys = Object.keys(loopable);
  1577. len = keys.length;
  1578. for (i = 0; i < len; i++) {
  1579. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1580. }
  1581. }
  1582. },
  1583. /**
  1584. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1585. * @see https://stackoverflow.com/a/14853974
  1586. * @param {Array} a0 - The array to compare
  1587. * @param {Array} a1 - The array to compare
  1588. * @returns {boolean}
  1589. */
  1590. arrayEquals: function(a0, a1) {
  1591. var i, ilen, v0, v1;
  1592. if (!a0 || !a1 || a0.length !== a1.length) {
  1593. return false;
  1594. }
  1595. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1596. v0 = a0[i];
  1597. v1 = a1[i];
  1598. if (v0 instanceof Array && v1 instanceof Array) {
  1599. if (!helpers.arrayEquals(v0, v1)) {
  1600. return false;
  1601. }
  1602. } else if (v0 !== v1) {
  1603. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1604. return false;
  1605. }
  1606. }
  1607. return true;
  1608. },
  1609. /**
  1610. * Returns a deep copy of `source` without keeping references on objects and arrays.
  1611. * @param {*} source - The value to clone.
  1612. * @returns {*}
  1613. */
  1614. clone: function(source) {
  1615. if (helpers.isArray(source)) {
  1616. return source.map(helpers.clone);
  1617. }
  1618. if (helpers.isObject(source)) {
  1619. var target = {};
  1620. var keys = Object.keys(source);
  1621. var klen = keys.length;
  1622. var k = 0;
  1623. for (; k < klen; ++k) {
  1624. target[keys[k]] = helpers.clone(source[keys[k]]);
  1625. }
  1626. return target;
  1627. }
  1628. return source;
  1629. },
  1630. /**
  1631. * The default merger when Chart.helpers.merge is called without merger option.
  1632. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  1633. * @private
  1634. */
  1635. _merger: function(key, target, source, options) {
  1636. var tval = target[key];
  1637. var sval = source[key];
  1638. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1639. helpers.merge(tval, sval, options);
  1640. } else {
  1641. target[key] = helpers.clone(sval);
  1642. }
  1643. },
  1644. /**
  1645. * Merges source[key] in target[key] only if target[key] is undefined.
  1646. * @private
  1647. */
  1648. _mergerIf: function(key, target, source) {
  1649. var tval = target[key];
  1650. var sval = source[key];
  1651. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1652. helpers.mergeIf(tval, sval);
  1653. } else if (!target.hasOwnProperty(key)) {
  1654. target[key] = helpers.clone(sval);
  1655. }
  1656. },
  1657. /**
  1658. * Recursively deep copies `source` properties into `target` with the given `options`.
  1659. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  1660. * @param {object} target - The target object in which all sources are merged into.
  1661. * @param {object|object[]} source - Object(s) to merge into `target`.
  1662. * @param {object} [options] - Merging options:
  1663. * @param {function} [options.merger] - The merge method (key, target, source, options)
  1664. * @returns {object} The `target` object.
  1665. */
  1666. merge: function(target, source, options) {
  1667. var sources = helpers.isArray(source) ? source : [source];
  1668. var ilen = sources.length;
  1669. var merge, i, keys, klen, k;
  1670. if (!helpers.isObject(target)) {
  1671. return target;
  1672. }
  1673. options = options || {};
  1674. merge = options.merger || helpers._merger;
  1675. for (i = 0; i < ilen; ++i) {
  1676. source = sources[i];
  1677. if (!helpers.isObject(source)) {
  1678. continue;
  1679. }
  1680. keys = Object.keys(source);
  1681. for (k = 0, klen = keys.length; k < klen; ++k) {
  1682. merge(keys[k], target, source, options);
  1683. }
  1684. }
  1685. return target;
  1686. },
  1687. /**
  1688. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  1689. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  1690. * @param {object} target - The target object in which all sources are merged into.
  1691. * @param {object|object[]} source - Object(s) to merge into `target`.
  1692. * @returns {object} The `target` object.
  1693. */
  1694. mergeIf: function(target, source) {
  1695. return helpers.merge(target, source, {merger: helpers._mergerIf});
  1696. },
  1697. /**
  1698. * Applies the contents of two or more objects together into the first object.
  1699. * @param {object} target - The target object in which all objects are merged into.
  1700. * @param {object} arg1 - Object containing additional properties to merge in target.
  1701. * @param {object} argN - Additional objects containing properties to merge in target.
  1702. * @returns {object} The `target` object.
  1703. */
  1704. extend: function(target) {
  1705. var setFn = function(value, key) {
  1706. target[key] = value;
  1707. };
  1708. for (var i = 1, ilen = arguments.length; i < ilen; ++i) {
  1709. helpers.each(arguments[i], setFn);
  1710. }
  1711. return target;
  1712. },
  1713. /**
  1714. * Basic javascript inheritance based on the model created in Backbone.js
  1715. */
  1716. inherits: function(extensions) {
  1717. var me = this;
  1718. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  1719. return me.apply(this, arguments);
  1720. };
  1721. var Surrogate = function() {
  1722. this.constructor = ChartElement;
  1723. };
  1724. Surrogate.prototype = me.prototype;
  1725. ChartElement.prototype = new Surrogate();
  1726. ChartElement.extend = helpers.inherits;
  1727. if (extensions) {
  1728. helpers.extend(ChartElement.prototype, extensions);
  1729. }
  1730. ChartElement.__super__ = me.prototype;
  1731. return ChartElement;
  1732. }
  1733. };
  1734. var helpers_core = helpers;
  1735. // DEPRECATIONS
  1736. /**
  1737. * Provided for backward compatibility, use Chart.helpers.callback instead.
  1738. * @function Chart.helpers.callCallback
  1739. * @deprecated since version 2.6.0
  1740. * @todo remove at version 3
  1741. * @private
  1742. */
  1743. helpers.callCallback = helpers.callback;
  1744. /**
  1745. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  1746. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  1747. * @function Chart.helpers.indexOf
  1748. * @deprecated since version 2.7.0
  1749. * @todo remove at version 3
  1750. * @private
  1751. */
  1752. helpers.indexOf = function(array, item, fromIndex) {
  1753. return Array.prototype.indexOf.call(array, item, fromIndex);
  1754. };
  1755. /**
  1756. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  1757. * @function Chart.helpers.getValueOrDefault
  1758. * @deprecated since version 2.7.0
  1759. * @todo remove at version 3
  1760. * @private
  1761. */
  1762. helpers.getValueOrDefault = helpers.valueOrDefault;
  1763. /**
  1764. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  1765. * @function Chart.helpers.getValueAtIndexOrDefault
  1766. * @deprecated since version 2.7.0
  1767. * @todo remove at version 3
  1768. * @private
  1769. */
  1770. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  1771. /**
  1772. * Easing functions adapted from Robert Penner's easing equations.
  1773. * @namespace Chart.helpers.easingEffects
  1774. * @see http://www.robertpenner.com/easing/
  1775. */
  1776. var effects = {
  1777. linear: function(t) {
  1778. return t;
  1779. },
  1780. easeInQuad: function(t) {
  1781. return t * t;
  1782. },
  1783. easeOutQuad: function(t) {
  1784. return -t * (t - 2);
  1785. },
  1786. easeInOutQuad: function(t) {
  1787. if ((t /= 0.5) < 1) {
  1788. return 0.5 * t * t;
  1789. }
  1790. return -0.5 * ((--t) * (t - 2) - 1);
  1791. },
  1792. easeInCubic: function(t) {
  1793. return t * t * t;
  1794. },
  1795. easeOutCubic: function(t) {
  1796. return (t = t - 1) * t * t + 1;
  1797. },
  1798. easeInOutCubic: function(t) {
  1799. if ((t /= 0.5) < 1) {
  1800. return 0.5 * t * t * t;
  1801. }
  1802. return 0.5 * ((t -= 2) * t * t + 2);
  1803. },
  1804. easeInQuart: function(t) {
  1805. return t * t * t * t;
  1806. },
  1807. easeOutQuart: function(t) {
  1808. return -((t = t - 1) * t * t * t - 1);
  1809. },
  1810. easeInOutQuart: function(t) {
  1811. if ((t /= 0.5) < 1) {
  1812. return 0.5 * t * t * t * t;
  1813. }
  1814. return -0.5 * ((t -= 2) * t * t * t - 2);
  1815. },
  1816. easeInQuint: function(t) {
  1817. return t * t * t * t * t;
  1818. },
  1819. easeOutQuint: function(t) {
  1820. return (t = t - 1) * t * t * t * t + 1;
  1821. },
  1822. easeInOutQuint: function(t) {
  1823. if ((t /= 0.5) < 1) {
  1824. return 0.5 * t * t * t * t * t;
  1825. }
  1826. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  1827. },
  1828. easeInSine: function(t) {
  1829. return -Math.cos(t * (Math.PI / 2)) + 1;
  1830. },
  1831. easeOutSine: function(t) {
  1832. return Math.sin(t * (Math.PI / 2));
  1833. },
  1834. easeInOutSine: function(t) {
  1835. return -0.5 * (Math.cos(Math.PI * t) - 1);
  1836. },
  1837. easeInExpo: function(t) {
  1838. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  1839. },
  1840. easeOutExpo: function(t) {
  1841. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  1842. },
  1843. easeInOutExpo: function(t) {
  1844. if (t === 0) {
  1845. return 0;
  1846. }
  1847. if (t === 1) {
  1848. return 1;
  1849. }
  1850. if ((t /= 0.5) < 1) {
  1851. return 0.5 * Math.pow(2, 10 * (t - 1));
  1852. }
  1853. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  1854. },
  1855. easeInCirc: function(t) {
  1856. if (t >= 1) {
  1857. return t;
  1858. }
  1859. return -(Math.sqrt(1 - t * t) - 1);
  1860. },
  1861. easeOutCirc: function(t) {
  1862. return Math.sqrt(1 - (t = t - 1) * t);
  1863. },
  1864. easeInOutCirc: function(t) {
  1865. if ((t /= 0.5) < 1) {
  1866. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  1867. }
  1868. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  1869. },
  1870. easeInElastic: function(t) {
  1871. var s = 1.70158;
  1872. var p = 0;
  1873. var a = 1;
  1874. if (t === 0) {
  1875. return 0;
  1876. }
  1877. if (t === 1) {
  1878. return 1;
  1879. }
  1880. if (!p) {
  1881. p = 0.3;
  1882. }
  1883. if (a < 1) {
  1884. a = 1;
  1885. s = p / 4;
  1886. } else {
  1887. s = p / (2 * Math.PI) * Math.asin(1 / a);
  1888. }
  1889. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  1890. },
  1891. easeOutElastic: function(t) {
  1892. var s = 1.70158;
  1893. var p = 0;
  1894. var a = 1;
  1895. if (t === 0) {
  1896. return 0;
  1897. }
  1898. if (t === 1) {
  1899. return 1;
  1900. }
  1901. if (!p) {
  1902. p = 0.3;
  1903. }
  1904. if (a < 1) {
  1905. a = 1;
  1906. s = p / 4;
  1907. } else {
  1908. s = p / (2 * Math.PI) * Math.asin(1 / a);
  1909. }
  1910. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  1911. },
  1912. easeInOutElastic: function(t) {
  1913. var s = 1.70158;
  1914. var p = 0;
  1915. var a = 1;
  1916. if (t === 0) {
  1917. return 0;
  1918. }
  1919. if ((t /= 0.5) === 2) {
  1920. return 1;
  1921. }
  1922. if (!p) {
  1923. p = 0.45;
  1924. }
  1925. if (a < 1) {
  1926. a = 1;
  1927. s = p / 4;
  1928. } else {
  1929. s = p / (2 * Math.PI) * Math.asin(1 / a);
  1930. }
  1931. if (t < 1) {
  1932. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  1933. }
  1934. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  1935. },
  1936. easeInBack: function(t) {
  1937. var s = 1.70158;
  1938. return t * t * ((s + 1) * t - s);
  1939. },
  1940. easeOutBack: function(t) {
  1941. var s = 1.70158;
  1942. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  1943. },
  1944. easeInOutBack: function(t) {
  1945. var s = 1.70158;
  1946. if ((t /= 0.5) < 1) {
  1947. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  1948. }
  1949. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  1950. },
  1951. easeInBounce: function(t) {
  1952. return 1 - effects.easeOutBounce(1 - t);
  1953. },
  1954. easeOutBounce: function(t) {
  1955. if (t < (1 / 2.75)) {
  1956. return 7.5625 * t * t;
  1957. }
  1958. if (t < (2 / 2.75)) {
  1959. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  1960. }
  1961. if (t < (2.5 / 2.75)) {
  1962. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  1963. }
  1964. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  1965. },
  1966. easeInOutBounce: function(t) {
  1967. if (t < 0.5) {
  1968. return effects.easeInBounce(t * 2) * 0.5;
  1969. }
  1970. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  1971. }
  1972. };
  1973. var helpers_easing = {
  1974. effects: effects
  1975. };
  1976. // DEPRECATIONS
  1977. /**
  1978. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  1979. * @function Chart.helpers.easingEffects
  1980. * @deprecated since version 2.7.0
  1981. * @todo remove at version 3
  1982. * @private
  1983. */
  1984. helpers_core.easingEffects = effects;
  1985. var PI = Math.PI;
  1986. var RAD_PER_DEG = PI / 180;
  1987. var DOUBLE_PI = PI * 2;
  1988. var HALF_PI = PI / 2;
  1989. var QUARTER_PI = PI / 4;
  1990. var TWO_THIRDS_PI = PI * 2 / 3;
  1991. /**
  1992. * @namespace Chart.helpers.canvas
  1993. */
  1994. var exports$1 = {
  1995. /**
  1996. * Clears the entire canvas associated to the given `chart`.
  1997. * @param {Chart} chart - The chart for which to clear the canvas.
  1998. */
  1999. clear: function(chart) {
  2000. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2001. },
  2002. /**
  2003. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2004. * given size (width, height) and the same `radius` for all corners.
  2005. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2006. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2007. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2008. * @param {number} width - The rectangle's width.
  2009. * @param {number} height - The rectangle's height.
  2010. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2011. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2012. */
  2013. roundedRect: function(ctx, x, y, width, height, radius) {
  2014. if (radius) {
  2015. var r = Math.min(radius, height / 2, width / 2);
  2016. var left = x + r;
  2017. var top = y + r;
  2018. var right = x + width - r;
  2019. var bottom = y + height - r;
  2020. ctx.moveTo(x, top);
  2021. if (left < right && top < bottom) {
  2022. ctx.arc(left, top, r, -PI, -HALF_PI);
  2023. ctx.arc(right, top, r, -HALF_PI, 0);
  2024. ctx.arc(right, bottom, r, 0, HALF_PI);
  2025. ctx.arc(left, bottom, r, HALF_PI, PI);
  2026. } else if (left < right) {
  2027. ctx.moveTo(left, y);
  2028. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2029. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2030. } else if (top < bottom) {
  2031. ctx.arc(left, top, r, -PI, 0);
  2032. ctx.arc(left, bottom, r, 0, PI);
  2033. } else {
  2034. ctx.arc(left, top, r, -PI, PI);
  2035. }
  2036. ctx.closePath();
  2037. ctx.moveTo(x, y);
  2038. } else {
  2039. ctx.rect(x, y, width, height);
  2040. }
  2041. },
  2042. drawPoint: function(ctx, style, radius, x, y, rotation) {
  2043. var type, xOffset, yOffset, size, cornerRadius;
  2044. var rad = (rotation || 0) * RAD_PER_DEG;
  2045. if (style && typeof style === 'object') {
  2046. type = style.toString();
  2047. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2048. ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height);
  2049. return;
  2050. }
  2051. }
  2052. if (isNaN(radius) || radius <= 0) {
  2053. return;
  2054. }
  2055. ctx.beginPath();
  2056. switch (style) {
  2057. // Default includes circle
  2058. default:
  2059. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2060. ctx.closePath();
  2061. break;
  2062. case 'triangle':
  2063. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2064. rad += TWO_THIRDS_PI;
  2065. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2066. rad += TWO_THIRDS_PI;
  2067. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2068. ctx.closePath();
  2069. break;
  2070. case 'rectRounded':
  2071. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2072. // `quadraticCurveTo` since it generates better results when rect is
  2073. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2074. // closer proportion to the previous impl and it is inscribed in the
  2075. // circle with `radius`. For more details, see the following PRs:
  2076. // https://github.com/chartjs/Chart.js/issues/5597
  2077. // https://github.com/chartjs/Chart.js/issues/5858
  2078. cornerRadius = radius * 0.516;
  2079. size = radius - cornerRadius;
  2080. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2081. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2082. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2083. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2084. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2085. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2086. ctx.closePath();
  2087. break;
  2088. case 'rect':
  2089. if (!rotation) {
  2090. size = Math.SQRT1_2 * radius;
  2091. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2092. break;
  2093. }
  2094. rad += QUARTER_PI;
  2095. /* falls through */
  2096. case 'rectRot':
  2097. xOffset = Math.cos(rad) * radius;
  2098. yOffset = Math.sin(rad) * radius;
  2099. ctx.moveTo(x - xOffset, y - yOffset);
  2100. ctx.lineTo(x + yOffset, y - xOffset);
  2101. ctx.lineTo(x + xOffset, y + yOffset);
  2102. ctx.lineTo(x - yOffset, y + xOffset);
  2103. ctx.closePath();
  2104. break;
  2105. case 'crossRot':
  2106. rad += QUARTER_PI;
  2107. /* falls through */
  2108. case 'cross':
  2109. xOffset = Math.cos(rad) * radius;
  2110. yOffset = Math.sin(rad) * radius;
  2111. ctx.moveTo(x - xOffset, y - yOffset);
  2112. ctx.lineTo(x + xOffset, y + yOffset);
  2113. ctx.moveTo(x + yOffset, y - xOffset);
  2114. ctx.lineTo(x - yOffset, y + xOffset);
  2115. break;
  2116. case 'star':
  2117. xOffset = Math.cos(rad) * radius;
  2118. yOffset = Math.sin(rad) * radius;
  2119. ctx.moveTo(x - xOffset, y - yOffset);
  2120. ctx.lineTo(x + xOffset, y + yOffset);
  2121. ctx.moveTo(x + yOffset, y - xOffset);
  2122. ctx.lineTo(x - yOffset, y + xOffset);
  2123. rad += QUARTER_PI;
  2124. xOffset = Math.cos(rad) * radius;
  2125. yOffset = Math.sin(rad) * radius;
  2126. ctx.moveTo(x - xOffset, y - yOffset);
  2127. ctx.lineTo(x + xOffset, y + yOffset);
  2128. ctx.moveTo(x + yOffset, y - xOffset);
  2129. ctx.lineTo(x - yOffset, y + xOffset);
  2130. break;
  2131. case 'line':
  2132. xOffset = Math.cos(rad) * radius;
  2133. yOffset = Math.sin(rad) * radius;
  2134. ctx.moveTo(x - xOffset, y - yOffset);
  2135. ctx.lineTo(x + xOffset, y + yOffset);
  2136. break;
  2137. case 'dash':
  2138. ctx.moveTo(x, y);
  2139. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2140. break;
  2141. }
  2142. ctx.fill();
  2143. ctx.stroke();
  2144. },
  2145. /**
  2146. * Returns true if the point is inside the rectangle
  2147. * @param {object} point - The point to test
  2148. * @param {object} area - The rectangle
  2149. * @returns {boolean}
  2150. * @private
  2151. */
  2152. _isPointInArea: function(point, area) {
  2153. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2154. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2155. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2156. },
  2157. clipArea: function(ctx, area) {
  2158. ctx.save();
  2159. ctx.beginPath();
  2160. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2161. ctx.clip();
  2162. },
  2163. unclipArea: function(ctx) {
  2164. ctx.restore();
  2165. },
  2166. lineTo: function(ctx, previous, target, flip) {
  2167. var stepped = target.steppedLine;
  2168. if (stepped) {
  2169. if (stepped === 'middle') {
  2170. var midpoint = (previous.x + target.x) / 2.0;
  2171. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2172. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2173. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2174. ctx.lineTo(previous.x, target.y);
  2175. } else {
  2176. ctx.lineTo(target.x, previous.y);
  2177. }
  2178. ctx.lineTo(target.x, target.y);
  2179. return;
  2180. }
  2181. if (!target.tension) {
  2182. ctx.lineTo(target.x, target.y);
  2183. return;
  2184. }
  2185. ctx.bezierCurveTo(
  2186. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2187. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2188. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2189. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2190. target.x,
  2191. target.y);
  2192. }
  2193. };
  2194. var helpers_canvas = exports$1;
  2195. // DEPRECATIONS
  2196. /**
  2197. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2198. * @namespace Chart.helpers.clear
  2199. * @deprecated since version 2.7.0
  2200. * @todo remove at version 3
  2201. * @private
  2202. */
  2203. helpers_core.clear = exports$1.clear;
  2204. /**
  2205. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2206. * @namespace Chart.helpers.drawRoundedRectangle
  2207. * @deprecated since version 2.7.0
  2208. * @todo remove at version 3
  2209. * @private
  2210. */
  2211. helpers_core.drawRoundedRectangle = function(ctx) {
  2212. ctx.beginPath();
  2213. exports$1.roundedRect.apply(exports$1, arguments);
  2214. };
  2215. var defaults = {
  2216. /**
  2217. * @private
  2218. */
  2219. _set: function(scope, values) {
  2220. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2221. }
  2222. };
  2223. defaults._set('global', {
  2224. defaultColor: 'rgba(0,0,0,0.1)',
  2225. defaultFontColor: '#666',
  2226. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2227. defaultFontSize: 12,
  2228. defaultFontStyle: 'normal',
  2229. defaultLineHeight: 1.2,
  2230. showLines: true
  2231. });
  2232. var core_defaults = defaults;
  2233. var valueOrDefault = helpers_core.valueOrDefault;
  2234. /**
  2235. * Converts the given font object into a CSS font string.
  2236. * @param {object} font - A font object.
  2237. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2238. * @private
  2239. */
  2240. function toFontString(font) {
  2241. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2242. return null;
  2243. }
  2244. return (font.style ? font.style + ' ' : '')
  2245. + (font.weight ? font.weight + ' ' : '')
  2246. + font.size + 'px '
  2247. + font.family;
  2248. }
  2249. /**
  2250. * @alias Chart.helpers.options
  2251. * @namespace
  2252. */
  2253. var helpers_options = {
  2254. /**
  2255. * Converts the given line height `value` in pixels for a specific font `size`.
  2256. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2257. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2258. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2259. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2260. * @since 2.7.0
  2261. */
  2262. toLineHeight: function(value, size) {
  2263. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2264. if (!matches || matches[1] === 'normal') {
  2265. return size * 1.2;
  2266. }
  2267. value = +matches[2];
  2268. switch (matches[3]) {
  2269. case 'px':
  2270. return value;
  2271. case '%':
  2272. value /= 100;
  2273. break;
  2274. default:
  2275. break;
  2276. }
  2277. return size * value;
  2278. },
  2279. /**
  2280. * Converts the given value into a padding object with pre-computed width/height.
  2281. * @param {number|object} value - If a number, set the value to all TRBL component,
  2282. * else, if and object, use defined properties and sets undefined ones to 0.
  2283. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2284. * @since 2.7.0
  2285. */
  2286. toPadding: function(value) {
  2287. var t, r, b, l;
  2288. if (helpers_core.isObject(value)) {
  2289. t = +value.top || 0;
  2290. r = +value.right || 0;
  2291. b = +value.bottom || 0;
  2292. l = +value.left || 0;
  2293. } else {
  2294. t = r = b = l = +value || 0;
  2295. }
  2296. return {
  2297. top: t,
  2298. right: r,
  2299. bottom: b,
  2300. left: l,
  2301. height: t + b,
  2302. width: l + r
  2303. };
  2304. },
  2305. /**
  2306. * Parses font options and returns the font object.
  2307. * @param {object} options - A object that contains font options to be parsed.
  2308. * @return {object} The font object.
  2309. * @todo Support font.* options and renamed to toFont().
  2310. * @private
  2311. */
  2312. _parseFont: function(options) {
  2313. var globalDefaults = core_defaults.global;
  2314. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2315. var font = {
  2316. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2317. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2318. size: size,
  2319. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2320. weight: null,
  2321. string: ''
  2322. };
  2323. font.string = toFontString(font);
  2324. return font;
  2325. },
  2326. /**
  2327. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2328. * @param {Array} inputs - An array of values, falling back to the last value.
  2329. * @param {object} [context] - If defined and the current value is a function, the value
  2330. * is called with `context` as first argument and the result becomes the new input.
  2331. * @param {number} [index] - If defined and the current value is an array, the value
  2332. * at `index` become the new input.
  2333. * @since 2.7.0
  2334. */
  2335. resolve: function(inputs, context, index) {
  2336. var i, ilen, value;
  2337. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2338. value = inputs[i];
  2339. if (value === undefined) {
  2340. continue;
  2341. }
  2342. if (context !== undefined && typeof value === 'function') {
  2343. value = value(context);
  2344. }
  2345. if (index !== undefined && helpers_core.isArray(value)) {
  2346. value = value[index];
  2347. }
  2348. if (value !== undefined) {
  2349. return value;
  2350. }
  2351. }
  2352. }
  2353. };
  2354. var helpers$1 = helpers_core;
  2355. var easing = helpers_easing;
  2356. var canvas = helpers_canvas;
  2357. var options = helpers_options;
  2358. helpers$1.easing = easing;
  2359. helpers$1.canvas = canvas;
  2360. helpers$1.options = options;
  2361. function interpolate(start, view, model, ease) {
  2362. var keys = Object.keys(model);
  2363. var i, ilen, key, actual, origin, target, type, c0, c1;
  2364. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2365. key = keys[i];
  2366. target = model[key];
  2367. // if a value is added to the model after pivot() has been called, the view
  2368. // doesn't contain it, so let's initialize the view to the target value.
  2369. if (!view.hasOwnProperty(key)) {
  2370. view[key] = target;
  2371. }
  2372. actual = view[key];
  2373. if (actual === target || key[0] === '_') {
  2374. continue;
  2375. }
  2376. if (!start.hasOwnProperty(key)) {
  2377. start[key] = actual;
  2378. }
  2379. origin = start[key];
  2380. type = typeof target;
  2381. if (type === typeof origin) {
  2382. if (type === 'string') {
  2383. c0 = chartjsColor(origin);
  2384. if (c0.valid) {
  2385. c1 = chartjsColor(target);
  2386. if (c1.valid) {
  2387. view[key] = c1.mix(c0, ease).rgbString();
  2388. continue;
  2389. }
  2390. }
  2391. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2392. view[key] = origin + (target - origin) * ease;
  2393. continue;
  2394. }
  2395. }
  2396. view[key] = target;
  2397. }
  2398. }
  2399. var Element = function(configuration) {
  2400. helpers$1.extend(this, configuration);
  2401. this.initialize.apply(this, arguments);
  2402. };
  2403. helpers$1.extend(Element.prototype, {
  2404. initialize: function() {
  2405. this.hidden = false;
  2406. },
  2407. pivot: function() {
  2408. var me = this;
  2409. if (!me._view) {
  2410. me._view = helpers$1.clone(me._model);
  2411. }
  2412. me._start = {};
  2413. return me;
  2414. },
  2415. transition: function(ease) {
  2416. var me = this;
  2417. var model = me._model;
  2418. var start = me._start;
  2419. var view = me._view;
  2420. // No animation -> No Transition
  2421. if (!model || ease === 1) {
  2422. me._view = model;
  2423. me._start = null;
  2424. return me;
  2425. }
  2426. if (!view) {
  2427. view = me._view = {};
  2428. }
  2429. if (!start) {
  2430. start = me._start = {};
  2431. }
  2432. interpolate(start, view, model, ease);
  2433. return me;
  2434. },
  2435. tooltipPosition: function() {
  2436. return {
  2437. x: this._model.x,
  2438. y: this._model.y
  2439. };
  2440. },
  2441. hasValue: function() {
  2442. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2443. }
  2444. });
  2445. Element.extend = helpers$1.inherits;
  2446. var core_element = Element;
  2447. var exports$2 = core_element.extend({
  2448. chart: null, // the animation associated chart instance
  2449. currentStep: 0, // the current animation step
  2450. numSteps: 60, // default number of steps
  2451. easing: '', // the easing to use for this animation
  2452. render: null, // render function used by the animation service
  2453. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2454. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2455. });
  2456. var core_animation = exports$2;
  2457. // DEPRECATIONS
  2458. /**
  2459. * Provided for backward compatibility, use Chart.Animation instead
  2460. * @prop Chart.Animation#animationObject
  2461. * @deprecated since version 2.6.0
  2462. * @todo remove at version 3
  2463. */
  2464. Object.defineProperty(exports$2.prototype, 'animationObject', {
  2465. get: function() {
  2466. return this;
  2467. }
  2468. });
  2469. /**
  2470. * Provided for backward compatibility, use Chart.Animation#chart instead
  2471. * @prop Chart.Animation#chartInstance
  2472. * @deprecated since version 2.6.0
  2473. * @todo remove at version 3
  2474. */
  2475. Object.defineProperty(exports$2.prototype, 'chartInstance', {
  2476. get: function() {
  2477. return this.chart;
  2478. },
  2479. set: function(value) {
  2480. this.chart = value;
  2481. }
  2482. });
  2483. core_defaults._set('global', {
  2484. animation: {
  2485. duration: 1000,
  2486. easing: 'easeOutQuart',
  2487. onProgress: helpers$1.noop,
  2488. onComplete: helpers$1.noop
  2489. }
  2490. });
  2491. var core_animations = {
  2492. animations: [],
  2493. request: null,
  2494. /**
  2495. * @param {Chart} chart - The chart to animate.
  2496. * @param {Chart.Animation} animation - The animation that we will animate.
  2497. * @param {number} duration - The animation duration in ms.
  2498. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  2499. */
  2500. addAnimation: function(chart, animation, duration, lazy) {
  2501. var animations = this.animations;
  2502. var i, ilen;
  2503. animation.chart = chart;
  2504. animation.startTime = Date.now();
  2505. animation.duration = duration;
  2506. if (!lazy) {
  2507. chart.animating = true;
  2508. }
  2509. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  2510. if (animations[i].chart === chart) {
  2511. animations[i] = animation;
  2512. return;
  2513. }
  2514. }
  2515. animations.push(animation);
  2516. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  2517. if (animations.length === 1) {
  2518. this.requestAnimationFrame();
  2519. }
  2520. },
  2521. cancelAnimation: function(chart) {
  2522. var index = helpers$1.findIndex(this.animations, function(animation) {
  2523. return animation.chart === chart;
  2524. });
  2525. if (index !== -1) {
  2526. this.animations.splice(index, 1);
  2527. chart.animating = false;
  2528. }
  2529. },
  2530. requestAnimationFrame: function() {
  2531. var me = this;
  2532. if (me.request === null) {
  2533. // Skip animation frame requests until the active one is executed.
  2534. // This can happen when processing mouse events, e.g. 'mousemove'
  2535. // and 'mouseout' events will trigger multiple renders.
  2536. me.request = helpers$1.requestAnimFrame.call(window, function() {
  2537. me.request = null;
  2538. me.startDigest();
  2539. });
  2540. }
  2541. },
  2542. /**
  2543. * @private
  2544. */
  2545. startDigest: function() {
  2546. var me = this;
  2547. me.advance();
  2548. // Do we have more stuff to animate?
  2549. if (me.animations.length > 0) {
  2550. me.requestAnimationFrame();
  2551. }
  2552. },
  2553. /**
  2554. * @private
  2555. */
  2556. advance: function() {
  2557. var animations = this.animations;
  2558. var animation, chart, numSteps, nextStep;
  2559. var i = 0;
  2560. // 1 animation per chart, so we are looping charts here
  2561. while (i < animations.length) {
  2562. animation = animations[i];
  2563. chart = animation.chart;
  2564. numSteps = animation.numSteps;
  2565. // Make sure that currentStep starts at 1
  2566. // https://github.com/chartjs/Chart.js/issues/6104
  2567. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  2568. animation.currentStep = Math.min(nextStep, numSteps);
  2569. helpers$1.callback(animation.render, [chart, animation], chart);
  2570. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  2571. if (animation.currentStep >= numSteps) {
  2572. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  2573. chart.animating = false;
  2574. animations.splice(i, 1);
  2575. } else {
  2576. ++i;
  2577. }
  2578. }
  2579. }
  2580. };
  2581. var resolve = helpers$1.options.resolve;
  2582. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  2583. /**
  2584. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  2585. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  2586. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  2587. */
  2588. function listenArrayEvents(array, listener) {
  2589. if (array._chartjs) {
  2590. array._chartjs.listeners.push(listener);
  2591. return;
  2592. }
  2593. Object.defineProperty(array, '_chartjs', {
  2594. configurable: true,
  2595. enumerable: false,
  2596. value: {
  2597. listeners: [listener]
  2598. }
  2599. });
  2600. arrayEvents.forEach(function(key) {
  2601. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  2602. var base = array[key];
  2603. Object.defineProperty(array, key, {
  2604. configurable: true,
  2605. enumerable: false,
  2606. value: function() {
  2607. var args = Array.prototype.slice.call(arguments);
  2608. var res = base.apply(this, args);
  2609. helpers$1.each(array._chartjs.listeners, function(object) {
  2610. if (typeof object[method] === 'function') {
  2611. object[method].apply(object, args);
  2612. }
  2613. });
  2614. return res;
  2615. }
  2616. });
  2617. });
  2618. }
  2619. /**
  2620. * Removes the given array event listener and cleanup extra attached properties (such as
  2621. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  2622. */
  2623. function unlistenArrayEvents(array, listener) {
  2624. var stub = array._chartjs;
  2625. if (!stub) {
  2626. return;
  2627. }
  2628. var listeners = stub.listeners;
  2629. var index = listeners.indexOf(listener);
  2630. if (index !== -1) {
  2631. listeners.splice(index, 1);
  2632. }
  2633. if (listeners.length > 0) {
  2634. return;
  2635. }
  2636. arrayEvents.forEach(function(key) {
  2637. delete array[key];
  2638. });
  2639. delete array._chartjs;
  2640. }
  2641. // Base class for all dataset controllers (line, bar, etc)
  2642. var DatasetController = function(chart, datasetIndex) {
  2643. this.initialize(chart, datasetIndex);
  2644. };
  2645. helpers$1.extend(DatasetController.prototype, {
  2646. /**
  2647. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  2648. * @type {Chart.core.element}
  2649. */
  2650. datasetElementType: null,
  2651. /**
  2652. * Element type used to generate a meta data (e.g. Chart.element.Point).
  2653. * @type {Chart.core.element}
  2654. */
  2655. dataElementType: null,
  2656. initialize: function(chart, datasetIndex) {
  2657. var me = this;
  2658. me.chart = chart;
  2659. me.index = datasetIndex;
  2660. me.linkScales();
  2661. me.addElements();
  2662. },
  2663. updateIndex: function(datasetIndex) {
  2664. this.index = datasetIndex;
  2665. },
  2666. linkScales: function() {
  2667. var me = this;
  2668. var meta = me.getMeta();
  2669. var dataset = me.getDataset();
  2670. if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) {
  2671. meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
  2672. }
  2673. if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) {
  2674. meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
  2675. }
  2676. },
  2677. getDataset: function() {
  2678. return this.chart.data.datasets[this.index];
  2679. },
  2680. getMeta: function() {
  2681. return this.chart.getDatasetMeta(this.index);
  2682. },
  2683. getScaleForId: function(scaleID) {
  2684. return this.chart.scales[scaleID];
  2685. },
  2686. /**
  2687. * @private
  2688. */
  2689. _getValueScaleId: function() {
  2690. return this.getMeta().yAxisID;
  2691. },
  2692. /**
  2693. * @private
  2694. */
  2695. _getIndexScaleId: function() {
  2696. return this.getMeta().xAxisID;
  2697. },
  2698. /**
  2699. * @private
  2700. */
  2701. _getValueScale: function() {
  2702. return this.getScaleForId(this._getValueScaleId());
  2703. },
  2704. /**
  2705. * @private
  2706. */
  2707. _getIndexScale: function() {
  2708. return this.getScaleForId(this._getIndexScaleId());
  2709. },
  2710. reset: function() {
  2711. this.update(true);
  2712. },
  2713. /**
  2714. * @private
  2715. */
  2716. destroy: function() {
  2717. if (this._data) {
  2718. unlistenArrayEvents(this._data, this);
  2719. }
  2720. },
  2721. createMetaDataset: function() {
  2722. var me = this;
  2723. var type = me.datasetElementType;
  2724. return type && new type({
  2725. _chart: me.chart,
  2726. _datasetIndex: me.index
  2727. });
  2728. },
  2729. createMetaData: function(index) {
  2730. var me = this;
  2731. var type = me.dataElementType;
  2732. return type && new type({
  2733. _chart: me.chart,
  2734. _datasetIndex: me.index,
  2735. _index: index
  2736. });
  2737. },
  2738. addElements: function() {
  2739. var me = this;
  2740. var meta = me.getMeta();
  2741. var data = me.getDataset().data || [];
  2742. var metaData = meta.data;
  2743. var i, ilen;
  2744. for (i = 0, ilen = data.length; i < ilen; ++i) {
  2745. metaData[i] = metaData[i] || me.createMetaData(i);
  2746. }
  2747. meta.dataset = meta.dataset || me.createMetaDataset();
  2748. },
  2749. addElementAndReset: function(index) {
  2750. var element = this.createMetaData(index);
  2751. this.getMeta().data.splice(index, 0, element);
  2752. this.updateElement(element, index, true);
  2753. },
  2754. buildOrUpdateElements: function() {
  2755. var me = this;
  2756. var dataset = me.getDataset();
  2757. var data = dataset.data || (dataset.data = []);
  2758. // In order to correctly handle data addition/deletion animation (an thus simulate
  2759. // real-time charts), we need to monitor these data modifications and synchronize
  2760. // the internal meta data accordingly.
  2761. if (me._data !== data) {
  2762. if (me._data) {
  2763. // This case happens when the user replaced the data array instance.
  2764. unlistenArrayEvents(me._data, me);
  2765. }
  2766. if (data && Object.isExtensible(data)) {
  2767. listenArrayEvents(data, me);
  2768. }
  2769. me._data = data;
  2770. }
  2771. // Re-sync meta data in case the user replaced the data array or if we missed
  2772. // any updates and so make sure that we handle number of datapoints changing.
  2773. me.resyncElements();
  2774. },
  2775. update: helpers$1.noop,
  2776. transition: function(easingValue) {
  2777. var meta = this.getMeta();
  2778. var elements = meta.data || [];
  2779. var ilen = elements.length;
  2780. var i = 0;
  2781. for (; i < ilen; ++i) {
  2782. elements[i].transition(easingValue);
  2783. }
  2784. if (meta.dataset) {
  2785. meta.dataset.transition(easingValue);
  2786. }
  2787. },
  2788. draw: function() {
  2789. var meta = this.getMeta();
  2790. var elements = meta.data || [];
  2791. var ilen = elements.length;
  2792. var i = 0;
  2793. if (meta.dataset) {
  2794. meta.dataset.draw();
  2795. }
  2796. for (; i < ilen; ++i) {
  2797. elements[i].draw();
  2798. }
  2799. },
  2800. removeHoverStyle: function(element) {
  2801. helpers$1.merge(element._model, element.$previousStyle || {});
  2802. delete element.$previousStyle;
  2803. },
  2804. setHoverStyle: function(element) {
  2805. var dataset = this.chart.data.datasets[element._datasetIndex];
  2806. var index = element._index;
  2807. var custom = element.custom || {};
  2808. var model = element._model;
  2809. var getHoverColor = helpers$1.getHoverColor;
  2810. element.$previousStyle = {
  2811. backgroundColor: model.backgroundColor,
  2812. borderColor: model.borderColor,
  2813. borderWidth: model.borderWidth
  2814. };
  2815. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  2816. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  2817. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  2818. },
  2819. /**
  2820. * @private
  2821. */
  2822. resyncElements: function() {
  2823. var me = this;
  2824. var meta = me.getMeta();
  2825. var data = me.getDataset().data;
  2826. var numMeta = meta.data.length;
  2827. var numData = data.length;
  2828. if (numData < numMeta) {
  2829. meta.data.splice(numData, numMeta - numData);
  2830. } else if (numData > numMeta) {
  2831. me.insertElements(numMeta, numData - numMeta);
  2832. }
  2833. },
  2834. /**
  2835. * @private
  2836. */
  2837. insertElements: function(start, count) {
  2838. for (var i = 0; i < count; ++i) {
  2839. this.addElementAndReset(start + i);
  2840. }
  2841. },
  2842. /**
  2843. * @private
  2844. */
  2845. onDataPush: function() {
  2846. var count = arguments.length;
  2847. this.insertElements(this.getDataset().data.length - count, count);
  2848. },
  2849. /**
  2850. * @private
  2851. */
  2852. onDataPop: function() {
  2853. this.getMeta().data.pop();
  2854. },
  2855. /**
  2856. * @private
  2857. */
  2858. onDataShift: function() {
  2859. this.getMeta().data.shift();
  2860. },
  2861. /**
  2862. * @private
  2863. */
  2864. onDataSplice: function(start, count) {
  2865. this.getMeta().data.splice(start, count);
  2866. this.insertElements(start, arguments.length - 2);
  2867. },
  2868. /**
  2869. * @private
  2870. */
  2871. onDataUnshift: function() {
  2872. this.insertElements(0, arguments.length);
  2873. }
  2874. });
  2875. DatasetController.extend = helpers$1.inherits;
  2876. var core_datasetController = DatasetController;
  2877. core_defaults._set('global', {
  2878. elements: {
  2879. arc: {
  2880. backgroundColor: core_defaults.global.defaultColor,
  2881. borderColor: '#fff',
  2882. borderWidth: 2,
  2883. borderAlign: 'center'
  2884. }
  2885. }
  2886. });
  2887. var element_arc = core_element.extend({
  2888. inLabelRange: function(mouseX) {
  2889. var vm = this._view;
  2890. if (vm) {
  2891. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  2892. }
  2893. return false;
  2894. },
  2895. inRange: function(chartX, chartY) {
  2896. var vm = this._view;
  2897. if (vm) {
  2898. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  2899. var angle = pointRelativePosition.angle;
  2900. var distance = pointRelativePosition.distance;
  2901. // Sanitise angle range
  2902. var startAngle = vm.startAngle;
  2903. var endAngle = vm.endAngle;
  2904. while (endAngle < startAngle) {
  2905. endAngle += 2.0 * Math.PI;
  2906. }
  2907. while (angle > endAngle) {
  2908. angle -= 2.0 * Math.PI;
  2909. }
  2910. while (angle < startAngle) {
  2911. angle += 2.0 * Math.PI;
  2912. }
  2913. // Check if within the range of the open/close angle
  2914. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  2915. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  2916. return (betweenAngles && withinRadius);
  2917. }
  2918. return false;
  2919. },
  2920. getCenterPoint: function() {
  2921. var vm = this._view;
  2922. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  2923. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  2924. return {
  2925. x: vm.x + Math.cos(halfAngle) * halfRadius,
  2926. y: vm.y + Math.sin(halfAngle) * halfRadius
  2927. };
  2928. },
  2929. getArea: function() {
  2930. var vm = this._view;
  2931. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  2932. },
  2933. tooltipPosition: function() {
  2934. var vm = this._view;
  2935. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  2936. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  2937. return {
  2938. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  2939. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  2940. };
  2941. },
  2942. draw: function() {
  2943. var ctx = this._chart.ctx;
  2944. var vm = this._view;
  2945. var sA = vm.startAngle;
  2946. var eA = vm.endAngle;
  2947. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  2948. var angleMargin;
  2949. ctx.save();
  2950. ctx.beginPath();
  2951. ctx.arc(vm.x, vm.y, Math.max(vm.outerRadius - pixelMargin, 0), sA, eA);
  2952. ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
  2953. ctx.closePath();
  2954. ctx.fillStyle = vm.backgroundColor;
  2955. ctx.fill();
  2956. if (vm.borderWidth) {
  2957. if (vm.borderAlign === 'inner') {
  2958. // Draw an inner border by cliping the arc and drawing a double-width border
  2959. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  2960. ctx.beginPath();
  2961. angleMargin = pixelMargin / vm.outerRadius;
  2962. ctx.arc(vm.x, vm.y, vm.outerRadius, sA - angleMargin, eA + angleMargin);
  2963. if (vm.innerRadius > pixelMargin) {
  2964. angleMargin = pixelMargin / vm.innerRadius;
  2965. ctx.arc(vm.x, vm.y, vm.innerRadius - pixelMargin, eA + angleMargin, sA - angleMargin, true);
  2966. } else {
  2967. ctx.arc(vm.x, vm.y, pixelMargin, eA + Math.PI / 2, sA - Math.PI / 2);
  2968. }
  2969. ctx.closePath();
  2970. ctx.clip();
  2971. ctx.beginPath();
  2972. ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
  2973. ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
  2974. ctx.closePath();
  2975. ctx.lineWidth = vm.borderWidth * 2;
  2976. ctx.lineJoin = 'round';
  2977. } else {
  2978. ctx.lineWidth = vm.borderWidth;
  2979. ctx.lineJoin = 'bevel';
  2980. }
  2981. ctx.strokeStyle = vm.borderColor;
  2982. ctx.stroke();
  2983. }
  2984. ctx.restore();
  2985. }
  2986. });
  2987. var valueOrDefault$1 = helpers$1.valueOrDefault;
  2988. var defaultColor = core_defaults.global.defaultColor;
  2989. core_defaults._set('global', {
  2990. elements: {
  2991. line: {
  2992. tension: 0.4,
  2993. backgroundColor: defaultColor,
  2994. borderWidth: 3,
  2995. borderColor: defaultColor,
  2996. borderCapStyle: 'butt',
  2997. borderDash: [],
  2998. borderDashOffset: 0.0,
  2999. borderJoinStyle: 'miter',
  3000. capBezierPoints: true,
  3001. fill: true, // do we fill in the area between the line and its base axis
  3002. }
  3003. }
  3004. });
  3005. var element_line = core_element.extend({
  3006. draw: function() {
  3007. var me = this;
  3008. var vm = me._view;
  3009. var ctx = me._chart.ctx;
  3010. var spanGaps = vm.spanGaps;
  3011. var points = me._children.slice(); // clone array
  3012. var globalDefaults = core_defaults.global;
  3013. var globalOptionLineElements = globalDefaults.elements.line;
  3014. var lastDrawnIndex = -1;
  3015. var index, current, previous, currentVM;
  3016. // If we are looping, adding the first point again
  3017. if (me._loop && points.length) {
  3018. points.push(points[0]);
  3019. }
  3020. ctx.save();
  3021. // Stroke Line Options
  3022. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3023. // IE 9 and 10 do not support line dash
  3024. if (ctx.setLineDash) {
  3025. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3026. }
  3027. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3028. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3029. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3030. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3031. // Stroke Line
  3032. ctx.beginPath();
  3033. lastDrawnIndex = -1;
  3034. for (index = 0; index < points.length; ++index) {
  3035. current = points[index];
  3036. previous = helpers$1.previousItem(points, index);
  3037. currentVM = current._view;
  3038. // First point moves to it's starting position no matter what
  3039. if (index === 0) {
  3040. if (!currentVM.skip) {
  3041. ctx.moveTo(currentVM.x, currentVM.y);
  3042. lastDrawnIndex = index;
  3043. }
  3044. } else {
  3045. previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
  3046. if (!currentVM.skip) {
  3047. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3048. // There was a gap and this is the first point after the gap
  3049. ctx.moveTo(currentVM.x, currentVM.y);
  3050. } else {
  3051. // Line to next point
  3052. helpers$1.canvas.lineTo(ctx, previous._view, current._view);
  3053. }
  3054. lastDrawnIndex = index;
  3055. }
  3056. }
  3057. }
  3058. ctx.stroke();
  3059. ctx.restore();
  3060. }
  3061. });
  3062. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3063. var defaultColor$1 = core_defaults.global.defaultColor;
  3064. core_defaults._set('global', {
  3065. elements: {
  3066. point: {
  3067. radius: 3,
  3068. pointStyle: 'circle',
  3069. backgroundColor: defaultColor$1,
  3070. borderColor: defaultColor$1,
  3071. borderWidth: 1,
  3072. // Hover
  3073. hitRadius: 1,
  3074. hoverRadius: 4,
  3075. hoverBorderWidth: 1
  3076. }
  3077. }
  3078. });
  3079. function xRange(mouseX) {
  3080. var vm = this._view;
  3081. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3082. }
  3083. function yRange(mouseY) {
  3084. var vm = this._view;
  3085. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3086. }
  3087. var element_point = core_element.extend({
  3088. inRange: function(mouseX, mouseY) {
  3089. var vm = this._view;
  3090. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3091. },
  3092. inLabelRange: xRange,
  3093. inXRange: xRange,
  3094. inYRange: yRange,
  3095. getCenterPoint: function() {
  3096. var vm = this._view;
  3097. return {
  3098. x: vm.x,
  3099. y: vm.y
  3100. };
  3101. },
  3102. getArea: function() {
  3103. return Math.PI * Math.pow(this._view.radius, 2);
  3104. },
  3105. tooltipPosition: function() {
  3106. var vm = this._view;
  3107. return {
  3108. x: vm.x,
  3109. y: vm.y,
  3110. padding: vm.radius + vm.borderWidth
  3111. };
  3112. },
  3113. draw: function(chartArea) {
  3114. var vm = this._view;
  3115. var ctx = this._chart.ctx;
  3116. var pointStyle = vm.pointStyle;
  3117. var rotation = vm.rotation;
  3118. var radius = vm.radius;
  3119. var x = vm.x;
  3120. var y = vm.y;
  3121. var globalDefaults = core_defaults.global;
  3122. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3123. if (vm.skip) {
  3124. return;
  3125. }
  3126. // Clipping for Points.
  3127. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3128. ctx.strokeStyle = vm.borderColor || defaultColor;
  3129. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3130. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3131. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3132. }
  3133. }
  3134. });
  3135. var defaultColor$2 = core_defaults.global.defaultColor;
  3136. core_defaults._set('global', {
  3137. elements: {
  3138. rectangle: {
  3139. backgroundColor: defaultColor$2,
  3140. borderColor: defaultColor$2,
  3141. borderSkipped: 'bottom',
  3142. borderWidth: 0
  3143. }
  3144. }
  3145. });
  3146. function isVertical(vm) {
  3147. return vm && vm.width !== undefined;
  3148. }
  3149. /**
  3150. * Helper function to get the bounds of the bar regardless of the orientation
  3151. * @param bar {Chart.Element.Rectangle} the bar
  3152. * @return {Bounds} bounds of the bar
  3153. * @private
  3154. */
  3155. function getBarBounds(vm) {
  3156. var x1, x2, y1, y2, half;
  3157. if (isVertical(vm)) {
  3158. half = vm.width / 2;
  3159. x1 = vm.x - half;
  3160. x2 = vm.x + half;
  3161. y1 = Math.min(vm.y, vm.base);
  3162. y2 = Math.max(vm.y, vm.base);
  3163. } else {
  3164. half = vm.height / 2;
  3165. x1 = Math.min(vm.x, vm.base);
  3166. x2 = Math.max(vm.x, vm.base);
  3167. y1 = vm.y - half;
  3168. y2 = vm.y + half;
  3169. }
  3170. return {
  3171. left: x1,
  3172. top: y1,
  3173. right: x2,
  3174. bottom: y2
  3175. };
  3176. }
  3177. function swap(orig, v1, v2) {
  3178. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3179. }
  3180. function parseBorderSkipped(vm) {
  3181. var edge = vm.borderSkipped;
  3182. var res = {};
  3183. if (!edge) {
  3184. return res;
  3185. }
  3186. if (vm.horizontal) {
  3187. if (vm.base > vm.x) {
  3188. edge = swap(edge, 'left', 'right');
  3189. }
  3190. } else if (vm.base < vm.y) {
  3191. edge = swap(edge, 'bottom', 'top');
  3192. }
  3193. res[edge] = true;
  3194. return res;
  3195. }
  3196. function parseBorderWidth(vm, maxW, maxH) {
  3197. var value = vm.borderWidth;
  3198. var skip = parseBorderSkipped(vm);
  3199. var t, r, b, l;
  3200. if (helpers$1.isObject(value)) {
  3201. t = +value.top || 0;
  3202. r = +value.right || 0;
  3203. b = +value.bottom || 0;
  3204. l = +value.left || 0;
  3205. } else {
  3206. t = r = b = l = +value || 0;
  3207. }
  3208. return {
  3209. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  3210. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  3211. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  3212. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  3213. };
  3214. }
  3215. function boundingRects(vm) {
  3216. var bounds = getBarBounds(vm);
  3217. var width = bounds.right - bounds.left;
  3218. var height = bounds.bottom - bounds.top;
  3219. var border = parseBorderWidth(vm, width / 2, height / 2);
  3220. return {
  3221. outer: {
  3222. x: bounds.left,
  3223. y: bounds.top,
  3224. w: width,
  3225. h: height
  3226. },
  3227. inner: {
  3228. x: bounds.left + border.l,
  3229. y: bounds.top + border.t,
  3230. w: width - border.l - border.r,
  3231. h: height - border.t - border.b
  3232. }
  3233. };
  3234. }
  3235. function inRange(vm, x, y) {
  3236. var skipX = x === null;
  3237. var skipY = y === null;
  3238. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  3239. return bounds
  3240. && (skipX || x >= bounds.left && x <= bounds.right)
  3241. && (skipY || y >= bounds.top && y <= bounds.bottom);
  3242. }
  3243. var element_rectangle = core_element.extend({
  3244. draw: function() {
  3245. var ctx = this._chart.ctx;
  3246. var vm = this._view;
  3247. var rects = boundingRects(vm);
  3248. var outer = rects.outer;
  3249. var inner = rects.inner;
  3250. ctx.fillStyle = vm.backgroundColor;
  3251. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  3252. if (outer.w === inner.w && outer.h === inner.h) {
  3253. return;
  3254. }
  3255. ctx.save();
  3256. ctx.beginPath();
  3257. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  3258. ctx.clip();
  3259. ctx.fillStyle = vm.borderColor;
  3260. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  3261. ctx.fill('evenodd');
  3262. ctx.restore();
  3263. },
  3264. height: function() {
  3265. var vm = this._view;
  3266. return vm.base - vm.y;
  3267. },
  3268. inRange: function(mouseX, mouseY) {
  3269. return inRange(this._view, mouseX, mouseY);
  3270. },
  3271. inLabelRange: function(mouseX, mouseY) {
  3272. var vm = this._view;
  3273. return isVertical(vm)
  3274. ? inRange(vm, mouseX, null)
  3275. : inRange(vm, null, mouseY);
  3276. },
  3277. inXRange: function(mouseX) {
  3278. return inRange(this._view, mouseX, null);
  3279. },
  3280. inYRange: function(mouseY) {
  3281. return inRange(this._view, null, mouseY);
  3282. },
  3283. getCenterPoint: function() {
  3284. var vm = this._view;
  3285. var x, y;
  3286. if (isVertical(vm)) {
  3287. x = vm.x;
  3288. y = (vm.y + vm.base) / 2;
  3289. } else {
  3290. x = (vm.x + vm.base) / 2;
  3291. y = vm.y;
  3292. }
  3293. return {x: x, y: y};
  3294. },
  3295. getArea: function() {
  3296. var vm = this._view;
  3297. return isVertical(vm)
  3298. ? vm.width * Math.abs(vm.y - vm.base)
  3299. : vm.height * Math.abs(vm.x - vm.base);
  3300. },
  3301. tooltipPosition: function() {
  3302. var vm = this._view;
  3303. return {
  3304. x: vm.x,
  3305. y: vm.y
  3306. };
  3307. }
  3308. });
  3309. var elements = {};
  3310. var Arc = element_arc;
  3311. var Line = element_line;
  3312. var Point = element_point;
  3313. var Rectangle = element_rectangle;
  3314. elements.Arc = Arc;
  3315. elements.Line = Line;
  3316. elements.Point = Point;
  3317. elements.Rectangle = Rectangle;
  3318. var resolve$1 = helpers$1.options.resolve;
  3319. core_defaults._set('bar', {
  3320. hover: {
  3321. mode: 'label'
  3322. },
  3323. scales: {
  3324. xAxes: [{
  3325. type: 'category',
  3326. categoryPercentage: 0.8,
  3327. barPercentage: 0.9,
  3328. offset: true,
  3329. gridLines: {
  3330. offsetGridLines: true
  3331. }
  3332. }],
  3333. yAxes: [{
  3334. type: 'linear'
  3335. }]
  3336. }
  3337. });
  3338. /**
  3339. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  3340. * @private
  3341. */
  3342. function computeMinSampleSize(scale, pixels) {
  3343. var min = scale.isHorizontal() ? scale.width : scale.height;
  3344. var ticks = scale.getTicks();
  3345. var prev, curr, i, ilen;
  3346. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  3347. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  3348. }
  3349. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  3350. curr = scale.getPixelForTick(i);
  3351. min = i > 0 ? Math.min(min, curr - prev) : min;
  3352. prev = curr;
  3353. }
  3354. return min;
  3355. }
  3356. /**
  3357. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  3358. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  3359. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  3360. * @private
  3361. */
  3362. function computeFitCategoryTraits(index, ruler, options) {
  3363. var thickness = options.barThickness;
  3364. var count = ruler.stackCount;
  3365. var curr = ruler.pixels[index];
  3366. var size, ratio;
  3367. if (helpers$1.isNullOrUndef(thickness)) {
  3368. size = ruler.min * options.categoryPercentage;
  3369. ratio = options.barPercentage;
  3370. } else {
  3371. // When bar thickness is enforced, category and bar percentages are ignored.
  3372. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  3373. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  3374. size = thickness * count;
  3375. ratio = 1;
  3376. }
  3377. return {
  3378. chunk: size / count,
  3379. ratio: ratio,
  3380. start: curr - (size / 2)
  3381. };
  3382. }
  3383. /**
  3384. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  3385. * percentage options are 1), based on the previous and following categories. This mode
  3386. * generates bars with different widths when data are not evenly spaced.
  3387. * @private
  3388. */
  3389. function computeFlexCategoryTraits(index, ruler, options) {
  3390. var pixels = ruler.pixels;
  3391. var curr = pixels[index];
  3392. var prev = index > 0 ? pixels[index - 1] : null;
  3393. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  3394. var percent = options.categoryPercentage;
  3395. var start, size;
  3396. if (prev === null) {
  3397. // first data: its size is double based on the next point or,
  3398. // if it's also the last data, we use the scale size.
  3399. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  3400. }
  3401. if (next === null) {
  3402. // last data: its size is also double based on the previous point.
  3403. next = curr + curr - prev;
  3404. }
  3405. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  3406. size = Math.abs(next - prev) / 2 * percent;
  3407. return {
  3408. chunk: size / ruler.stackCount,
  3409. ratio: options.barPercentage,
  3410. start: start
  3411. };
  3412. }
  3413. var controller_bar = core_datasetController.extend({
  3414. dataElementType: elements.Rectangle,
  3415. initialize: function() {
  3416. var me = this;
  3417. var meta;
  3418. core_datasetController.prototype.initialize.apply(me, arguments);
  3419. meta = me.getMeta();
  3420. meta.stack = me.getDataset().stack;
  3421. meta.bar = true;
  3422. },
  3423. update: function(reset) {
  3424. var me = this;
  3425. var rects = me.getMeta().data;
  3426. var i, ilen;
  3427. me._ruler = me.getRuler();
  3428. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  3429. me.updateElement(rects[i], i, reset);
  3430. }
  3431. },
  3432. updateElement: function(rectangle, index, reset) {
  3433. var me = this;
  3434. var meta = me.getMeta();
  3435. var dataset = me.getDataset();
  3436. var options = me._resolveElementOptions(rectangle, index);
  3437. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  3438. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  3439. rectangle._datasetIndex = me.index;
  3440. rectangle._index = index;
  3441. rectangle._model = {
  3442. backgroundColor: options.backgroundColor,
  3443. borderColor: options.borderColor,
  3444. borderSkipped: options.borderSkipped,
  3445. borderWidth: options.borderWidth,
  3446. datasetLabel: dataset.label,
  3447. label: me.chart.data.labels[index]
  3448. };
  3449. me._updateElementGeometry(rectangle, index, reset);
  3450. rectangle.pivot();
  3451. },
  3452. /**
  3453. * @private
  3454. */
  3455. _updateElementGeometry: function(rectangle, index, reset) {
  3456. var me = this;
  3457. var model = rectangle._model;
  3458. var vscale = me._getValueScale();
  3459. var base = vscale.getBasePixel();
  3460. var horizontal = vscale.isHorizontal();
  3461. var ruler = me._ruler || me.getRuler();
  3462. var vpixels = me.calculateBarValuePixels(me.index, index);
  3463. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
  3464. model.horizontal = horizontal;
  3465. model.base = reset ? base : vpixels.base;
  3466. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  3467. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  3468. model.height = horizontal ? ipixels.size : undefined;
  3469. model.width = horizontal ? undefined : ipixels.size;
  3470. },
  3471. /**
  3472. * Returns the stacks based on groups and bar visibility.
  3473. * @param {number} [last] - The dataset index
  3474. * @returns {string[]} The list of stack IDs
  3475. * @private
  3476. */
  3477. _getStacks: function(last) {
  3478. var me = this;
  3479. var chart = me.chart;
  3480. var scale = me._getIndexScale();
  3481. var stacked = scale.options.stacked;
  3482. var ilen = last === undefined ? chart.data.datasets.length : last + 1;
  3483. var stacks = [];
  3484. var i, meta;
  3485. for (i = 0; i < ilen; ++i) {
  3486. meta = chart.getDatasetMeta(i);
  3487. if (meta.bar && chart.isDatasetVisible(i) &&
  3488. (stacked === false ||
  3489. (stacked === true && stacks.indexOf(meta.stack) === -1) ||
  3490. (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
  3491. stacks.push(meta.stack);
  3492. }
  3493. }
  3494. return stacks;
  3495. },
  3496. /**
  3497. * Returns the effective number of stacks based on groups and bar visibility.
  3498. * @private
  3499. */
  3500. getStackCount: function() {
  3501. return this._getStacks().length;
  3502. },
  3503. /**
  3504. * Returns the stack index for the given dataset based on groups and bar visibility.
  3505. * @param {number} [datasetIndex] - The dataset index
  3506. * @param {string} [name] - The stack name to find
  3507. * @returns {number} The stack index
  3508. * @private
  3509. */
  3510. getStackIndex: function(datasetIndex, name) {
  3511. var stacks = this._getStacks(datasetIndex);
  3512. var index = (name !== undefined)
  3513. ? stacks.indexOf(name)
  3514. : -1; // indexOf returns -1 if element is not present
  3515. return (index === -1)
  3516. ? stacks.length - 1
  3517. : index;
  3518. },
  3519. /**
  3520. * @private
  3521. */
  3522. getRuler: function() {
  3523. var me = this;
  3524. var scale = me._getIndexScale();
  3525. var stackCount = me.getStackCount();
  3526. var datasetIndex = me.index;
  3527. var isHorizontal = scale.isHorizontal();
  3528. var start = isHorizontal ? scale.left : scale.top;
  3529. var end = start + (isHorizontal ? scale.width : scale.height);
  3530. var pixels = [];
  3531. var i, ilen, min;
  3532. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  3533. pixels.push(scale.getPixelForValue(null, i, datasetIndex));
  3534. }
  3535. min = helpers$1.isNullOrUndef(scale.options.barThickness)
  3536. ? computeMinSampleSize(scale, pixels)
  3537. : -1;
  3538. return {
  3539. min: min,
  3540. pixels: pixels,
  3541. start: start,
  3542. end: end,
  3543. stackCount: stackCount,
  3544. scale: scale
  3545. };
  3546. },
  3547. /**
  3548. * Note: pixel values are not clamped to the scale area.
  3549. * @private
  3550. */
  3551. calculateBarValuePixels: function(datasetIndex, index) {
  3552. var me = this;
  3553. var chart = me.chart;
  3554. var meta = me.getMeta();
  3555. var scale = me._getValueScale();
  3556. var isHorizontal = scale.isHorizontal();
  3557. var datasets = chart.data.datasets;
  3558. var value = +scale.getRightValue(datasets[datasetIndex].data[index]);
  3559. var minBarLength = scale.options.minBarLength;
  3560. var stacked = scale.options.stacked;
  3561. var stack = meta.stack;
  3562. var start = 0;
  3563. var i, imeta, ivalue, base, head, size;
  3564. if (stacked || (stacked === undefined && stack !== undefined)) {
  3565. for (i = 0; i < datasetIndex; ++i) {
  3566. imeta = chart.getDatasetMeta(i);
  3567. if (imeta.bar &&
  3568. imeta.stack === stack &&
  3569. imeta.controller._getValueScaleId() === scale.id &&
  3570. chart.isDatasetVisible(i)) {
  3571. ivalue = +scale.getRightValue(datasets[i].data[index]);
  3572. if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
  3573. start += ivalue;
  3574. }
  3575. }
  3576. }
  3577. }
  3578. base = scale.getPixelForValue(start);
  3579. head = scale.getPixelForValue(start + value);
  3580. size = head - base;
  3581. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  3582. size = minBarLength;
  3583. if (value >= 0 && !isHorizontal || value < 0 && isHorizontal) {
  3584. head = base - minBarLength;
  3585. } else {
  3586. head = base + minBarLength;
  3587. }
  3588. }
  3589. return {
  3590. size: size,
  3591. base: base,
  3592. head: head,
  3593. center: head + size / 2
  3594. };
  3595. },
  3596. /**
  3597. * @private
  3598. */
  3599. calculateBarIndexPixels: function(datasetIndex, index, ruler) {
  3600. var me = this;
  3601. var options = ruler.scale.options;
  3602. var range = options.barThickness === 'flex'
  3603. ? computeFlexCategoryTraits(index, ruler, options)
  3604. : computeFitCategoryTraits(index, ruler, options);
  3605. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  3606. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  3607. var size = Math.min(
  3608. helpers$1.valueOrDefault(options.maxBarThickness, Infinity),
  3609. range.chunk * range.ratio);
  3610. return {
  3611. base: center - size / 2,
  3612. head: center + size / 2,
  3613. center: center,
  3614. size: size
  3615. };
  3616. },
  3617. draw: function() {
  3618. var me = this;
  3619. var chart = me.chart;
  3620. var scale = me._getValueScale();
  3621. var rects = me.getMeta().data;
  3622. var dataset = me.getDataset();
  3623. var ilen = rects.length;
  3624. var i = 0;
  3625. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  3626. for (; i < ilen; ++i) {
  3627. if (!isNaN(scale.getRightValue(dataset.data[i]))) {
  3628. rects[i].draw();
  3629. }
  3630. }
  3631. helpers$1.canvas.unclipArea(chart.ctx);
  3632. },
  3633. /**
  3634. * @private
  3635. */
  3636. _resolveElementOptions: function(rectangle, index) {
  3637. var me = this;
  3638. var chart = me.chart;
  3639. var datasets = chart.data.datasets;
  3640. var dataset = datasets[me.index];
  3641. var custom = rectangle.custom || {};
  3642. var options = chart.options.elements.rectangle;
  3643. var values = {};
  3644. var i, ilen, key;
  3645. // Scriptable options
  3646. var context = {
  3647. chart: chart,
  3648. dataIndex: index,
  3649. dataset: dataset,
  3650. datasetIndex: me.index
  3651. };
  3652. var keys = [
  3653. 'backgroundColor',
  3654. 'borderColor',
  3655. 'borderSkipped',
  3656. 'borderWidth'
  3657. ];
  3658. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3659. key = keys[i];
  3660. values[key] = resolve$1([
  3661. custom[key],
  3662. dataset[key],
  3663. options[key]
  3664. ], context, index);
  3665. }
  3666. return values;
  3667. }
  3668. });
  3669. var valueOrDefault$3 = helpers$1.valueOrDefault;
  3670. var resolve$2 = helpers$1.options.resolve;
  3671. core_defaults._set('bubble', {
  3672. hover: {
  3673. mode: 'single'
  3674. },
  3675. scales: {
  3676. xAxes: [{
  3677. type: 'linear', // bubble should probably use a linear scale by default
  3678. position: 'bottom',
  3679. id: 'x-axis-0' // need an ID so datasets can reference the scale
  3680. }],
  3681. yAxes: [{
  3682. type: 'linear',
  3683. position: 'left',
  3684. id: 'y-axis-0'
  3685. }]
  3686. },
  3687. tooltips: {
  3688. callbacks: {
  3689. title: function() {
  3690. // Title doesn't make sense for scatter since we format the data as a point
  3691. return '';
  3692. },
  3693. label: function(item, data) {
  3694. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  3695. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  3696. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  3697. }
  3698. }
  3699. }
  3700. });
  3701. var controller_bubble = core_datasetController.extend({
  3702. /**
  3703. * @protected
  3704. */
  3705. dataElementType: elements.Point,
  3706. /**
  3707. * @protected
  3708. */
  3709. update: function(reset) {
  3710. var me = this;
  3711. var meta = me.getMeta();
  3712. var points = meta.data;
  3713. // Update Points
  3714. helpers$1.each(points, function(point, index) {
  3715. me.updateElement(point, index, reset);
  3716. });
  3717. },
  3718. /**
  3719. * @protected
  3720. */
  3721. updateElement: function(point, index, reset) {
  3722. var me = this;
  3723. var meta = me.getMeta();
  3724. var custom = point.custom || {};
  3725. var xScale = me.getScaleForId(meta.xAxisID);
  3726. var yScale = me.getScaleForId(meta.yAxisID);
  3727. var options = me._resolveElementOptions(point, index);
  3728. var data = me.getDataset().data[index];
  3729. var dsIndex = me.index;
  3730. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  3731. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  3732. point._xScale = xScale;
  3733. point._yScale = yScale;
  3734. point._options = options;
  3735. point._datasetIndex = dsIndex;
  3736. point._index = index;
  3737. point._model = {
  3738. backgroundColor: options.backgroundColor,
  3739. borderColor: options.borderColor,
  3740. borderWidth: options.borderWidth,
  3741. hitRadius: options.hitRadius,
  3742. pointStyle: options.pointStyle,
  3743. rotation: options.rotation,
  3744. radius: reset ? 0 : options.radius,
  3745. skip: custom.skip || isNaN(x) || isNaN(y),
  3746. x: x,
  3747. y: y,
  3748. };
  3749. point.pivot();
  3750. },
  3751. /**
  3752. * @protected
  3753. */
  3754. setHoverStyle: function(point) {
  3755. var model = point._model;
  3756. var options = point._options;
  3757. var getHoverColor = helpers$1.getHoverColor;
  3758. point.$previousStyle = {
  3759. backgroundColor: model.backgroundColor,
  3760. borderColor: model.borderColor,
  3761. borderWidth: model.borderWidth,
  3762. radius: model.radius
  3763. };
  3764. model.backgroundColor = valueOrDefault$3(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  3765. model.borderColor = valueOrDefault$3(options.hoverBorderColor, getHoverColor(options.borderColor));
  3766. model.borderWidth = valueOrDefault$3(options.hoverBorderWidth, options.borderWidth);
  3767. model.radius = options.radius + options.hoverRadius;
  3768. },
  3769. /**
  3770. * @private
  3771. */
  3772. _resolveElementOptions: function(point, index) {
  3773. var me = this;
  3774. var chart = me.chart;
  3775. var datasets = chart.data.datasets;
  3776. var dataset = datasets[me.index];
  3777. var custom = point.custom || {};
  3778. var options = chart.options.elements.point;
  3779. var data = dataset.data[index];
  3780. var values = {};
  3781. var i, ilen, key;
  3782. // Scriptable options
  3783. var context = {
  3784. chart: chart,
  3785. dataIndex: index,
  3786. dataset: dataset,
  3787. datasetIndex: me.index
  3788. };
  3789. var keys = [
  3790. 'backgroundColor',
  3791. 'borderColor',
  3792. 'borderWidth',
  3793. 'hoverBackgroundColor',
  3794. 'hoverBorderColor',
  3795. 'hoverBorderWidth',
  3796. 'hoverRadius',
  3797. 'hitRadius',
  3798. 'pointStyle',
  3799. 'rotation'
  3800. ];
  3801. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3802. key = keys[i];
  3803. values[key] = resolve$2([
  3804. custom[key],
  3805. dataset[key],
  3806. options[key]
  3807. ], context, index);
  3808. }
  3809. // Custom radius resolution
  3810. values.radius = resolve$2([
  3811. custom.radius,
  3812. data ? data.r : undefined,
  3813. dataset.radius,
  3814. options.radius
  3815. ], context, index);
  3816. return values;
  3817. }
  3818. });
  3819. var resolve$3 = helpers$1.options.resolve;
  3820. var valueOrDefault$4 = helpers$1.valueOrDefault;
  3821. core_defaults._set('doughnut', {
  3822. animation: {
  3823. // Boolean - Whether we animate the rotation of the Doughnut
  3824. animateRotate: true,
  3825. // Boolean - Whether we animate scaling the Doughnut from the centre
  3826. animateScale: false
  3827. },
  3828. hover: {
  3829. mode: 'single'
  3830. },
  3831. legendCallback: function(chart) {
  3832. var text = [];
  3833. text.push('<ul class="' + chart.id + '-legend">');
  3834. var data = chart.data;
  3835. var datasets = data.datasets;
  3836. var labels = data.labels;
  3837. if (datasets.length) {
  3838. for (var i = 0; i < datasets[0].data.length; ++i) {
  3839. text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
  3840. if (labels[i]) {
  3841. text.push(labels[i]);
  3842. }
  3843. text.push('</li>');
  3844. }
  3845. }
  3846. text.push('</ul>');
  3847. return text.join('');
  3848. },
  3849. legend: {
  3850. labels: {
  3851. generateLabels: function(chart) {
  3852. var data = chart.data;
  3853. if (data.labels.length && data.datasets.length) {
  3854. return data.labels.map(function(label, i) {
  3855. var meta = chart.getDatasetMeta(0);
  3856. var ds = data.datasets[0];
  3857. var arc = meta.data[i];
  3858. var custom = arc && arc.custom || {};
  3859. var arcOpts = chart.options.elements.arc;
  3860. var fill = resolve$3([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i);
  3861. var stroke = resolve$3([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i);
  3862. var bw = resolve$3([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i);
  3863. return {
  3864. text: label,
  3865. fillStyle: fill,
  3866. strokeStyle: stroke,
  3867. lineWidth: bw,
  3868. hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
  3869. // Extra data used for toggling the correct item
  3870. index: i
  3871. };
  3872. });
  3873. }
  3874. return [];
  3875. }
  3876. },
  3877. onClick: function(e, legendItem) {
  3878. var index = legendItem.index;
  3879. var chart = this.chart;
  3880. var i, ilen, meta;
  3881. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  3882. meta = chart.getDatasetMeta(i);
  3883. // toggle visibility of index if exists
  3884. if (meta.data[index]) {
  3885. meta.data[index].hidden = !meta.data[index].hidden;
  3886. }
  3887. }
  3888. chart.update();
  3889. }
  3890. },
  3891. // The percentage of the chart that we cut out of the middle.
  3892. cutoutPercentage: 50,
  3893. // The rotation of the chart, where the first data arc begins.
  3894. rotation: Math.PI * -0.5,
  3895. // The total circumference of the chart.
  3896. circumference: Math.PI * 2.0,
  3897. // Need to override these to give a nice default
  3898. tooltips: {
  3899. callbacks: {
  3900. title: function() {
  3901. return '';
  3902. },
  3903. label: function(tooltipItem, data) {
  3904. var dataLabel = data.labels[tooltipItem.index];
  3905. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  3906. if (helpers$1.isArray(dataLabel)) {
  3907. // show value on first line of multiline label
  3908. // need to clone because we are changing the value
  3909. dataLabel = dataLabel.slice();
  3910. dataLabel[0] += value;
  3911. } else {
  3912. dataLabel += value;
  3913. }
  3914. return dataLabel;
  3915. }
  3916. }
  3917. }
  3918. });
  3919. var controller_doughnut = core_datasetController.extend({
  3920. dataElementType: elements.Arc,
  3921. linkScales: helpers$1.noop,
  3922. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  3923. getRingIndex: function(datasetIndex) {
  3924. var ringIndex = 0;
  3925. for (var j = 0; j < datasetIndex; ++j) {
  3926. if (this.chart.isDatasetVisible(j)) {
  3927. ++ringIndex;
  3928. }
  3929. }
  3930. return ringIndex;
  3931. },
  3932. update: function(reset) {
  3933. var me = this;
  3934. var chart = me.chart;
  3935. var chartArea = chart.chartArea;
  3936. var opts = chart.options;
  3937. var availableWidth = chartArea.right - chartArea.left;
  3938. var availableHeight = chartArea.bottom - chartArea.top;
  3939. var minSize = Math.min(availableWidth, availableHeight);
  3940. var offset = {x: 0, y: 0};
  3941. var meta = me.getMeta();
  3942. var arcs = meta.data;
  3943. var cutoutPercentage = opts.cutoutPercentage;
  3944. var circumference = opts.circumference;
  3945. var chartWeight = me._getRingWeight(me.index);
  3946. var i, ilen;
  3947. // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
  3948. if (circumference < Math.PI * 2.0) {
  3949. var startAngle = opts.rotation % (Math.PI * 2.0);
  3950. startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
  3951. var endAngle = startAngle + circumference;
  3952. var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
  3953. var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
  3954. var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
  3955. var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
  3956. var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
  3957. var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
  3958. var cutout = cutoutPercentage / 100.0;
  3959. var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))};
  3960. var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))};
  3961. var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
  3962. minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
  3963. offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
  3964. }
  3965. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  3966. arcs[i]._options = me._resolveElementOptions(arcs[i], i);
  3967. }
  3968. chart.borderWidth = me.getMaxBorderWidth();
  3969. chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
  3970. chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
  3971. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  3972. chart.offsetX = offset.x * chart.outerRadius;
  3973. chart.offsetY = offset.y * chart.outerRadius;
  3974. meta.total = me.calculateTotal();
  3975. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  3976. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  3977. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  3978. me.updateElement(arcs[i], i, reset);
  3979. }
  3980. },
  3981. updateElement: function(arc, index, reset) {
  3982. var me = this;
  3983. var chart = me.chart;
  3984. var chartArea = chart.chartArea;
  3985. var opts = chart.options;
  3986. var animationOpts = opts.animation;
  3987. var centerX = (chartArea.left + chartArea.right) / 2;
  3988. var centerY = (chartArea.top + chartArea.bottom) / 2;
  3989. var startAngle = opts.rotation; // non reset case handled later
  3990. var endAngle = opts.rotation; // non reset case handled later
  3991. var dataset = me.getDataset();
  3992. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI));
  3993. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  3994. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  3995. var options = arc._options || {};
  3996. helpers$1.extend(arc, {
  3997. // Utility
  3998. _datasetIndex: me.index,
  3999. _index: index,
  4000. // Desired view properties
  4001. _model: {
  4002. backgroundColor: options.backgroundColor,
  4003. borderColor: options.borderColor,
  4004. borderWidth: options.borderWidth,
  4005. borderAlign: options.borderAlign,
  4006. x: centerX + chart.offsetX,
  4007. y: centerY + chart.offsetY,
  4008. startAngle: startAngle,
  4009. endAngle: endAngle,
  4010. circumference: circumference,
  4011. outerRadius: outerRadius,
  4012. innerRadius: innerRadius,
  4013. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4014. }
  4015. });
  4016. var model = arc._model;
  4017. // Set correct angles if not resetting
  4018. if (!reset || !animationOpts.animateRotate) {
  4019. if (index === 0) {
  4020. model.startAngle = opts.rotation;
  4021. } else {
  4022. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4023. }
  4024. model.endAngle = model.startAngle + model.circumference;
  4025. }
  4026. arc.pivot();
  4027. },
  4028. calculateTotal: function() {
  4029. var dataset = this.getDataset();
  4030. var meta = this.getMeta();
  4031. var total = 0;
  4032. var value;
  4033. helpers$1.each(meta.data, function(element, index) {
  4034. value = dataset.data[index];
  4035. if (!isNaN(value) && !element.hidden) {
  4036. total += Math.abs(value);
  4037. }
  4038. });
  4039. /* if (total === 0) {
  4040. total = NaN;
  4041. }*/
  4042. return total;
  4043. },
  4044. calculateCircumference: function(value) {
  4045. var total = this.getMeta().total;
  4046. if (total > 0 && !isNaN(value)) {
  4047. return (Math.PI * 2.0) * (Math.abs(value) / total);
  4048. }
  4049. return 0;
  4050. },
  4051. // gets the max border or hover width to properly scale pie charts
  4052. getMaxBorderWidth: function(arcs) {
  4053. var me = this;
  4054. var max = 0;
  4055. var chart = me.chart;
  4056. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4057. if (!arcs) {
  4058. // Find the outmost visible dataset
  4059. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4060. if (chart.isDatasetVisible(i)) {
  4061. meta = chart.getDatasetMeta(i);
  4062. arcs = meta.data;
  4063. if (i !== me.index) {
  4064. controller = meta.controller;
  4065. }
  4066. break;
  4067. }
  4068. }
  4069. }
  4070. if (!arcs) {
  4071. return 0;
  4072. }
  4073. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4074. arc = arcs[i];
  4075. options = controller ? controller._resolveElementOptions(arc, i) : arc._options;
  4076. if (options.borderAlign !== 'inner') {
  4077. borderWidth = options.borderWidth;
  4078. hoverWidth = options.hoverBorderWidth;
  4079. max = borderWidth > max ? borderWidth : max;
  4080. max = hoverWidth > max ? hoverWidth : max;
  4081. }
  4082. }
  4083. return max;
  4084. },
  4085. /**
  4086. * @protected
  4087. */
  4088. setHoverStyle: function(arc) {
  4089. var model = arc._model;
  4090. var options = arc._options;
  4091. var getHoverColor = helpers$1.getHoverColor;
  4092. arc.$previousStyle = {
  4093. backgroundColor: model.backgroundColor,
  4094. borderColor: model.borderColor,
  4095. borderWidth: model.borderWidth,
  4096. };
  4097. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4098. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4099. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4100. },
  4101. /**
  4102. * @private
  4103. */
  4104. _resolveElementOptions: function(arc, index) {
  4105. var me = this;
  4106. var chart = me.chart;
  4107. var dataset = me.getDataset();
  4108. var custom = arc.custom || {};
  4109. var options = chart.options.elements.arc;
  4110. var values = {};
  4111. var i, ilen, key;
  4112. // Scriptable options
  4113. var context = {
  4114. chart: chart,
  4115. dataIndex: index,
  4116. dataset: dataset,
  4117. datasetIndex: me.index
  4118. };
  4119. var keys = [
  4120. 'backgroundColor',
  4121. 'borderColor',
  4122. 'borderWidth',
  4123. 'borderAlign',
  4124. 'hoverBackgroundColor',
  4125. 'hoverBorderColor',
  4126. 'hoverBorderWidth',
  4127. ];
  4128. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4129. key = keys[i];
  4130. values[key] = resolve$3([
  4131. custom[key],
  4132. dataset[key],
  4133. options[key]
  4134. ], context, index);
  4135. }
  4136. return values;
  4137. },
  4138. /**
  4139. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4140. * @private
  4141. */
  4142. _getRingWeightOffset: function(datasetIndex) {
  4143. var ringWeightOffset = 0;
  4144. for (var i = 0; i < datasetIndex; ++i) {
  4145. if (this.chart.isDatasetVisible(i)) {
  4146. ringWeightOffset += this._getRingWeight(i);
  4147. }
  4148. }
  4149. return ringWeightOffset;
  4150. },
  4151. /**
  4152. * @private
  4153. */
  4154. _getRingWeight: function(dataSetIndex) {
  4155. return Math.max(valueOrDefault$4(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4156. },
  4157. /**
  4158. * Returns the sum of all visibile data set weights. This value can be 0.
  4159. * @private
  4160. */
  4161. _getVisibleDatasetWeightTotal: function() {
  4162. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4163. }
  4164. });
  4165. core_defaults._set('horizontalBar', {
  4166. hover: {
  4167. mode: 'index',
  4168. axis: 'y'
  4169. },
  4170. scales: {
  4171. xAxes: [{
  4172. type: 'linear',
  4173. position: 'bottom'
  4174. }],
  4175. yAxes: [{
  4176. type: 'category',
  4177. position: 'left',
  4178. categoryPercentage: 0.8,
  4179. barPercentage: 0.9,
  4180. offset: true,
  4181. gridLines: {
  4182. offsetGridLines: true
  4183. }
  4184. }]
  4185. },
  4186. elements: {
  4187. rectangle: {
  4188. borderSkipped: 'left'
  4189. }
  4190. },
  4191. tooltips: {
  4192. mode: 'index',
  4193. axis: 'y'
  4194. }
  4195. });
  4196. var controller_horizontalBar = controller_bar.extend({
  4197. /**
  4198. * @private
  4199. */
  4200. _getValueScaleId: function() {
  4201. return this.getMeta().xAxisID;
  4202. },
  4203. /**
  4204. * @private
  4205. */
  4206. _getIndexScaleId: function() {
  4207. return this.getMeta().yAxisID;
  4208. }
  4209. });
  4210. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4211. var resolve$4 = helpers$1.options.resolve;
  4212. var isPointInArea = helpers$1.canvas._isPointInArea;
  4213. core_defaults._set('line', {
  4214. showLines: true,
  4215. spanGaps: false,
  4216. hover: {
  4217. mode: 'label'
  4218. },
  4219. scales: {
  4220. xAxes: [{
  4221. type: 'category',
  4222. id: 'x-axis-0'
  4223. }],
  4224. yAxes: [{
  4225. type: 'linear',
  4226. id: 'y-axis-0'
  4227. }]
  4228. }
  4229. });
  4230. function lineEnabled(dataset, options) {
  4231. return valueOrDefault$5(dataset.showLine, options.showLines);
  4232. }
  4233. var controller_line = core_datasetController.extend({
  4234. datasetElementType: elements.Line,
  4235. dataElementType: elements.Point,
  4236. update: function(reset) {
  4237. var me = this;
  4238. var meta = me.getMeta();
  4239. var line = meta.dataset;
  4240. var points = meta.data || [];
  4241. var scale = me.getScaleForId(meta.yAxisID);
  4242. var dataset = me.getDataset();
  4243. var showLine = lineEnabled(dataset, me.chart.options);
  4244. var i, ilen;
  4245. // Update Line
  4246. if (showLine) {
  4247. // Compatibility: If the properties are defined with only the old name, use those values
  4248. if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
  4249. dataset.lineTension = dataset.tension;
  4250. }
  4251. // Utility
  4252. line._scale = scale;
  4253. line._datasetIndex = me.index;
  4254. // Data
  4255. line._children = points;
  4256. // Model
  4257. line._model = me._resolveLineOptions(line);
  4258. line.pivot();
  4259. }
  4260. // Update Points
  4261. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4262. me.updateElement(points[i], i, reset);
  4263. }
  4264. if (showLine && line._model.tension !== 0) {
  4265. me.updateBezierControlPoints();
  4266. }
  4267. // Now pivot the point for animation
  4268. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4269. points[i].pivot();
  4270. }
  4271. },
  4272. updateElement: function(point, index, reset) {
  4273. var me = this;
  4274. var meta = me.getMeta();
  4275. var custom = point.custom || {};
  4276. var dataset = me.getDataset();
  4277. var datasetIndex = me.index;
  4278. var value = dataset.data[index];
  4279. var yScale = me.getScaleForId(meta.yAxisID);
  4280. var xScale = me.getScaleForId(meta.xAxisID);
  4281. var lineModel = meta.dataset._model;
  4282. var x, y;
  4283. var options = me._resolvePointOptions(point, index);
  4284. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  4285. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  4286. // Utility
  4287. point._xScale = xScale;
  4288. point._yScale = yScale;
  4289. point._options = options;
  4290. point._datasetIndex = datasetIndex;
  4291. point._index = index;
  4292. // Desired view properties
  4293. point._model = {
  4294. x: x,
  4295. y: y,
  4296. skip: custom.skip || isNaN(x) || isNaN(y),
  4297. // Appearance
  4298. radius: options.radius,
  4299. pointStyle: options.pointStyle,
  4300. rotation: options.rotation,
  4301. backgroundColor: options.backgroundColor,
  4302. borderColor: options.borderColor,
  4303. borderWidth: options.borderWidth,
  4304. tension: valueOrDefault$5(custom.tension, lineModel ? lineModel.tension : 0),
  4305. steppedLine: lineModel ? lineModel.steppedLine : false,
  4306. // Tooltip
  4307. hitRadius: options.hitRadius
  4308. };
  4309. },
  4310. /**
  4311. * @private
  4312. */
  4313. _resolvePointOptions: function(element, index) {
  4314. var me = this;
  4315. var chart = me.chart;
  4316. var dataset = chart.data.datasets[me.index];
  4317. var custom = element.custom || {};
  4318. var options = chart.options.elements.point;
  4319. var values = {};
  4320. var i, ilen, key;
  4321. // Scriptable options
  4322. var context = {
  4323. chart: chart,
  4324. dataIndex: index,
  4325. dataset: dataset,
  4326. datasetIndex: me.index
  4327. };
  4328. var ELEMENT_OPTIONS = {
  4329. backgroundColor: 'pointBackgroundColor',
  4330. borderColor: 'pointBorderColor',
  4331. borderWidth: 'pointBorderWidth',
  4332. hitRadius: 'pointHitRadius',
  4333. hoverBackgroundColor: 'pointHoverBackgroundColor',
  4334. hoverBorderColor: 'pointHoverBorderColor',
  4335. hoverBorderWidth: 'pointHoverBorderWidth',
  4336. hoverRadius: 'pointHoverRadius',
  4337. pointStyle: 'pointStyle',
  4338. radius: 'pointRadius',
  4339. rotation: 'pointRotation'
  4340. };
  4341. var keys = Object.keys(ELEMENT_OPTIONS);
  4342. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4343. key = keys[i];
  4344. values[key] = resolve$4([
  4345. custom[key],
  4346. dataset[ELEMENT_OPTIONS[key]],
  4347. dataset[key],
  4348. options[key]
  4349. ], context, index);
  4350. }
  4351. return values;
  4352. },
  4353. /**
  4354. * @private
  4355. */
  4356. _resolveLineOptions: function(element) {
  4357. var me = this;
  4358. var chart = me.chart;
  4359. var dataset = chart.data.datasets[me.index];
  4360. var custom = element.custom || {};
  4361. var options = chart.options;
  4362. var elementOptions = options.elements.line;
  4363. var values = {};
  4364. var i, ilen, key;
  4365. var keys = [
  4366. 'backgroundColor',
  4367. 'borderWidth',
  4368. 'borderColor',
  4369. 'borderCapStyle',
  4370. 'borderDash',
  4371. 'borderDashOffset',
  4372. 'borderJoinStyle',
  4373. 'fill',
  4374. 'cubicInterpolationMode'
  4375. ];
  4376. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4377. key = keys[i];
  4378. values[key] = resolve$4([
  4379. custom[key],
  4380. dataset[key],
  4381. elementOptions[key]
  4382. ]);
  4383. }
  4384. // The default behavior of lines is to break at null values, according
  4385. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  4386. // This option gives lines the ability to span gaps
  4387. values.spanGaps = valueOrDefault$5(dataset.spanGaps, options.spanGaps);
  4388. values.tension = valueOrDefault$5(dataset.lineTension, elementOptions.tension);
  4389. values.steppedLine = resolve$4([custom.steppedLine, dataset.steppedLine, elementOptions.stepped]);
  4390. return values;
  4391. },
  4392. calculatePointY: function(value, index, datasetIndex) {
  4393. var me = this;
  4394. var chart = me.chart;
  4395. var meta = me.getMeta();
  4396. var yScale = me.getScaleForId(meta.yAxisID);
  4397. var sumPos = 0;
  4398. var sumNeg = 0;
  4399. var i, ds, dsMeta;
  4400. if (yScale.options.stacked) {
  4401. for (i = 0; i < datasetIndex; i++) {
  4402. ds = chart.data.datasets[i];
  4403. dsMeta = chart.getDatasetMeta(i);
  4404. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
  4405. var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
  4406. if (stackedRightValue < 0) {
  4407. sumNeg += stackedRightValue || 0;
  4408. } else {
  4409. sumPos += stackedRightValue || 0;
  4410. }
  4411. }
  4412. }
  4413. var rightValue = Number(yScale.getRightValue(value));
  4414. if (rightValue < 0) {
  4415. return yScale.getPixelForValue(sumNeg + rightValue);
  4416. }
  4417. return yScale.getPixelForValue(sumPos + rightValue);
  4418. }
  4419. return yScale.getPixelForValue(value);
  4420. },
  4421. updateBezierControlPoints: function() {
  4422. var me = this;
  4423. var chart = me.chart;
  4424. var meta = me.getMeta();
  4425. var lineModel = meta.dataset._model;
  4426. var area = chart.chartArea;
  4427. var points = meta.data || [];
  4428. var i, ilen, model, controlPoints;
  4429. // Only consider points that are drawn in case the spanGaps option is used
  4430. if (lineModel.spanGaps) {
  4431. points = points.filter(function(pt) {
  4432. return !pt._model.skip;
  4433. });
  4434. }
  4435. function capControlPoint(pt, min, max) {
  4436. return Math.max(Math.min(pt, max), min);
  4437. }
  4438. if (lineModel.cubicInterpolationMode === 'monotone') {
  4439. helpers$1.splineCurveMonotone(points);
  4440. } else {
  4441. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4442. model = points[i]._model;
  4443. controlPoints = helpers$1.splineCurve(
  4444. helpers$1.previousItem(points, i)._model,
  4445. model,
  4446. helpers$1.nextItem(points, i)._model,
  4447. lineModel.tension
  4448. );
  4449. model.controlPointPreviousX = controlPoints.previous.x;
  4450. model.controlPointPreviousY = controlPoints.previous.y;
  4451. model.controlPointNextX = controlPoints.next.x;
  4452. model.controlPointNextY = controlPoints.next.y;
  4453. }
  4454. }
  4455. if (chart.options.elements.line.capBezierPoints) {
  4456. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4457. model = points[i]._model;
  4458. if (isPointInArea(model, area)) {
  4459. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  4460. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  4461. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  4462. }
  4463. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  4464. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  4465. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  4466. }
  4467. }
  4468. }
  4469. }
  4470. },
  4471. draw: function() {
  4472. var me = this;
  4473. var chart = me.chart;
  4474. var meta = me.getMeta();
  4475. var points = meta.data || [];
  4476. var area = chart.chartArea;
  4477. var ilen = points.length;
  4478. var halfBorderWidth;
  4479. var i = 0;
  4480. if (lineEnabled(me.getDataset(), chart.options)) {
  4481. halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2;
  4482. helpers$1.canvas.clipArea(chart.ctx, {
  4483. left: area.left,
  4484. right: area.right,
  4485. top: area.top - halfBorderWidth,
  4486. bottom: area.bottom + halfBorderWidth
  4487. });
  4488. meta.dataset.draw();
  4489. helpers$1.canvas.unclipArea(chart.ctx);
  4490. }
  4491. // Draw the points
  4492. for (; i < ilen; ++i) {
  4493. points[i].draw(area);
  4494. }
  4495. },
  4496. /**
  4497. * @protected
  4498. */
  4499. setHoverStyle: function(point) {
  4500. var model = point._model;
  4501. var options = point._options;
  4502. var getHoverColor = helpers$1.getHoverColor;
  4503. point.$previousStyle = {
  4504. backgroundColor: model.backgroundColor,
  4505. borderColor: model.borderColor,
  4506. borderWidth: model.borderWidth,
  4507. radius: model.radius
  4508. };
  4509. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4510. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4511. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4512. model.radius = valueOrDefault$5(options.hoverRadius, options.radius);
  4513. },
  4514. });
  4515. var resolve$5 = helpers$1.options.resolve;
  4516. core_defaults._set('polarArea', {
  4517. scale: {
  4518. type: 'radialLinear',
  4519. angleLines: {
  4520. display: false
  4521. },
  4522. gridLines: {
  4523. circular: true
  4524. },
  4525. pointLabels: {
  4526. display: false
  4527. },
  4528. ticks: {
  4529. beginAtZero: true
  4530. }
  4531. },
  4532. // Boolean - Whether to animate the rotation of the chart
  4533. animation: {
  4534. animateRotate: true,
  4535. animateScale: true
  4536. },
  4537. startAngle: -0.5 * Math.PI,
  4538. legendCallback: function(chart) {
  4539. var text = [];
  4540. text.push('<ul class="' + chart.id + '-legend">');
  4541. var data = chart.data;
  4542. var datasets = data.datasets;
  4543. var labels = data.labels;
  4544. if (datasets.length) {
  4545. for (var i = 0; i < datasets[0].data.length; ++i) {
  4546. text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
  4547. if (labels[i]) {
  4548. text.push(labels[i]);
  4549. }
  4550. text.push('</li>');
  4551. }
  4552. }
  4553. text.push('</ul>');
  4554. return text.join('');
  4555. },
  4556. legend: {
  4557. labels: {
  4558. generateLabels: function(chart) {
  4559. var data = chart.data;
  4560. if (data.labels.length && data.datasets.length) {
  4561. return data.labels.map(function(label, i) {
  4562. var meta = chart.getDatasetMeta(0);
  4563. var ds = data.datasets[0];
  4564. var arc = meta.data[i];
  4565. var custom = arc.custom || {};
  4566. var arcOpts = chart.options.elements.arc;
  4567. var fill = resolve$5([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i);
  4568. var stroke = resolve$5([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i);
  4569. var bw = resolve$5([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i);
  4570. return {
  4571. text: label,
  4572. fillStyle: fill,
  4573. strokeStyle: stroke,
  4574. lineWidth: bw,
  4575. hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
  4576. // Extra data used for toggling the correct item
  4577. index: i
  4578. };
  4579. });
  4580. }
  4581. return [];
  4582. }
  4583. },
  4584. onClick: function(e, legendItem) {
  4585. var index = legendItem.index;
  4586. var chart = this.chart;
  4587. var i, ilen, meta;
  4588. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4589. meta = chart.getDatasetMeta(i);
  4590. meta.data[index].hidden = !meta.data[index].hidden;
  4591. }
  4592. chart.update();
  4593. }
  4594. },
  4595. // Need to override these to give a nice default
  4596. tooltips: {
  4597. callbacks: {
  4598. title: function() {
  4599. return '';
  4600. },
  4601. label: function(item, data) {
  4602. return data.labels[item.index] + ': ' + item.yLabel;
  4603. }
  4604. }
  4605. }
  4606. });
  4607. var controller_polarArea = core_datasetController.extend({
  4608. dataElementType: elements.Arc,
  4609. linkScales: helpers$1.noop,
  4610. update: function(reset) {
  4611. var me = this;
  4612. var dataset = me.getDataset();
  4613. var meta = me.getMeta();
  4614. var start = me.chart.options.startAngle || 0;
  4615. var starts = me._starts = [];
  4616. var angles = me._angles = [];
  4617. var arcs = meta.data;
  4618. var i, ilen, angle;
  4619. me._updateRadius();
  4620. meta.count = me.countVisibleElements();
  4621. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  4622. starts[i] = start;
  4623. angle = me._computeAngle(i);
  4624. angles[i] = angle;
  4625. start += angle;
  4626. }
  4627. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4628. arcs[i]._options = me._resolveElementOptions(arcs[i], i);
  4629. me.updateElement(arcs[i], i, reset);
  4630. }
  4631. },
  4632. /**
  4633. * @private
  4634. */
  4635. _updateRadius: function() {
  4636. var me = this;
  4637. var chart = me.chart;
  4638. var chartArea = chart.chartArea;
  4639. var opts = chart.options;
  4640. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  4641. chart.outerRadius = Math.max(minSize / 2, 0);
  4642. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  4643. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  4644. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  4645. me.innerRadius = me.outerRadius - chart.radiusLength;
  4646. },
  4647. updateElement: function(arc, index, reset) {
  4648. var me = this;
  4649. var chart = me.chart;
  4650. var dataset = me.getDataset();
  4651. var opts = chart.options;
  4652. var animationOpts = opts.animation;
  4653. var scale = chart.scale;
  4654. var labels = chart.data.labels;
  4655. var centerX = scale.xCenter;
  4656. var centerY = scale.yCenter;
  4657. // var negHalfPI = -0.5 * Math.PI;
  4658. var datasetStartAngle = opts.startAngle;
  4659. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  4660. var startAngle = me._starts[index];
  4661. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  4662. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  4663. var options = arc._options || {};
  4664. helpers$1.extend(arc, {
  4665. // Utility
  4666. _datasetIndex: me.index,
  4667. _index: index,
  4668. _scale: scale,
  4669. // Desired view properties
  4670. _model: {
  4671. backgroundColor: options.backgroundColor,
  4672. borderColor: options.borderColor,
  4673. borderWidth: options.borderWidth,
  4674. borderAlign: options.borderAlign,
  4675. x: centerX,
  4676. y: centerY,
  4677. innerRadius: 0,
  4678. outerRadius: reset ? resetRadius : distance,
  4679. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  4680. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  4681. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  4682. }
  4683. });
  4684. arc.pivot();
  4685. },
  4686. countVisibleElements: function() {
  4687. var dataset = this.getDataset();
  4688. var meta = this.getMeta();
  4689. var count = 0;
  4690. helpers$1.each(meta.data, function(element, index) {
  4691. if (!isNaN(dataset.data[index]) && !element.hidden) {
  4692. count++;
  4693. }
  4694. });
  4695. return count;
  4696. },
  4697. /**
  4698. * @protected
  4699. */
  4700. setHoverStyle: function(arc) {
  4701. var model = arc._model;
  4702. var options = arc._options;
  4703. var getHoverColor = helpers$1.getHoverColor;
  4704. var valueOrDefault = helpers$1.valueOrDefault;
  4705. arc.$previousStyle = {
  4706. backgroundColor: model.backgroundColor,
  4707. borderColor: model.borderColor,
  4708. borderWidth: model.borderWidth,
  4709. };
  4710. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4711. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  4712. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  4713. },
  4714. /**
  4715. * @private
  4716. */
  4717. _resolveElementOptions: function(arc, index) {
  4718. var me = this;
  4719. var chart = me.chart;
  4720. var dataset = me.getDataset();
  4721. var custom = arc.custom || {};
  4722. var options = chart.options.elements.arc;
  4723. var values = {};
  4724. var i, ilen, key;
  4725. // Scriptable options
  4726. var context = {
  4727. chart: chart,
  4728. dataIndex: index,
  4729. dataset: dataset,
  4730. datasetIndex: me.index
  4731. };
  4732. var keys = [
  4733. 'backgroundColor',
  4734. 'borderColor',
  4735. 'borderWidth',
  4736. 'borderAlign',
  4737. 'hoverBackgroundColor',
  4738. 'hoverBorderColor',
  4739. 'hoverBorderWidth',
  4740. ];
  4741. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4742. key = keys[i];
  4743. values[key] = resolve$5([
  4744. custom[key],
  4745. dataset[key],
  4746. options[key]
  4747. ], context, index);
  4748. }
  4749. return values;
  4750. },
  4751. /**
  4752. * @private
  4753. */
  4754. _computeAngle: function(index) {
  4755. var me = this;
  4756. var count = this.getMeta().count;
  4757. var dataset = me.getDataset();
  4758. var meta = me.getMeta();
  4759. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  4760. return 0;
  4761. }
  4762. // Scriptable options
  4763. var context = {
  4764. chart: me.chart,
  4765. dataIndex: index,
  4766. dataset: dataset,
  4767. datasetIndex: me.index
  4768. };
  4769. return resolve$5([
  4770. me.chart.options.elements.arc.angle,
  4771. (2 * Math.PI) / count
  4772. ], context, index);
  4773. }
  4774. });
  4775. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  4776. core_defaults._set('pie', {
  4777. cutoutPercentage: 0
  4778. });
  4779. // Pie charts are Doughnut chart with different defaults
  4780. var controller_pie = controller_doughnut;
  4781. var valueOrDefault$6 = helpers$1.valueOrDefault;
  4782. var resolve$6 = helpers$1.options.resolve;
  4783. core_defaults._set('radar', {
  4784. scale: {
  4785. type: 'radialLinear'
  4786. },
  4787. elements: {
  4788. line: {
  4789. tension: 0 // no bezier in radar
  4790. }
  4791. }
  4792. });
  4793. var controller_radar = core_datasetController.extend({
  4794. datasetElementType: elements.Line,
  4795. dataElementType: elements.Point,
  4796. linkScales: helpers$1.noop,
  4797. update: function(reset) {
  4798. var me = this;
  4799. var meta = me.getMeta();
  4800. var line = meta.dataset;
  4801. var points = meta.data || [];
  4802. var scale = me.chart.scale;
  4803. var dataset = me.getDataset();
  4804. var i, ilen;
  4805. // Compatibility: If the properties are defined with only the old name, use those values
  4806. if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
  4807. dataset.lineTension = dataset.tension;
  4808. }
  4809. // Utility
  4810. line._scale = scale;
  4811. line._datasetIndex = me.index;
  4812. // Data
  4813. line._children = points;
  4814. line._loop = true;
  4815. // Model
  4816. line._model = me._resolveLineOptions(line);
  4817. line.pivot();
  4818. // Update Points
  4819. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4820. me.updateElement(points[i], i, reset);
  4821. }
  4822. // Update bezier control points
  4823. me.updateBezierControlPoints();
  4824. // Now pivot the point for animation
  4825. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4826. points[i].pivot();
  4827. }
  4828. },
  4829. updateElement: function(point, index, reset) {
  4830. var me = this;
  4831. var custom = point.custom || {};
  4832. var dataset = me.getDataset();
  4833. var scale = me.chart.scale;
  4834. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  4835. var options = me._resolvePointOptions(point, index);
  4836. var lineModel = me.getMeta().dataset._model;
  4837. var x = reset ? scale.xCenter : pointPosition.x;
  4838. var y = reset ? scale.yCenter : pointPosition.y;
  4839. // Utility
  4840. point._scale = scale;
  4841. point._options = options;
  4842. point._datasetIndex = me.index;
  4843. point._index = index;
  4844. // Desired view properties
  4845. point._model = {
  4846. x: x, // value not used in dataset scale, but we want a consistent API between scales
  4847. y: y,
  4848. skip: custom.skip || isNaN(x) || isNaN(y),
  4849. // Appearance
  4850. radius: options.radius,
  4851. pointStyle: options.pointStyle,
  4852. rotation: options.rotation,
  4853. backgroundColor: options.backgroundColor,
  4854. borderColor: options.borderColor,
  4855. borderWidth: options.borderWidth,
  4856. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  4857. // Tooltip
  4858. hitRadius: options.hitRadius
  4859. };
  4860. },
  4861. /**
  4862. * @private
  4863. */
  4864. _resolvePointOptions: function(element, index) {
  4865. var me = this;
  4866. var chart = me.chart;
  4867. var dataset = chart.data.datasets[me.index];
  4868. var custom = element.custom || {};
  4869. var options = chart.options.elements.point;
  4870. var values = {};
  4871. var i, ilen, key;
  4872. // Scriptable options
  4873. var context = {
  4874. chart: chart,
  4875. dataIndex: index,
  4876. dataset: dataset,
  4877. datasetIndex: me.index
  4878. };
  4879. var ELEMENT_OPTIONS = {
  4880. backgroundColor: 'pointBackgroundColor',
  4881. borderColor: 'pointBorderColor',
  4882. borderWidth: 'pointBorderWidth',
  4883. hitRadius: 'pointHitRadius',
  4884. hoverBackgroundColor: 'pointHoverBackgroundColor',
  4885. hoverBorderColor: 'pointHoverBorderColor',
  4886. hoverBorderWidth: 'pointHoverBorderWidth',
  4887. hoverRadius: 'pointHoverRadius',
  4888. pointStyle: 'pointStyle',
  4889. radius: 'pointRadius',
  4890. rotation: 'pointRotation'
  4891. };
  4892. var keys = Object.keys(ELEMENT_OPTIONS);
  4893. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4894. key = keys[i];
  4895. values[key] = resolve$6([
  4896. custom[key],
  4897. dataset[ELEMENT_OPTIONS[key]],
  4898. dataset[key],
  4899. options[key]
  4900. ], context, index);
  4901. }
  4902. return values;
  4903. },
  4904. /**
  4905. * @private
  4906. */
  4907. _resolveLineOptions: function(element) {
  4908. var me = this;
  4909. var chart = me.chart;
  4910. var dataset = chart.data.datasets[me.index];
  4911. var custom = element.custom || {};
  4912. var options = chart.options.elements.line;
  4913. var values = {};
  4914. var i, ilen, key;
  4915. var keys = [
  4916. 'backgroundColor',
  4917. 'borderWidth',
  4918. 'borderColor',
  4919. 'borderCapStyle',
  4920. 'borderDash',
  4921. 'borderDashOffset',
  4922. 'borderJoinStyle',
  4923. 'fill'
  4924. ];
  4925. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4926. key = keys[i];
  4927. values[key] = resolve$6([
  4928. custom[key],
  4929. dataset[key],
  4930. options[key]
  4931. ]);
  4932. }
  4933. values.tension = valueOrDefault$6(dataset.lineTension, options.tension);
  4934. return values;
  4935. },
  4936. updateBezierControlPoints: function() {
  4937. var me = this;
  4938. var meta = me.getMeta();
  4939. var area = me.chart.chartArea;
  4940. var points = meta.data || [];
  4941. var i, ilen, model, controlPoints;
  4942. function capControlPoint(pt, min, max) {
  4943. return Math.max(Math.min(pt, max), min);
  4944. }
  4945. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4946. model = points[i]._model;
  4947. controlPoints = helpers$1.splineCurve(
  4948. helpers$1.previousItem(points, i, true)._model,
  4949. model,
  4950. helpers$1.nextItem(points, i, true)._model,
  4951. model.tension
  4952. );
  4953. // Prevent the bezier going outside of the bounds of the graph
  4954. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  4955. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  4956. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  4957. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  4958. }
  4959. },
  4960. setHoverStyle: function(point) {
  4961. var model = point._model;
  4962. var options = point._options;
  4963. var getHoverColor = helpers$1.getHoverColor;
  4964. point.$previousStyle = {
  4965. backgroundColor: model.backgroundColor,
  4966. borderColor: model.borderColor,
  4967. borderWidth: model.borderWidth,
  4968. radius: model.radius
  4969. };
  4970. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4971. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  4972. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  4973. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  4974. }
  4975. });
  4976. core_defaults._set('scatter', {
  4977. hover: {
  4978. mode: 'single'
  4979. },
  4980. scales: {
  4981. xAxes: [{
  4982. id: 'x-axis-1', // need an ID so datasets can reference the scale
  4983. type: 'linear', // scatter should not use a category axis
  4984. position: 'bottom'
  4985. }],
  4986. yAxes: [{
  4987. id: 'y-axis-1',
  4988. type: 'linear',
  4989. position: 'left'
  4990. }]
  4991. },
  4992. showLines: false,
  4993. tooltips: {
  4994. callbacks: {
  4995. title: function() {
  4996. return ''; // doesn't make sense for scatter since data are formatted as a point
  4997. },
  4998. label: function(item) {
  4999. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  5000. }
  5001. }
  5002. }
  5003. });
  5004. // Scatter charts use line controllers
  5005. var controller_scatter = controller_line;
  5006. // NOTE export a map in which the key represents the controller type, not
  5007. // the class, and so must be CamelCase in order to be correctly retrieved
  5008. // by the controller in core.controller.js (`controllers[meta.type]`).
  5009. var controllers = {
  5010. bar: controller_bar,
  5011. bubble: controller_bubble,
  5012. doughnut: controller_doughnut,
  5013. horizontalBar: controller_horizontalBar,
  5014. line: controller_line,
  5015. polarArea: controller_polarArea,
  5016. pie: controller_pie,
  5017. radar: controller_radar,
  5018. scatter: controller_scatter
  5019. };
  5020. /**
  5021. * Helper function to get relative position for an event
  5022. * @param {Event|IEvent} event - The event to get the position for
  5023. * @param {Chart} chart - The chart
  5024. * @returns {object} the event position
  5025. */
  5026. function getRelativePosition(e, chart) {
  5027. if (e.native) {
  5028. return {
  5029. x: e.x,
  5030. y: e.y
  5031. };
  5032. }
  5033. return helpers$1.getRelativePosition(e, chart);
  5034. }
  5035. /**
  5036. * Helper function to traverse all of the visible elements in the chart
  5037. * @param {Chart} chart - the chart
  5038. * @param {function} handler - the callback to execute for each visible item
  5039. */
  5040. function parseVisibleItems(chart, handler) {
  5041. var datasets = chart.data.datasets;
  5042. var meta, i, j, ilen, jlen;
  5043. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  5044. if (!chart.isDatasetVisible(i)) {
  5045. continue;
  5046. }
  5047. meta = chart.getDatasetMeta(i);
  5048. for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
  5049. var element = meta.data[j];
  5050. if (!element._view.skip) {
  5051. handler(element);
  5052. }
  5053. }
  5054. }
  5055. }
  5056. /**
  5057. * Helper function to get the items that intersect the event position
  5058. * @param {ChartElement[]} items - elements to filter
  5059. * @param {object} position - the point to be nearest to
  5060. * @return {ChartElement[]} the nearest items
  5061. */
  5062. function getIntersectItems(chart, position) {
  5063. var elements = [];
  5064. parseVisibleItems(chart, function(element) {
  5065. if (element.inRange(position.x, position.y)) {
  5066. elements.push(element);
  5067. }
  5068. });
  5069. return elements;
  5070. }
  5071. /**
  5072. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5073. * @param {Chart} chart - the chart to look at elements from
  5074. * @param {object} position - the point to be nearest to
  5075. * @param {boolean} intersect - if true, only consider items that intersect the position
  5076. * @param {function} distanceMetric - function to provide the distance between points
  5077. * @return {ChartElement[]} the nearest items
  5078. */
  5079. function getNearestItems(chart, position, intersect, distanceMetric) {
  5080. var minDistance = Number.POSITIVE_INFINITY;
  5081. var nearestItems = [];
  5082. parseVisibleItems(chart, function(element) {
  5083. if (intersect && !element.inRange(position.x, position.y)) {
  5084. return;
  5085. }
  5086. var center = element.getCenterPoint();
  5087. var distance = distanceMetric(position, center);
  5088. if (distance < minDistance) {
  5089. nearestItems = [element];
  5090. minDistance = distance;
  5091. } else if (distance === minDistance) {
  5092. // Can have multiple items at the same distance in which case we sort by size
  5093. nearestItems.push(element);
  5094. }
  5095. });
  5096. return nearestItems;
  5097. }
  5098. /**
  5099. * Get a distance metric function for two points based on the
  5100. * axis mode setting
  5101. * @param {string} axis - the axis mode. x|y|xy
  5102. */
  5103. function getDistanceMetricForAxis(axis) {
  5104. var useX = axis.indexOf('x') !== -1;
  5105. var useY = axis.indexOf('y') !== -1;
  5106. return function(pt1, pt2) {
  5107. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5108. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5109. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5110. };
  5111. }
  5112. function indexMode(chart, e, options) {
  5113. var position = getRelativePosition(e, chart);
  5114. // Default axis for index mode is 'x' to match old behaviour
  5115. options.axis = options.axis || 'x';
  5116. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5117. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5118. var elements = [];
  5119. if (!items.length) {
  5120. return [];
  5121. }
  5122. chart.data.datasets.forEach(function(dataset, datasetIndex) {
  5123. if (chart.isDatasetVisible(datasetIndex)) {
  5124. var meta = chart.getDatasetMeta(datasetIndex);
  5125. var element = meta.data[items[0]._index];
  5126. // don't count items that are skipped (null data)
  5127. if (element && !element._view.skip) {
  5128. elements.push(element);
  5129. }
  5130. }
  5131. });
  5132. return elements;
  5133. }
  5134. /**
  5135. * @interface IInteractionOptions
  5136. */
  5137. /**
  5138. * If true, only consider items that intersect the point
  5139. * @name IInterfaceOptions#boolean
  5140. * @type Boolean
  5141. */
  5142. /**
  5143. * Contains interaction related functions
  5144. * @namespace Chart.Interaction
  5145. */
  5146. var core_interaction = {
  5147. // Helper function for different modes
  5148. modes: {
  5149. single: function(chart, e) {
  5150. var position = getRelativePosition(e, chart);
  5151. var elements = [];
  5152. parseVisibleItems(chart, function(element) {
  5153. if (element.inRange(position.x, position.y)) {
  5154. elements.push(element);
  5155. return elements;
  5156. }
  5157. });
  5158. return elements.slice(0, 1);
  5159. },
  5160. /**
  5161. * @function Chart.Interaction.modes.label
  5162. * @deprecated since version 2.4.0
  5163. * @todo remove at version 3
  5164. * @private
  5165. */
  5166. label: indexMode,
  5167. /**
  5168. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5169. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5170. * @function Chart.Interaction.modes.index
  5171. * @since v2.4.0
  5172. * @param {Chart} chart - the chart we are returning items from
  5173. * @param {Event} e - the event we are find things at
  5174. * @param {IInteractionOptions} options - options to use during interaction
  5175. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5176. */
  5177. index: indexMode,
  5178. /**
  5179. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5180. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5181. * @function Chart.Interaction.modes.dataset
  5182. * @param {Chart} chart - the chart we are returning items from
  5183. * @param {Event} e - the event we are find things at
  5184. * @param {IInteractionOptions} options - options to use during interaction
  5185. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5186. */
  5187. dataset: function(chart, e, options) {
  5188. var position = getRelativePosition(e, chart);
  5189. options.axis = options.axis || 'xy';
  5190. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5191. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5192. if (items.length > 0) {
  5193. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5194. }
  5195. return items;
  5196. },
  5197. /**
  5198. * @function Chart.Interaction.modes.x-axis
  5199. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5200. * @todo remove at version 3
  5201. * @private
  5202. */
  5203. 'x-axis': function(chart, e) {
  5204. return indexMode(chart, e, {intersect: false});
  5205. },
  5206. /**
  5207. * Point mode returns all elements that hit test based on the event position
  5208. * of the event
  5209. * @function Chart.Interaction.modes.intersect
  5210. * @param {Chart} chart - the chart we are returning items from
  5211. * @param {Event} e - the event we are find things at
  5212. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5213. */
  5214. point: function(chart, e) {
  5215. var position = getRelativePosition(e, chart);
  5216. return getIntersectItems(chart, position);
  5217. },
  5218. /**
  5219. * nearest mode returns the element closest to the point
  5220. * @function Chart.Interaction.modes.intersect
  5221. * @param {Chart} chart - the chart we are returning items from
  5222. * @param {Event} e - the event we are find things at
  5223. * @param {IInteractionOptions} options - options to use
  5224. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5225. */
  5226. nearest: function(chart, e, options) {
  5227. var position = getRelativePosition(e, chart);
  5228. options.axis = options.axis || 'xy';
  5229. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5230. return getNearestItems(chart, position, options.intersect, distanceMetric);
  5231. },
  5232. /**
  5233. * x mode returns the elements that hit-test at the current x coordinate
  5234. * @function Chart.Interaction.modes.x
  5235. * @param {Chart} chart - the chart we are returning items from
  5236. * @param {Event} e - the event we are find things at
  5237. * @param {IInteractionOptions} options - options to use
  5238. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5239. */
  5240. x: function(chart, e, options) {
  5241. var position = getRelativePosition(e, chart);
  5242. var items = [];
  5243. var intersectsItem = false;
  5244. parseVisibleItems(chart, function(element) {
  5245. if (element.inXRange(position.x)) {
  5246. items.push(element);
  5247. }
  5248. if (element.inRange(position.x, position.y)) {
  5249. intersectsItem = true;
  5250. }
  5251. });
  5252. // If we want to trigger on an intersect and we don't have any items
  5253. // that intersect the position, return nothing
  5254. if (options.intersect && !intersectsItem) {
  5255. items = [];
  5256. }
  5257. return items;
  5258. },
  5259. /**
  5260. * y mode returns the elements that hit-test at the current y coordinate
  5261. * @function Chart.Interaction.modes.y
  5262. * @param {Chart} chart - the chart we are returning items from
  5263. * @param {Event} e - the event we are find things at
  5264. * @param {IInteractionOptions} options - options to use
  5265. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5266. */
  5267. y: function(chart, e, options) {
  5268. var position = getRelativePosition(e, chart);
  5269. var items = [];
  5270. var intersectsItem = false;
  5271. parseVisibleItems(chart, function(element) {
  5272. if (element.inYRange(position.y)) {
  5273. items.push(element);
  5274. }
  5275. if (element.inRange(position.x, position.y)) {
  5276. intersectsItem = true;
  5277. }
  5278. });
  5279. // If we want to trigger on an intersect and we don't have any items
  5280. // that intersect the position, return nothing
  5281. if (options.intersect && !intersectsItem) {
  5282. items = [];
  5283. }
  5284. return items;
  5285. }
  5286. }
  5287. };
  5288. function filterByPosition(array, position) {
  5289. return helpers$1.where(array, function(v) {
  5290. return v.position === position;
  5291. });
  5292. }
  5293. function sortByWeight(array, reverse) {
  5294. array.forEach(function(v, i) {
  5295. v._tmpIndex_ = i;
  5296. return v;
  5297. });
  5298. array.sort(function(a, b) {
  5299. var v0 = reverse ? b : a;
  5300. var v1 = reverse ? a : b;
  5301. return v0.weight === v1.weight ?
  5302. v0._tmpIndex_ - v1._tmpIndex_ :
  5303. v0.weight - v1.weight;
  5304. });
  5305. array.forEach(function(v) {
  5306. delete v._tmpIndex_;
  5307. });
  5308. }
  5309. function findMaxPadding(boxes) {
  5310. var top = 0;
  5311. var left = 0;
  5312. var bottom = 0;
  5313. var right = 0;
  5314. helpers$1.each(boxes, function(box) {
  5315. if (box.getPadding) {
  5316. var boxPadding = box.getPadding();
  5317. top = Math.max(top, boxPadding.top);
  5318. left = Math.max(left, boxPadding.left);
  5319. bottom = Math.max(bottom, boxPadding.bottom);
  5320. right = Math.max(right, boxPadding.right);
  5321. }
  5322. });
  5323. return {
  5324. top: top,
  5325. left: left,
  5326. bottom: bottom,
  5327. right: right
  5328. };
  5329. }
  5330. function addSizeByPosition(boxes, size) {
  5331. helpers$1.each(boxes, function(box) {
  5332. size[box.position] += box.isHorizontal() ? box.height : box.width;
  5333. });
  5334. }
  5335. core_defaults._set('global', {
  5336. layout: {
  5337. padding: {
  5338. top: 0,
  5339. right: 0,
  5340. bottom: 0,
  5341. left: 0
  5342. }
  5343. }
  5344. });
  5345. /**
  5346. * @interface ILayoutItem
  5347. * @prop {string} position - The position of the item in the chart layout. Possible values are
  5348. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  5349. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  5350. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  5351. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  5352. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  5353. * @prop {function} getPadding - Returns an object with padding on the edges
  5354. * @prop {number} width - Width of item. Must be valid after update()
  5355. * @prop {number} height - Height of item. Must be valid after update()
  5356. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  5357. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  5358. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  5359. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  5360. */
  5361. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  5362. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  5363. // It is this service's responsibility of carrying out that layout.
  5364. var core_layouts = {
  5365. defaults: {},
  5366. /**
  5367. * Register a box to a chart.
  5368. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  5369. * @param {Chart} chart - the chart to use
  5370. * @param {ILayoutItem} item - the item to add to be layed out
  5371. */
  5372. addBox: function(chart, item) {
  5373. if (!chart.boxes) {
  5374. chart.boxes = [];
  5375. }
  5376. // initialize item with default values
  5377. item.fullWidth = item.fullWidth || false;
  5378. item.position = item.position || 'top';
  5379. item.weight = item.weight || 0;
  5380. chart.boxes.push(item);
  5381. },
  5382. /**
  5383. * Remove a layoutItem from a chart
  5384. * @param {Chart} chart - the chart to remove the box from
  5385. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  5386. */
  5387. removeBox: function(chart, layoutItem) {
  5388. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  5389. if (index !== -1) {
  5390. chart.boxes.splice(index, 1);
  5391. }
  5392. },
  5393. /**
  5394. * Sets (or updates) options on the given `item`.
  5395. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  5396. * @param {ILayoutItem} item - the item to configure with the given options
  5397. * @param {object} options - the new item options.
  5398. */
  5399. configure: function(chart, item, options) {
  5400. var props = ['fullWidth', 'position', 'weight'];
  5401. var ilen = props.length;
  5402. var i = 0;
  5403. var prop;
  5404. for (; i < ilen; ++i) {
  5405. prop = props[i];
  5406. if (options.hasOwnProperty(prop)) {
  5407. item[prop] = options[prop];
  5408. }
  5409. }
  5410. },
  5411. /**
  5412. * Fits boxes of the given chart into the given size by having each box measure itself
  5413. * then running a fitting algorithm
  5414. * @param {Chart} chart - the chart
  5415. * @param {number} width - the width to fit into
  5416. * @param {number} height - the height to fit into
  5417. */
  5418. update: function(chart, width, height) {
  5419. if (!chart) {
  5420. return;
  5421. }
  5422. var layoutOptions = chart.options.layout || {};
  5423. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  5424. var leftPadding = padding.left;
  5425. var rightPadding = padding.right;
  5426. var topPadding = padding.top;
  5427. var bottomPadding = padding.bottom;
  5428. var leftBoxes = filterByPosition(chart.boxes, 'left');
  5429. var rightBoxes = filterByPosition(chart.boxes, 'right');
  5430. var topBoxes = filterByPosition(chart.boxes, 'top');
  5431. var bottomBoxes = filterByPosition(chart.boxes, 'bottom');
  5432. var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');
  5433. // Sort boxes by weight. A higher weight is further away from the chart area
  5434. sortByWeight(leftBoxes, true);
  5435. sortByWeight(rightBoxes, false);
  5436. sortByWeight(topBoxes, true);
  5437. sortByWeight(bottomBoxes, false);
  5438. var verticalBoxes = leftBoxes.concat(rightBoxes);
  5439. var horizontalBoxes = topBoxes.concat(bottomBoxes);
  5440. var outerBoxes = verticalBoxes.concat(horizontalBoxes);
  5441. // Essentially we now have any number of boxes on each of the 4 sides.
  5442. // Our canvas looks like the following.
  5443. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  5444. // B1 is the bottom axis
  5445. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  5446. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  5447. // an error will be thrown.
  5448. //
  5449. // |----------------------------------------------------|
  5450. // | T1 (Full Width) |
  5451. // |----------------------------------------------------|
  5452. // | | | T2 | |
  5453. // | |----|-------------------------------------|----|
  5454. // | | | C1 | | C2 | |
  5455. // | | |----| |----| |
  5456. // | | | | |
  5457. // | L1 | L2 | ChartArea (C0) | R1 |
  5458. // | | | | |
  5459. // | | |----| |----| |
  5460. // | | | C3 | | C4 | |
  5461. // | |----|-------------------------------------|----|
  5462. // | | | B1 | |
  5463. // |----------------------------------------------------|
  5464. // | B2 (Full Width) |
  5465. // |----------------------------------------------------|
  5466. //
  5467. // What we do to find the best sizing, we do the following
  5468. // 1. Determine the minimum size of the chart area.
  5469. // 2. Split the remaining width equally between each vertical axis
  5470. // 3. Split the remaining height equally between each horizontal axis
  5471. // 4. Give each layout the maximum size it can be. The layout will return it's minimum size
  5472. // 5. Adjust the sizes of each axis based on it's minimum reported size.
  5473. // 6. Refit each axis
  5474. // 7. Position each axis in the final location
  5475. // 8. Tell the chart the final location of the chart area
  5476. // 9. Tell any axes that overlay the chart area the positions of the chart area
  5477. // Step 1
  5478. var chartWidth = width - leftPadding - rightPadding;
  5479. var chartHeight = height - topPadding - bottomPadding;
  5480. var chartAreaWidth = chartWidth / 2; // min 50%
  5481. // Step 2
  5482. var verticalBoxWidth = (width - chartAreaWidth) / verticalBoxes.length;
  5483. // Step 3
  5484. // TODO re-limit horizontal axis height (this limit has affected only padding calculation since PR 1837)
  5485. // var horizontalBoxHeight = (height - chartAreaHeight) / horizontalBoxes.length;
  5486. // Step 4
  5487. var maxChartAreaWidth = chartWidth;
  5488. var maxChartAreaHeight = chartHeight;
  5489. var outerBoxSizes = {top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding};
  5490. var minBoxSizes = [];
  5491. var maxPadding;
  5492. function getMinimumBoxSize(box) {
  5493. var minSize;
  5494. var isHorizontal = box.isHorizontal();
  5495. if (isHorizontal) {
  5496. minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2);
  5497. maxChartAreaHeight -= minSize.height;
  5498. } else {
  5499. minSize = box.update(verticalBoxWidth, maxChartAreaHeight);
  5500. maxChartAreaWidth -= minSize.width;
  5501. }
  5502. minBoxSizes.push({
  5503. horizontal: isHorizontal,
  5504. width: minSize.width,
  5505. box: box,
  5506. });
  5507. }
  5508. helpers$1.each(outerBoxes, getMinimumBoxSize);
  5509. // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
  5510. maxPadding = findMaxPadding(outerBoxes);
  5511. // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
  5512. // be if the axes are drawn at their minimum sizes.
  5513. // Steps 5 & 6
  5514. // Function to fit a box
  5515. function fitBox(box) {
  5516. var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minBox) {
  5517. return minBox.box === box;
  5518. });
  5519. if (minBoxSize) {
  5520. if (minBoxSize.horizontal) {
  5521. var scaleMargin = {
  5522. left: Math.max(outerBoxSizes.left, maxPadding.left),
  5523. right: Math.max(outerBoxSizes.right, maxPadding.right),
  5524. top: 0,
  5525. bottom: 0
  5526. };
  5527. // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
  5528. // on the margin. Sometimes they need to increase in size slightly
  5529. box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
  5530. } else {
  5531. box.update(minBoxSize.width, maxChartAreaHeight);
  5532. }
  5533. }
  5534. }
  5535. // Update, and calculate the left and right margins for the horizontal boxes
  5536. helpers$1.each(verticalBoxes, fitBox);
  5537. addSizeByPosition(verticalBoxes, outerBoxSizes);
  5538. // Set the Left and Right margins for the horizontal boxes
  5539. helpers$1.each(horizontalBoxes, fitBox);
  5540. addSizeByPosition(horizontalBoxes, outerBoxSizes);
  5541. function finalFitVerticalBox(box) {
  5542. var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minSize) {
  5543. return minSize.box === box;
  5544. });
  5545. var scaleMargin = {
  5546. left: 0,
  5547. right: 0,
  5548. top: outerBoxSizes.top,
  5549. bottom: outerBoxSizes.bottom
  5550. };
  5551. if (minBoxSize) {
  5552. box.update(minBoxSize.width, maxChartAreaHeight, scaleMargin);
  5553. }
  5554. }
  5555. // Let the left layout know the final margin
  5556. helpers$1.each(verticalBoxes, finalFitVerticalBox);
  5557. // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
  5558. outerBoxSizes = {top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding};
  5559. addSizeByPosition(outerBoxes, outerBoxSizes);
  5560. // We may be adding some padding to account for rotated x axis labels
  5561. var leftPaddingAddition = Math.max(maxPadding.left - outerBoxSizes.left, 0);
  5562. outerBoxSizes.left += leftPaddingAddition;
  5563. outerBoxSizes.right += Math.max(maxPadding.right - outerBoxSizes.right, 0);
  5564. var topPaddingAddition = Math.max(maxPadding.top - outerBoxSizes.top, 0);
  5565. outerBoxSizes.top += topPaddingAddition;
  5566. outerBoxSizes.bottom += Math.max(maxPadding.bottom - outerBoxSizes.bottom, 0);
  5567. // Figure out if our chart area changed. This would occur if the dataset layout label rotation
  5568. // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
  5569. // without calling `fit` again
  5570. var newMaxChartAreaHeight = height - outerBoxSizes.top - outerBoxSizes.bottom;
  5571. var newMaxChartAreaWidth = width - outerBoxSizes.left - outerBoxSizes.right;
  5572. if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
  5573. helpers$1.each(verticalBoxes, function(box) {
  5574. box.height = newMaxChartAreaHeight;
  5575. });
  5576. helpers$1.each(horizontalBoxes, function(box) {
  5577. if (!box.fullWidth) {
  5578. box.width = newMaxChartAreaWidth;
  5579. }
  5580. });
  5581. maxChartAreaHeight = newMaxChartAreaHeight;
  5582. maxChartAreaWidth = newMaxChartAreaWidth;
  5583. }
  5584. // Step 7 - Position the boxes
  5585. var left = leftPadding + leftPaddingAddition;
  5586. var top = topPadding + topPaddingAddition;
  5587. function placeBox(box) {
  5588. if (box.isHorizontal()) {
  5589. box.left = box.fullWidth ? leftPadding : outerBoxSizes.left;
  5590. box.right = box.fullWidth ? width - rightPadding : outerBoxSizes.left + maxChartAreaWidth;
  5591. box.top = top;
  5592. box.bottom = top + box.height;
  5593. // Move to next point
  5594. top = box.bottom;
  5595. } else {
  5596. box.left = left;
  5597. box.right = left + box.width;
  5598. box.top = outerBoxSizes.top;
  5599. box.bottom = outerBoxSizes.top + maxChartAreaHeight;
  5600. // Move to next point
  5601. left = box.right;
  5602. }
  5603. }
  5604. helpers$1.each(leftBoxes.concat(topBoxes), placeBox);
  5605. // Account for chart width and height
  5606. left += maxChartAreaWidth;
  5607. top += maxChartAreaHeight;
  5608. helpers$1.each(rightBoxes, placeBox);
  5609. helpers$1.each(bottomBoxes, placeBox);
  5610. // Step 8
  5611. chart.chartArea = {
  5612. left: outerBoxSizes.left,
  5613. top: outerBoxSizes.top,
  5614. right: outerBoxSizes.left + maxChartAreaWidth,
  5615. bottom: outerBoxSizes.top + maxChartAreaHeight
  5616. };
  5617. // Step 9
  5618. helpers$1.each(chartAreaBoxes, function(box) {
  5619. box.left = chart.chartArea.left;
  5620. box.top = chart.chartArea.top;
  5621. box.right = chart.chartArea.right;
  5622. box.bottom = chart.chartArea.bottom;
  5623. box.update(maxChartAreaWidth, maxChartAreaHeight);
  5624. });
  5625. }
  5626. };
  5627. /**
  5628. * Platform fallback implementation (minimal).
  5629. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  5630. */
  5631. var platform_basic = {
  5632. acquireContext: function(item) {
  5633. if (item && item.canvas) {
  5634. // Support for any object associated to a canvas (including a context2d)
  5635. item = item.canvas;
  5636. }
  5637. return item && item.getContext('2d') || null;
  5638. }
  5639. };
  5640. 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";
  5641. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  5642. default: platform_dom
  5643. });
  5644. function getCjsExportFromNamespace (n) {
  5645. return n && n.default || n;
  5646. }
  5647. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  5648. var EXPANDO_KEY = '$chartjs';
  5649. var CSS_PREFIX = 'chartjs-';
  5650. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  5651. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  5652. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  5653. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  5654. /**
  5655. * DOM event types -> Chart.js event types.
  5656. * Note: only events with different types are mapped.
  5657. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  5658. */
  5659. var EVENT_TYPES = {
  5660. touchstart: 'mousedown',
  5661. touchmove: 'mousemove',
  5662. touchend: 'mouseup',
  5663. pointerenter: 'mouseenter',
  5664. pointerdown: 'mousedown',
  5665. pointermove: 'mousemove',
  5666. pointerup: 'mouseup',
  5667. pointerleave: 'mouseout',
  5668. pointerout: 'mouseout'
  5669. };
  5670. /**
  5671. * The "used" size is the final value of a dimension property after all calculations have
  5672. * been performed. This method uses the computed style of `element` but returns undefined
  5673. * if the computed style is not expressed in pixels. That can happen in some cases where
  5674. * `element` has a size relative to its parent and this last one is not yet displayed,
  5675. * for example because of `display: none` on a parent node.
  5676. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  5677. * @returns {number} Size in pixels or undefined if unknown.
  5678. */
  5679. function readUsedSize(element, property) {
  5680. var value = helpers$1.getStyle(element, property);
  5681. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  5682. return matches ? Number(matches[1]) : undefined;
  5683. }
  5684. /**
  5685. * Initializes the canvas style and render size without modifying the canvas display size,
  5686. * since responsiveness is handled by the controller.resize() method. The config is used
  5687. * to determine the aspect ratio to apply in case no explicit height has been specified.
  5688. */
  5689. function initCanvas(canvas, config) {
  5690. var style = canvas.style;
  5691. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  5692. // returns null or '' if no explicit value has been set to the canvas attribute.
  5693. var renderHeight = canvas.getAttribute('height');
  5694. var renderWidth = canvas.getAttribute('width');
  5695. // Chart.js modifies some canvas values that we want to restore on destroy
  5696. canvas[EXPANDO_KEY] = {
  5697. initial: {
  5698. height: renderHeight,
  5699. width: renderWidth,
  5700. style: {
  5701. display: style.display,
  5702. height: style.height,
  5703. width: style.width
  5704. }
  5705. }
  5706. };
  5707. // Force canvas to display as block to avoid extra space caused by inline
  5708. // elements, which would interfere with the responsive resize process.
  5709. // https://github.com/chartjs/Chart.js/issues/2538
  5710. style.display = style.display || 'block';
  5711. if (renderWidth === null || renderWidth === '') {
  5712. var displayWidth = readUsedSize(canvas, 'width');
  5713. if (displayWidth !== undefined) {
  5714. canvas.width = displayWidth;
  5715. }
  5716. }
  5717. if (renderHeight === null || renderHeight === '') {
  5718. if (canvas.style.height === '') {
  5719. // If no explicit render height and style height, let's apply the aspect ratio,
  5720. // which one can be specified by the user but also by charts as default option
  5721. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  5722. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  5723. } else {
  5724. var displayHeight = readUsedSize(canvas, 'height');
  5725. if (displayWidth !== undefined) {
  5726. canvas.height = displayHeight;
  5727. }
  5728. }
  5729. }
  5730. return canvas;
  5731. }
  5732. /**
  5733. * Detects support for options object argument in addEventListener.
  5734. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  5735. * @private
  5736. */
  5737. var supportsEventListenerOptions = (function() {
  5738. var supports = false;
  5739. try {
  5740. var options = Object.defineProperty({}, 'passive', {
  5741. // eslint-disable-next-line getter-return
  5742. get: function() {
  5743. supports = true;
  5744. }
  5745. });
  5746. window.addEventListener('e', null, options);
  5747. } catch (e) {
  5748. // continue regardless of error
  5749. }
  5750. return supports;
  5751. }());
  5752. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  5753. // https://github.com/chartjs/Chart.js/issues/4287
  5754. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  5755. function addListener(node, type, listener) {
  5756. node.addEventListener(type, listener, eventListenerOptions);
  5757. }
  5758. function removeListener(node, type, listener) {
  5759. node.removeEventListener(type, listener, eventListenerOptions);
  5760. }
  5761. function createEvent(type, chart, x, y, nativeEvent) {
  5762. return {
  5763. type: type,
  5764. chart: chart,
  5765. native: nativeEvent || null,
  5766. x: x !== undefined ? x : null,
  5767. y: y !== undefined ? y : null,
  5768. };
  5769. }
  5770. function fromNativeEvent(event, chart) {
  5771. var type = EVENT_TYPES[event.type] || event.type;
  5772. var pos = helpers$1.getRelativePosition(event, chart);
  5773. return createEvent(type, chart, pos.x, pos.y, event);
  5774. }
  5775. function throttled(fn, thisArg) {
  5776. var ticking = false;
  5777. var args = [];
  5778. return function() {
  5779. args = Array.prototype.slice.call(arguments);
  5780. thisArg = thisArg || this;
  5781. if (!ticking) {
  5782. ticking = true;
  5783. helpers$1.requestAnimFrame.call(window, function() {
  5784. ticking = false;
  5785. fn.apply(thisArg, args);
  5786. });
  5787. }
  5788. };
  5789. }
  5790. function createDiv(cls) {
  5791. var el = document.createElement('div');
  5792. el.className = cls || '';
  5793. return el;
  5794. }
  5795. // Implementation based on https://github.com/marcj/css-element-queries
  5796. function createResizer(handler) {
  5797. var maxSize = 1000000;
  5798. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  5799. // https://github.com/chartjs/Chart.js/issues/5902
  5800. var resizer = createDiv(CSS_SIZE_MONITOR);
  5801. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  5802. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  5803. expand.appendChild(createDiv());
  5804. shrink.appendChild(createDiv());
  5805. resizer.appendChild(expand);
  5806. resizer.appendChild(shrink);
  5807. resizer._reset = function() {
  5808. expand.scrollLeft = maxSize;
  5809. expand.scrollTop = maxSize;
  5810. shrink.scrollLeft = maxSize;
  5811. shrink.scrollTop = maxSize;
  5812. };
  5813. var onScroll = function() {
  5814. resizer._reset();
  5815. handler();
  5816. };
  5817. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  5818. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  5819. return resizer;
  5820. }
  5821. // https://davidwalsh.name/detect-node-insertion
  5822. function watchForRender(node, handler) {
  5823. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  5824. var proxy = expando.renderProxy = function(e) {
  5825. if (e.animationName === CSS_RENDER_ANIMATION) {
  5826. handler();
  5827. }
  5828. };
  5829. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  5830. addListener(node, type, proxy);
  5831. });
  5832. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  5833. // is removed then added back immediately (same animation frame?). Accessing the
  5834. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  5835. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  5836. // https://github.com/chartjs/Chart.js/issues/4737
  5837. expando.reflow = !!node.offsetParent;
  5838. node.classList.add(CSS_RENDER_MONITOR);
  5839. }
  5840. function unwatchForRender(node) {
  5841. var expando = node[EXPANDO_KEY] || {};
  5842. var proxy = expando.renderProxy;
  5843. if (proxy) {
  5844. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  5845. removeListener(node, type, proxy);
  5846. });
  5847. delete expando.renderProxy;
  5848. }
  5849. node.classList.remove(CSS_RENDER_MONITOR);
  5850. }
  5851. function addResizeListener(node, listener, chart) {
  5852. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  5853. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  5854. var resizer = expando.resizer = createResizer(throttled(function() {
  5855. if (expando.resizer) {
  5856. var container = chart.options.maintainAspectRatio && node.parentNode;
  5857. var w = container ? container.clientWidth : 0;
  5858. listener(createEvent('resize', chart));
  5859. if (container && container.clientWidth < w && chart.canvas) {
  5860. // If the container size shrank during chart resize, let's assume
  5861. // scrollbar appeared. So we resize again with the scrollbar visible -
  5862. // effectively making chart smaller and the scrollbar hidden again.
  5863. // Because we are inside `throttled`, and currently `ticking`, scroll
  5864. // events are ignored during this whole 2 resize process.
  5865. // If we assumed wrong and something else happened, we are resizing
  5866. // twice in a frame (potential performance issue)
  5867. listener(createEvent('resize', chart));
  5868. }
  5869. }
  5870. }));
  5871. // The resizer needs to be attached to the node parent, so we first need to be
  5872. // sure that `node` is attached to the DOM before injecting the resizer element.
  5873. watchForRender(node, function() {
  5874. if (expando.resizer) {
  5875. var container = node.parentNode;
  5876. if (container && container !== resizer.parentNode) {
  5877. container.insertBefore(resizer, container.firstChild);
  5878. }
  5879. // The container size might have changed, let's reset the resizer state.
  5880. resizer._reset();
  5881. }
  5882. });
  5883. }
  5884. function removeResizeListener(node) {
  5885. var expando = node[EXPANDO_KEY] || {};
  5886. var resizer = expando.resizer;
  5887. delete expando.resizer;
  5888. unwatchForRender(node);
  5889. if (resizer && resizer.parentNode) {
  5890. resizer.parentNode.removeChild(resizer);
  5891. }
  5892. }
  5893. function injectCSS(platform, css) {
  5894. // https://stackoverflow.com/q/3922139
  5895. var style = platform._style || document.createElement('style');
  5896. if (!platform._style) {
  5897. platform._style = style;
  5898. css = '/* Chart.js */\n' + css;
  5899. style.setAttribute('type', 'text/css');
  5900. document.getElementsByTagName('head')[0].appendChild(style);
  5901. }
  5902. style.appendChild(document.createTextNode(css));
  5903. }
  5904. var platform_dom$2 = {
  5905. /**
  5906. * When `true`, prevents the automatic injection of the stylesheet required to
  5907. * correctly detect when the chart is added to the DOM and then resized. This
  5908. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  5909. * to be manually imported to make this library compatible with any CSP.
  5910. * See https://github.com/chartjs/Chart.js/issues/5208
  5911. */
  5912. disableCSSInjection: false,
  5913. /**
  5914. * This property holds whether this platform is enabled for the current environment.
  5915. * Currently used by platform.js to select the proper implementation.
  5916. * @private
  5917. */
  5918. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  5919. /**
  5920. * @private
  5921. */
  5922. _ensureLoaded: function() {
  5923. if (this._loaded) {
  5924. return;
  5925. }
  5926. this._loaded = true;
  5927. // https://github.com/chartjs/Chart.js/issues/5208
  5928. if (!this.disableCSSInjection) {
  5929. injectCSS(this, stylesheet);
  5930. }
  5931. },
  5932. acquireContext: function(item, config) {
  5933. if (typeof item === 'string') {
  5934. item = document.getElementById(item);
  5935. } else if (item.length) {
  5936. // Support for array based queries (such as jQuery)
  5937. item = item[0];
  5938. }
  5939. if (item && item.canvas) {
  5940. // Support for any object associated to a canvas (including a context2d)
  5941. item = item.canvas;
  5942. }
  5943. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  5944. // method, for example: https://github.com/kkapsner/CanvasBlocker
  5945. // https://github.com/chartjs/Chart.js/issues/2807
  5946. var context = item && item.getContext && item.getContext('2d');
  5947. // Load platform resources on first chart creation, to make possible to change
  5948. // platform options after importing the library (e.g. `disableCSSInjection`).
  5949. this._ensureLoaded();
  5950. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  5951. // inside an iframe or when running in a protected environment. We could guess the
  5952. // types from their toString() value but let's keep things flexible and assume it's
  5953. // a sufficient condition if the item has a context2D which has item as `canvas`.
  5954. // https://github.com/chartjs/Chart.js/issues/3887
  5955. // https://github.com/chartjs/Chart.js/issues/4102
  5956. // https://github.com/chartjs/Chart.js/issues/4152
  5957. if (context && context.canvas === item) {
  5958. initCanvas(item, config);
  5959. return context;
  5960. }
  5961. return null;
  5962. },
  5963. releaseContext: function(context) {
  5964. var canvas = context.canvas;
  5965. if (!canvas[EXPANDO_KEY]) {
  5966. return;
  5967. }
  5968. var initial = canvas[EXPANDO_KEY].initial;
  5969. ['height', 'width'].forEach(function(prop) {
  5970. var value = initial[prop];
  5971. if (helpers$1.isNullOrUndef(value)) {
  5972. canvas.removeAttribute(prop);
  5973. } else {
  5974. canvas.setAttribute(prop, value);
  5975. }
  5976. });
  5977. helpers$1.each(initial.style || {}, function(value, key) {
  5978. canvas.style[key] = value;
  5979. });
  5980. // The canvas render size might have been changed (and thus the state stack discarded),
  5981. // we can't use save() and restore() to restore the initial state. So make sure that at
  5982. // least the canvas context is reset to the default state by setting the canvas width.
  5983. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  5984. // eslint-disable-next-line no-self-assign
  5985. canvas.width = canvas.width;
  5986. delete canvas[EXPANDO_KEY];
  5987. },
  5988. addEventListener: function(chart, type, listener) {
  5989. var canvas = chart.canvas;
  5990. if (type === 'resize') {
  5991. // Note: the resize event is not supported on all browsers.
  5992. addResizeListener(canvas, listener, chart);
  5993. return;
  5994. }
  5995. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  5996. var proxies = expando.proxies || (expando.proxies = {});
  5997. var proxy = proxies[chart.id + '_' + type] = function(event) {
  5998. listener(fromNativeEvent(event, chart));
  5999. };
  6000. addListener(canvas, type, proxy);
  6001. },
  6002. removeEventListener: function(chart, type, listener) {
  6003. var canvas = chart.canvas;
  6004. if (type === 'resize') {
  6005. // Note: the resize event is not supported on all browsers.
  6006. removeResizeListener(canvas);
  6007. return;
  6008. }
  6009. var expando = listener[EXPANDO_KEY] || {};
  6010. var proxies = expando.proxies || {};
  6011. var proxy = proxies[chart.id + '_' + type];
  6012. if (!proxy) {
  6013. return;
  6014. }
  6015. removeListener(canvas, type, proxy);
  6016. }
  6017. };
  6018. // DEPRECATIONS
  6019. /**
  6020. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6021. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6022. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6023. * @function Chart.helpers.addEvent
  6024. * @deprecated since version 2.7.0
  6025. * @todo remove at version 3
  6026. * @private
  6027. */
  6028. helpers$1.addEvent = addListener;
  6029. /**
  6030. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6031. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6032. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6033. * @function Chart.helpers.removeEvent
  6034. * @deprecated since version 2.7.0
  6035. * @todo remove at version 3
  6036. * @private
  6037. */
  6038. helpers$1.removeEvent = removeListener;
  6039. // @TODO Make possible to select another platform at build time.
  6040. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6041. /**
  6042. * @namespace Chart.platform
  6043. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6044. * @since 2.4.0
  6045. */
  6046. var platform = helpers$1.extend({
  6047. /**
  6048. * @since 2.7.0
  6049. */
  6050. initialize: function() {},
  6051. /**
  6052. * Called at chart construction time, returns a context2d instance implementing
  6053. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6054. * @param {*} item - The native item from which to acquire context (platform specific)
  6055. * @param {object} options - The chart options
  6056. * @returns {CanvasRenderingContext2D} context2d instance
  6057. */
  6058. acquireContext: function() {},
  6059. /**
  6060. * Called at chart destruction time, releases any resources associated to the context
  6061. * previously returned by the acquireContext() method.
  6062. * @param {CanvasRenderingContext2D} context - The context2d instance
  6063. * @returns {boolean} true if the method succeeded, else false
  6064. */
  6065. releaseContext: function() {},
  6066. /**
  6067. * Registers the specified listener on the given chart.
  6068. * @param {Chart} chart - Chart from which to listen for event
  6069. * @param {string} type - The ({@link IEvent}) type to listen for
  6070. * @param {function} listener - Receives a notification (an object that implements
  6071. * the {@link IEvent} interface) when an event of the specified type occurs.
  6072. */
  6073. addEventListener: function() {},
  6074. /**
  6075. * Removes the specified listener previously registered with addEventListener.
  6076. * @param {Chart} chart - Chart from which to remove the listener
  6077. * @param {string} type - The ({@link IEvent}) type to remove
  6078. * @param {function} listener - The listener function to remove from the event target.
  6079. */
  6080. removeEventListener: function() {}
  6081. }, implementation);
  6082. core_defaults._set('global', {
  6083. plugins: {}
  6084. });
  6085. /**
  6086. * The plugin service singleton
  6087. * @namespace Chart.plugins
  6088. * @since 2.1.0
  6089. */
  6090. var core_plugins = {
  6091. /**
  6092. * Globally registered plugins.
  6093. * @private
  6094. */
  6095. _plugins: [],
  6096. /**
  6097. * This identifier is used to invalidate the descriptors cache attached to each chart
  6098. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6099. * incremented and descriptors are regenerated during following API calls.
  6100. * @private
  6101. */
  6102. _cacheId: 0,
  6103. /**
  6104. * Registers the given plugin(s) if not already registered.
  6105. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6106. */
  6107. register: function(plugins) {
  6108. var p = this._plugins;
  6109. ([]).concat(plugins).forEach(function(plugin) {
  6110. if (p.indexOf(plugin) === -1) {
  6111. p.push(plugin);
  6112. }
  6113. });
  6114. this._cacheId++;
  6115. },
  6116. /**
  6117. * Unregisters the given plugin(s) only if registered.
  6118. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6119. */
  6120. unregister: function(plugins) {
  6121. var p = this._plugins;
  6122. ([]).concat(plugins).forEach(function(plugin) {
  6123. var idx = p.indexOf(plugin);
  6124. if (idx !== -1) {
  6125. p.splice(idx, 1);
  6126. }
  6127. });
  6128. this._cacheId++;
  6129. },
  6130. /**
  6131. * Remove all registered plugins.
  6132. * @since 2.1.5
  6133. */
  6134. clear: function() {
  6135. this._plugins = [];
  6136. this._cacheId++;
  6137. },
  6138. /**
  6139. * Returns the number of registered plugins?
  6140. * @returns {number}
  6141. * @since 2.1.5
  6142. */
  6143. count: function() {
  6144. return this._plugins.length;
  6145. },
  6146. /**
  6147. * Returns all registered plugin instances.
  6148. * @returns {IPlugin[]} array of plugin objects.
  6149. * @since 2.1.5
  6150. */
  6151. getAll: function() {
  6152. return this._plugins;
  6153. },
  6154. /**
  6155. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6156. * This method immediately returns as soon as a plugin explicitly returns false. The
  6157. * returned value can be used, for instance, to interrupt the current action.
  6158. * @param {Chart} chart - The chart instance for which plugins should be called.
  6159. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6160. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6161. * @returns {boolean} false if any of the plugins return false, else returns true.
  6162. */
  6163. notify: function(chart, hook, args) {
  6164. var descriptors = this.descriptors(chart);
  6165. var ilen = descriptors.length;
  6166. var i, descriptor, plugin, params, method;
  6167. for (i = 0; i < ilen; ++i) {
  6168. descriptor = descriptors[i];
  6169. plugin = descriptor.plugin;
  6170. method = plugin[hook];
  6171. if (typeof method === 'function') {
  6172. params = [chart].concat(args || []);
  6173. params.push(descriptor.options);
  6174. if (method.apply(plugin, params) === false) {
  6175. return false;
  6176. }
  6177. }
  6178. }
  6179. return true;
  6180. },
  6181. /**
  6182. * Returns descriptors of enabled plugins for the given chart.
  6183. * @returns {object[]} [{ plugin, options }]
  6184. * @private
  6185. */
  6186. descriptors: function(chart) {
  6187. var cache = chart.$plugins || (chart.$plugins = {});
  6188. if (cache.id === this._cacheId) {
  6189. return cache.descriptors;
  6190. }
  6191. var plugins = [];
  6192. var descriptors = [];
  6193. var config = (chart && chart.config) || {};
  6194. var options = (config.options && config.options.plugins) || {};
  6195. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  6196. var idx = plugins.indexOf(plugin);
  6197. if (idx !== -1) {
  6198. return;
  6199. }
  6200. var id = plugin.id;
  6201. var opts = options[id];
  6202. if (opts === false) {
  6203. return;
  6204. }
  6205. if (opts === true) {
  6206. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6207. }
  6208. plugins.push(plugin);
  6209. descriptors.push({
  6210. plugin: plugin,
  6211. options: opts || {}
  6212. });
  6213. });
  6214. cache.descriptors = descriptors;
  6215. cache.id = this._cacheId;
  6216. return descriptors;
  6217. },
  6218. /**
  6219. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  6220. * but in some cases, this reference can be changed by the user when updating options.
  6221. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  6222. * @private
  6223. */
  6224. _invalidate: function(chart) {
  6225. delete chart.$plugins;
  6226. }
  6227. };
  6228. var core_scaleService = {
  6229. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  6230. // use the new chart options to grab the correct scale
  6231. constructors: {},
  6232. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  6233. // old browsers
  6234. // Scale config defaults
  6235. defaults: {},
  6236. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  6237. this.constructors[type] = scaleConstructor;
  6238. this.defaults[type] = helpers$1.clone(scaleDefaults);
  6239. },
  6240. getScaleConstructor: function(type) {
  6241. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  6242. },
  6243. getScaleDefaults: function(type) {
  6244. // Return the scale defaults merged with the global settings so that we always use the latest ones
  6245. return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {};
  6246. },
  6247. updateScaleDefaults: function(type, additions) {
  6248. var me = this;
  6249. if (me.defaults.hasOwnProperty(type)) {
  6250. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  6251. }
  6252. },
  6253. addScalesToLayout: function(chart) {
  6254. // Adds each scale to the chart.boxes array to be sized accordingly
  6255. helpers$1.each(chart.scales, function(scale) {
  6256. // Set ILayoutItem parameters for backwards compatibility
  6257. scale.fullWidth = scale.options.fullWidth;
  6258. scale.position = scale.options.position;
  6259. scale.weight = scale.options.weight;
  6260. core_layouts.addBox(chart, scale);
  6261. });
  6262. }
  6263. };
  6264. var valueOrDefault$7 = helpers$1.valueOrDefault;
  6265. core_defaults._set('global', {
  6266. tooltips: {
  6267. enabled: true,
  6268. custom: null,
  6269. mode: 'nearest',
  6270. position: 'average',
  6271. intersect: true,
  6272. backgroundColor: 'rgba(0,0,0,0.8)',
  6273. titleFontStyle: 'bold',
  6274. titleSpacing: 2,
  6275. titleMarginBottom: 6,
  6276. titleFontColor: '#fff',
  6277. titleAlign: 'left',
  6278. bodySpacing: 2,
  6279. bodyFontColor: '#fff',
  6280. bodyAlign: 'left',
  6281. footerFontStyle: 'bold',
  6282. footerSpacing: 2,
  6283. footerMarginTop: 6,
  6284. footerFontColor: '#fff',
  6285. footerAlign: 'left',
  6286. yPadding: 6,
  6287. xPadding: 6,
  6288. caretPadding: 2,
  6289. caretSize: 5,
  6290. cornerRadius: 6,
  6291. multiKeyBackground: '#fff',
  6292. displayColors: true,
  6293. borderColor: 'rgba(0,0,0,0)',
  6294. borderWidth: 0,
  6295. callbacks: {
  6296. // Args are: (tooltipItems, data)
  6297. beforeTitle: helpers$1.noop,
  6298. title: function(tooltipItems, data) {
  6299. var title = '';
  6300. var labels = data.labels;
  6301. var labelCount = labels ? labels.length : 0;
  6302. if (tooltipItems.length > 0) {
  6303. var item = tooltipItems[0];
  6304. if (item.label) {
  6305. title = item.label;
  6306. } else if (item.xLabel) {
  6307. title = item.xLabel;
  6308. } else if (labelCount > 0 && item.index < labelCount) {
  6309. title = labels[item.index];
  6310. }
  6311. }
  6312. return title;
  6313. },
  6314. afterTitle: helpers$1.noop,
  6315. // Args are: (tooltipItems, data)
  6316. beforeBody: helpers$1.noop,
  6317. // Args are: (tooltipItem, data)
  6318. beforeLabel: helpers$1.noop,
  6319. label: function(tooltipItem, data) {
  6320. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  6321. if (label) {
  6322. label += ': ';
  6323. }
  6324. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  6325. label += tooltipItem.value;
  6326. } else {
  6327. label += tooltipItem.yLabel;
  6328. }
  6329. return label;
  6330. },
  6331. labelColor: function(tooltipItem, chart) {
  6332. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  6333. var activeElement = meta.data[tooltipItem.index];
  6334. var view = activeElement._view;
  6335. return {
  6336. borderColor: view.borderColor,
  6337. backgroundColor: view.backgroundColor
  6338. };
  6339. },
  6340. labelTextColor: function() {
  6341. return this._options.bodyFontColor;
  6342. },
  6343. afterLabel: helpers$1.noop,
  6344. // Args are: (tooltipItems, data)
  6345. afterBody: helpers$1.noop,
  6346. // Args are: (tooltipItems, data)
  6347. beforeFooter: helpers$1.noop,
  6348. footer: helpers$1.noop,
  6349. afterFooter: helpers$1.noop
  6350. }
  6351. }
  6352. });
  6353. var positioners = {
  6354. /**
  6355. * Average mode places the tooltip at the average position of the elements shown
  6356. * @function Chart.Tooltip.positioners.average
  6357. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  6358. * @returns {object} tooltip position
  6359. */
  6360. average: function(elements) {
  6361. if (!elements.length) {
  6362. return false;
  6363. }
  6364. var i, len;
  6365. var x = 0;
  6366. var y = 0;
  6367. var count = 0;
  6368. for (i = 0, len = elements.length; i < len; ++i) {
  6369. var el = elements[i];
  6370. if (el && el.hasValue()) {
  6371. var pos = el.tooltipPosition();
  6372. x += pos.x;
  6373. y += pos.y;
  6374. ++count;
  6375. }
  6376. }
  6377. return {
  6378. x: x / count,
  6379. y: y / count
  6380. };
  6381. },
  6382. /**
  6383. * Gets the tooltip position nearest of the item nearest to the event position
  6384. * @function Chart.Tooltip.positioners.nearest
  6385. * @param elements {Chart.Element[]} the tooltip elements
  6386. * @param eventPosition {object} the position of the event in canvas coordinates
  6387. * @returns {object} the tooltip position
  6388. */
  6389. nearest: function(elements, eventPosition) {
  6390. var x = eventPosition.x;
  6391. var y = eventPosition.y;
  6392. var minDistance = Number.POSITIVE_INFINITY;
  6393. var i, len, nearestElement;
  6394. for (i = 0, len = elements.length; i < len; ++i) {
  6395. var el = elements[i];
  6396. if (el && el.hasValue()) {
  6397. var center = el.getCenterPoint();
  6398. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  6399. if (d < minDistance) {
  6400. minDistance = d;
  6401. nearestElement = el;
  6402. }
  6403. }
  6404. }
  6405. if (nearestElement) {
  6406. var tp = nearestElement.tooltipPosition();
  6407. x = tp.x;
  6408. y = tp.y;
  6409. }
  6410. return {
  6411. x: x,
  6412. y: y
  6413. };
  6414. }
  6415. };
  6416. // Helper to push or concat based on if the 2nd parameter is an array or not
  6417. function pushOrConcat(base, toPush) {
  6418. if (toPush) {
  6419. if (helpers$1.isArray(toPush)) {
  6420. // base = base.concat(toPush);
  6421. Array.prototype.push.apply(base, toPush);
  6422. } else {
  6423. base.push(toPush);
  6424. }
  6425. }
  6426. return base;
  6427. }
  6428. /**
  6429. * Returns array of strings split by newline
  6430. * @param {string} value - The value to split by newline.
  6431. * @returns {string[]} value if newline present - Returned from String split() method
  6432. * @function
  6433. */
  6434. function splitNewlines(str) {
  6435. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  6436. return str.split('\n');
  6437. }
  6438. return str;
  6439. }
  6440. /**
  6441. * Private helper to create a tooltip item model
  6442. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  6443. * @return new tooltip item
  6444. */
  6445. function createTooltipItem(element) {
  6446. var xScale = element._xScale;
  6447. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  6448. var index = element._index;
  6449. var datasetIndex = element._datasetIndex;
  6450. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  6451. var indexScale = controller._getIndexScale();
  6452. var valueScale = controller._getValueScale();
  6453. return {
  6454. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  6455. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  6456. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  6457. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  6458. index: index,
  6459. datasetIndex: datasetIndex,
  6460. x: element._model.x,
  6461. y: element._model.y
  6462. };
  6463. }
  6464. /**
  6465. * Helper to get the reset model for the tooltip
  6466. * @param tooltipOpts {object} the tooltip options
  6467. */
  6468. function getBaseModel(tooltipOpts) {
  6469. var globalDefaults = core_defaults.global;
  6470. return {
  6471. // Positioning
  6472. xPadding: tooltipOpts.xPadding,
  6473. yPadding: tooltipOpts.yPadding,
  6474. xAlign: tooltipOpts.xAlign,
  6475. yAlign: tooltipOpts.yAlign,
  6476. // Body
  6477. bodyFontColor: tooltipOpts.bodyFontColor,
  6478. _bodyFontFamily: valueOrDefault$7(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  6479. _bodyFontStyle: valueOrDefault$7(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  6480. _bodyAlign: tooltipOpts.bodyAlign,
  6481. bodyFontSize: valueOrDefault$7(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  6482. bodySpacing: tooltipOpts.bodySpacing,
  6483. // Title
  6484. titleFontColor: tooltipOpts.titleFontColor,
  6485. _titleFontFamily: valueOrDefault$7(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  6486. _titleFontStyle: valueOrDefault$7(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  6487. titleFontSize: valueOrDefault$7(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  6488. _titleAlign: tooltipOpts.titleAlign,
  6489. titleSpacing: tooltipOpts.titleSpacing,
  6490. titleMarginBottom: tooltipOpts.titleMarginBottom,
  6491. // Footer
  6492. footerFontColor: tooltipOpts.footerFontColor,
  6493. _footerFontFamily: valueOrDefault$7(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  6494. _footerFontStyle: valueOrDefault$7(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  6495. footerFontSize: valueOrDefault$7(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  6496. _footerAlign: tooltipOpts.footerAlign,
  6497. footerSpacing: tooltipOpts.footerSpacing,
  6498. footerMarginTop: tooltipOpts.footerMarginTop,
  6499. // Appearance
  6500. caretSize: tooltipOpts.caretSize,
  6501. cornerRadius: tooltipOpts.cornerRadius,
  6502. backgroundColor: tooltipOpts.backgroundColor,
  6503. opacity: 0,
  6504. legendColorBackground: tooltipOpts.multiKeyBackground,
  6505. displayColors: tooltipOpts.displayColors,
  6506. borderColor: tooltipOpts.borderColor,
  6507. borderWidth: tooltipOpts.borderWidth
  6508. };
  6509. }
  6510. /**
  6511. * Get the size of the tooltip
  6512. */
  6513. function getTooltipSize(tooltip, model) {
  6514. var ctx = tooltip._chart.ctx;
  6515. var height = model.yPadding * 2; // Tooltip Padding
  6516. var width = 0;
  6517. // Count of all lines in the body
  6518. var body = model.body;
  6519. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  6520. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  6521. }, 0);
  6522. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  6523. var titleLineCount = model.title.length;
  6524. var footerLineCount = model.footer.length;
  6525. var titleFontSize = model.titleFontSize;
  6526. var bodyFontSize = model.bodyFontSize;
  6527. var footerFontSize = model.footerFontSize;
  6528. height += titleLineCount * titleFontSize; // Title Lines
  6529. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  6530. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  6531. height += combinedBodyLength * bodyFontSize; // Body Lines
  6532. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  6533. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  6534. height += footerLineCount * (footerFontSize); // Footer Lines
  6535. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  6536. // Title width
  6537. var widthPadding = 0;
  6538. var maxLineWidth = function(line) {
  6539. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  6540. };
  6541. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  6542. helpers$1.each(model.title, maxLineWidth);
  6543. // Body width
  6544. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  6545. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  6546. // Body lines may include some extra width due to the color box
  6547. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  6548. helpers$1.each(body, function(bodyItem) {
  6549. helpers$1.each(bodyItem.before, maxLineWidth);
  6550. helpers$1.each(bodyItem.lines, maxLineWidth);
  6551. helpers$1.each(bodyItem.after, maxLineWidth);
  6552. });
  6553. // Reset back to 0
  6554. widthPadding = 0;
  6555. // Footer width
  6556. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  6557. helpers$1.each(model.footer, maxLineWidth);
  6558. // Add padding
  6559. width += 2 * model.xPadding;
  6560. return {
  6561. width: width,
  6562. height: height
  6563. };
  6564. }
  6565. /**
  6566. * Helper to get the alignment of a tooltip given the size
  6567. */
  6568. function determineAlignment(tooltip, size) {
  6569. var model = tooltip._model;
  6570. var chart = tooltip._chart;
  6571. var chartArea = tooltip._chart.chartArea;
  6572. var xAlign = 'center';
  6573. var yAlign = 'center';
  6574. if (model.y < size.height) {
  6575. yAlign = 'top';
  6576. } else if (model.y > (chart.height - size.height)) {
  6577. yAlign = 'bottom';
  6578. }
  6579. var lf, rf; // functions to determine left, right alignment
  6580. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  6581. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  6582. var midX = (chartArea.left + chartArea.right) / 2;
  6583. var midY = (chartArea.top + chartArea.bottom) / 2;
  6584. if (yAlign === 'center') {
  6585. lf = function(x) {
  6586. return x <= midX;
  6587. };
  6588. rf = function(x) {
  6589. return x > midX;
  6590. };
  6591. } else {
  6592. lf = function(x) {
  6593. return x <= (size.width / 2);
  6594. };
  6595. rf = function(x) {
  6596. return x >= (chart.width - (size.width / 2));
  6597. };
  6598. }
  6599. olf = function(x) {
  6600. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  6601. };
  6602. orf = function(x) {
  6603. return x - size.width - model.caretSize - model.caretPadding < 0;
  6604. };
  6605. yf = function(y) {
  6606. return y <= midY ? 'top' : 'bottom';
  6607. };
  6608. if (lf(model.x)) {
  6609. xAlign = 'left';
  6610. // Is tooltip too wide and goes over the right side of the chart.?
  6611. if (olf(model.x)) {
  6612. xAlign = 'center';
  6613. yAlign = yf(model.y);
  6614. }
  6615. } else if (rf(model.x)) {
  6616. xAlign = 'right';
  6617. // Is tooltip too wide and goes outside left edge of canvas?
  6618. if (orf(model.x)) {
  6619. xAlign = 'center';
  6620. yAlign = yf(model.y);
  6621. }
  6622. }
  6623. var opts = tooltip._options;
  6624. return {
  6625. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  6626. yAlign: opts.yAlign ? opts.yAlign : yAlign
  6627. };
  6628. }
  6629. /**
  6630. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  6631. */
  6632. function getBackgroundPoint(vm, size, alignment, chart) {
  6633. // Background Position
  6634. var x = vm.x;
  6635. var y = vm.y;
  6636. var caretSize = vm.caretSize;
  6637. var caretPadding = vm.caretPadding;
  6638. var cornerRadius = vm.cornerRadius;
  6639. var xAlign = alignment.xAlign;
  6640. var yAlign = alignment.yAlign;
  6641. var paddingAndSize = caretSize + caretPadding;
  6642. var radiusAndPadding = cornerRadius + caretPadding;
  6643. if (xAlign === 'right') {
  6644. x -= size.width;
  6645. } else if (xAlign === 'center') {
  6646. x -= (size.width / 2);
  6647. if (x + size.width > chart.width) {
  6648. x = chart.width - size.width;
  6649. }
  6650. if (x < 0) {
  6651. x = 0;
  6652. }
  6653. }
  6654. if (yAlign === 'top') {
  6655. y += paddingAndSize;
  6656. } else if (yAlign === 'bottom') {
  6657. y -= size.height + paddingAndSize;
  6658. } else {
  6659. y -= (size.height / 2);
  6660. }
  6661. if (yAlign === 'center') {
  6662. if (xAlign === 'left') {
  6663. x += paddingAndSize;
  6664. } else if (xAlign === 'right') {
  6665. x -= paddingAndSize;
  6666. }
  6667. } else if (xAlign === 'left') {
  6668. x -= radiusAndPadding;
  6669. } else if (xAlign === 'right') {
  6670. x += radiusAndPadding;
  6671. }
  6672. return {
  6673. x: x,
  6674. y: y
  6675. };
  6676. }
  6677. function getAlignedX(vm, align) {
  6678. return align === 'center'
  6679. ? vm.x + vm.width / 2
  6680. : align === 'right'
  6681. ? vm.x + vm.width - vm.xPadding
  6682. : vm.x + vm.xPadding;
  6683. }
  6684. /**
  6685. * Helper to build before and after body lines
  6686. */
  6687. function getBeforeAfterBodyLines(callback) {
  6688. return pushOrConcat([], splitNewlines(callback));
  6689. }
  6690. var exports$3 = core_element.extend({
  6691. initialize: function() {
  6692. this._model = getBaseModel(this._options);
  6693. this._lastActive = [];
  6694. },
  6695. // Get the title
  6696. // Args are: (tooltipItem, data)
  6697. getTitle: function() {
  6698. var me = this;
  6699. var opts = me._options;
  6700. var callbacks = opts.callbacks;
  6701. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  6702. var title = callbacks.title.apply(me, arguments);
  6703. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  6704. var lines = [];
  6705. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  6706. lines = pushOrConcat(lines, splitNewlines(title));
  6707. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  6708. return lines;
  6709. },
  6710. // Args are: (tooltipItem, data)
  6711. getBeforeBody: function() {
  6712. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  6713. },
  6714. // Args are: (tooltipItem, data)
  6715. getBody: function(tooltipItems, data) {
  6716. var me = this;
  6717. var callbacks = me._options.callbacks;
  6718. var bodyItems = [];
  6719. helpers$1.each(tooltipItems, function(tooltipItem) {
  6720. var bodyItem = {
  6721. before: [],
  6722. lines: [],
  6723. after: []
  6724. };
  6725. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  6726. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  6727. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  6728. bodyItems.push(bodyItem);
  6729. });
  6730. return bodyItems;
  6731. },
  6732. // Args are: (tooltipItem, data)
  6733. getAfterBody: function() {
  6734. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  6735. },
  6736. // Get the footer and beforeFooter and afterFooter lines
  6737. // Args are: (tooltipItem, data)
  6738. getFooter: function() {
  6739. var me = this;
  6740. var callbacks = me._options.callbacks;
  6741. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  6742. var footer = callbacks.footer.apply(me, arguments);
  6743. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  6744. var lines = [];
  6745. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  6746. lines = pushOrConcat(lines, splitNewlines(footer));
  6747. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  6748. return lines;
  6749. },
  6750. update: function(changed) {
  6751. var me = this;
  6752. var opts = me._options;
  6753. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  6754. // 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
  6755. // which breaks any animations.
  6756. var existingModel = me._model;
  6757. var model = me._model = getBaseModel(opts);
  6758. var active = me._active;
  6759. var data = me._data;
  6760. // In the case where active.length === 0 we need to keep these at existing values for good animations
  6761. var alignment = {
  6762. xAlign: existingModel.xAlign,
  6763. yAlign: existingModel.yAlign
  6764. };
  6765. var backgroundPoint = {
  6766. x: existingModel.x,
  6767. y: existingModel.y
  6768. };
  6769. var tooltipSize = {
  6770. width: existingModel.width,
  6771. height: existingModel.height
  6772. };
  6773. var tooltipPosition = {
  6774. x: existingModel.caretX,
  6775. y: existingModel.caretY
  6776. };
  6777. var i, len;
  6778. if (active.length) {
  6779. model.opacity = 1;
  6780. var labelColors = [];
  6781. var labelTextColors = [];
  6782. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  6783. var tooltipItems = [];
  6784. for (i = 0, len = active.length; i < len; ++i) {
  6785. tooltipItems.push(createTooltipItem(active[i]));
  6786. }
  6787. // If the user provided a filter function, use it to modify the tooltip items
  6788. if (opts.filter) {
  6789. tooltipItems = tooltipItems.filter(function(a) {
  6790. return opts.filter(a, data);
  6791. });
  6792. }
  6793. // If the user provided a sorting function, use it to modify the tooltip items
  6794. if (opts.itemSort) {
  6795. tooltipItems = tooltipItems.sort(function(a, b) {
  6796. return opts.itemSort(a, b, data);
  6797. });
  6798. }
  6799. // Determine colors for boxes
  6800. helpers$1.each(tooltipItems, function(tooltipItem) {
  6801. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  6802. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  6803. });
  6804. // Build the Text Lines
  6805. model.title = me.getTitle(tooltipItems, data);
  6806. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  6807. model.body = me.getBody(tooltipItems, data);
  6808. model.afterBody = me.getAfterBody(tooltipItems, data);
  6809. model.footer = me.getFooter(tooltipItems, data);
  6810. // Initial positioning and colors
  6811. model.x = tooltipPosition.x;
  6812. model.y = tooltipPosition.y;
  6813. model.caretPadding = opts.caretPadding;
  6814. model.labelColors = labelColors;
  6815. model.labelTextColors = labelTextColors;
  6816. // data points
  6817. model.dataPoints = tooltipItems;
  6818. // We need to determine alignment of the tooltip
  6819. tooltipSize = getTooltipSize(this, model);
  6820. alignment = determineAlignment(this, tooltipSize);
  6821. // Final Size and Position
  6822. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  6823. } else {
  6824. model.opacity = 0;
  6825. }
  6826. model.xAlign = alignment.xAlign;
  6827. model.yAlign = alignment.yAlign;
  6828. model.x = backgroundPoint.x;
  6829. model.y = backgroundPoint.y;
  6830. model.width = tooltipSize.width;
  6831. model.height = tooltipSize.height;
  6832. // Point where the caret on the tooltip points to
  6833. model.caretX = tooltipPosition.x;
  6834. model.caretY = tooltipPosition.y;
  6835. me._model = model;
  6836. if (changed && opts.custom) {
  6837. opts.custom.call(me, model);
  6838. }
  6839. return me;
  6840. },
  6841. drawCaret: function(tooltipPoint, size) {
  6842. var ctx = this._chart.ctx;
  6843. var vm = this._view;
  6844. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  6845. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  6846. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  6847. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  6848. },
  6849. getCaretPosition: function(tooltipPoint, size, vm) {
  6850. var x1, x2, x3, y1, y2, y3;
  6851. var caretSize = vm.caretSize;
  6852. var cornerRadius = vm.cornerRadius;
  6853. var xAlign = vm.xAlign;
  6854. var yAlign = vm.yAlign;
  6855. var ptX = tooltipPoint.x;
  6856. var ptY = tooltipPoint.y;
  6857. var width = size.width;
  6858. var height = size.height;
  6859. if (yAlign === 'center') {
  6860. y2 = ptY + (height / 2);
  6861. if (xAlign === 'left') {
  6862. x1 = ptX;
  6863. x2 = x1 - caretSize;
  6864. x3 = x1;
  6865. y1 = y2 + caretSize;
  6866. y3 = y2 - caretSize;
  6867. } else {
  6868. x1 = ptX + width;
  6869. x2 = x1 + caretSize;
  6870. x3 = x1;
  6871. y1 = y2 - caretSize;
  6872. y3 = y2 + caretSize;
  6873. }
  6874. } else {
  6875. if (xAlign === 'left') {
  6876. x2 = ptX + cornerRadius + (caretSize);
  6877. x1 = x2 - caretSize;
  6878. x3 = x2 + caretSize;
  6879. } else if (xAlign === 'right') {
  6880. x2 = ptX + width - cornerRadius - caretSize;
  6881. x1 = x2 - caretSize;
  6882. x3 = x2 + caretSize;
  6883. } else {
  6884. x2 = vm.caretX;
  6885. x1 = x2 - caretSize;
  6886. x3 = x2 + caretSize;
  6887. }
  6888. if (yAlign === 'top') {
  6889. y1 = ptY;
  6890. y2 = y1 - caretSize;
  6891. y3 = y1;
  6892. } else {
  6893. y1 = ptY + height;
  6894. y2 = y1 + caretSize;
  6895. y3 = y1;
  6896. // invert drawing order
  6897. var tmp = x3;
  6898. x3 = x1;
  6899. x1 = tmp;
  6900. }
  6901. }
  6902. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  6903. },
  6904. drawTitle: function(pt, vm, ctx) {
  6905. var title = vm.title;
  6906. if (title.length) {
  6907. pt.x = getAlignedX(vm, vm._titleAlign);
  6908. ctx.textAlign = vm._titleAlign;
  6909. ctx.textBaseline = 'top';
  6910. var titleFontSize = vm.titleFontSize;
  6911. var titleSpacing = vm.titleSpacing;
  6912. ctx.fillStyle = vm.titleFontColor;
  6913. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  6914. var i, len;
  6915. for (i = 0, len = title.length; i < len; ++i) {
  6916. ctx.fillText(title[i], pt.x, pt.y);
  6917. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  6918. if (i + 1 === title.length) {
  6919. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  6920. }
  6921. }
  6922. }
  6923. },
  6924. drawBody: function(pt, vm, ctx) {
  6925. var bodyFontSize = vm.bodyFontSize;
  6926. var bodySpacing = vm.bodySpacing;
  6927. var bodyAlign = vm._bodyAlign;
  6928. var body = vm.body;
  6929. var drawColorBoxes = vm.displayColors;
  6930. var labelColors = vm.labelColors;
  6931. var xLinePadding = 0;
  6932. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  6933. var textColor;
  6934. ctx.textAlign = bodyAlign;
  6935. ctx.textBaseline = 'top';
  6936. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  6937. pt.x = getAlignedX(vm, bodyAlign);
  6938. // Before Body
  6939. var fillLineOfText = function(line) {
  6940. ctx.fillText(line, pt.x + xLinePadding, pt.y);
  6941. pt.y += bodyFontSize + bodySpacing;
  6942. };
  6943. // Before body lines
  6944. ctx.fillStyle = vm.bodyFontColor;
  6945. helpers$1.each(vm.beforeBody, fillLineOfText);
  6946. xLinePadding = drawColorBoxes && bodyAlign !== 'right'
  6947. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  6948. : 0;
  6949. // Draw body lines now
  6950. helpers$1.each(body, function(bodyItem, i) {
  6951. textColor = vm.labelTextColors[i];
  6952. ctx.fillStyle = textColor;
  6953. helpers$1.each(bodyItem.before, fillLineOfText);
  6954. helpers$1.each(bodyItem.lines, function(line) {
  6955. // Draw Legend-like boxes if needed
  6956. if (drawColorBoxes) {
  6957. // Fill a white rect so that colours merge nicely if the opacity is < 1
  6958. ctx.fillStyle = vm.legendColorBackground;
  6959. ctx.fillRect(colorX, pt.y, bodyFontSize, bodyFontSize);
  6960. // Border
  6961. ctx.lineWidth = 1;
  6962. ctx.strokeStyle = labelColors[i].borderColor;
  6963. ctx.strokeRect(colorX, pt.y, bodyFontSize, bodyFontSize);
  6964. // Inner square
  6965. ctx.fillStyle = labelColors[i].backgroundColor;
  6966. ctx.fillRect(colorX + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  6967. ctx.fillStyle = textColor;
  6968. }
  6969. fillLineOfText(line);
  6970. });
  6971. helpers$1.each(bodyItem.after, fillLineOfText);
  6972. });
  6973. // Reset back to 0 for after body
  6974. xLinePadding = 0;
  6975. // After body lines
  6976. helpers$1.each(vm.afterBody, fillLineOfText);
  6977. pt.y -= bodySpacing; // Remove last body spacing
  6978. },
  6979. drawFooter: function(pt, vm, ctx) {
  6980. var footer = vm.footer;
  6981. if (footer.length) {
  6982. pt.x = getAlignedX(vm, vm._footerAlign);
  6983. pt.y += vm.footerMarginTop;
  6984. ctx.textAlign = vm._footerAlign;
  6985. ctx.textBaseline = 'top';
  6986. ctx.fillStyle = vm.footerFontColor;
  6987. ctx.font = helpers$1.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  6988. helpers$1.each(footer, function(line) {
  6989. ctx.fillText(line, pt.x, pt.y);
  6990. pt.y += vm.footerFontSize + vm.footerSpacing;
  6991. });
  6992. }
  6993. },
  6994. drawBackground: function(pt, vm, ctx, tooltipSize) {
  6995. ctx.fillStyle = vm.backgroundColor;
  6996. ctx.strokeStyle = vm.borderColor;
  6997. ctx.lineWidth = vm.borderWidth;
  6998. var xAlign = vm.xAlign;
  6999. var yAlign = vm.yAlign;
  7000. var x = pt.x;
  7001. var y = pt.y;
  7002. var width = tooltipSize.width;
  7003. var height = tooltipSize.height;
  7004. var radius = vm.cornerRadius;
  7005. ctx.beginPath();
  7006. ctx.moveTo(x + radius, y);
  7007. if (yAlign === 'top') {
  7008. this.drawCaret(pt, tooltipSize);
  7009. }
  7010. ctx.lineTo(x + width - radius, y);
  7011. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7012. if (yAlign === 'center' && xAlign === 'right') {
  7013. this.drawCaret(pt, tooltipSize);
  7014. }
  7015. ctx.lineTo(x + width, y + height - radius);
  7016. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7017. if (yAlign === 'bottom') {
  7018. this.drawCaret(pt, tooltipSize);
  7019. }
  7020. ctx.lineTo(x + radius, y + height);
  7021. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7022. if (yAlign === 'center' && xAlign === 'left') {
  7023. this.drawCaret(pt, tooltipSize);
  7024. }
  7025. ctx.lineTo(x, y + radius);
  7026. ctx.quadraticCurveTo(x, y, x + radius, y);
  7027. ctx.closePath();
  7028. ctx.fill();
  7029. if (vm.borderWidth > 0) {
  7030. ctx.stroke();
  7031. }
  7032. },
  7033. draw: function() {
  7034. var ctx = this._chart.ctx;
  7035. var vm = this._view;
  7036. if (vm.opacity === 0) {
  7037. return;
  7038. }
  7039. var tooltipSize = {
  7040. width: vm.width,
  7041. height: vm.height
  7042. };
  7043. var pt = {
  7044. x: vm.x,
  7045. y: vm.y
  7046. };
  7047. // IE11/Edge does not like very small opacities, so snap to 0
  7048. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7049. // Truthy/falsey value for empty tooltip
  7050. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7051. if (this._options.enabled && hasTooltipContent) {
  7052. ctx.save();
  7053. ctx.globalAlpha = opacity;
  7054. // Draw Background
  7055. this.drawBackground(pt, vm, ctx, tooltipSize);
  7056. // Draw Title, Body, and Footer
  7057. pt.y += vm.yPadding;
  7058. // Titles
  7059. this.drawTitle(pt, vm, ctx);
  7060. // Body
  7061. this.drawBody(pt, vm, ctx);
  7062. // Footer
  7063. this.drawFooter(pt, vm, ctx);
  7064. ctx.restore();
  7065. }
  7066. },
  7067. /**
  7068. * Handle an event
  7069. * @private
  7070. * @param {IEvent} event - The event to handle
  7071. * @returns {boolean} true if the tooltip changed
  7072. */
  7073. handleEvent: function(e) {
  7074. var me = this;
  7075. var options = me._options;
  7076. var changed = false;
  7077. me._lastActive = me._lastActive || [];
  7078. // Find Active Elements for tooltips
  7079. if (e.type === 'mouseout') {
  7080. me._active = [];
  7081. } else {
  7082. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7083. }
  7084. // Remember Last Actives
  7085. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7086. // Only handle target event on tooltip change
  7087. if (changed) {
  7088. me._lastActive = me._active;
  7089. if (options.enabled || options.custom) {
  7090. me._eventPosition = {
  7091. x: e.x,
  7092. y: e.y
  7093. };
  7094. me.update(true);
  7095. me.pivot();
  7096. }
  7097. }
  7098. return changed;
  7099. }
  7100. });
  7101. /**
  7102. * @namespace Chart.Tooltip.positioners
  7103. */
  7104. var positioners_1 = positioners;
  7105. var core_tooltip = exports$3;
  7106. core_tooltip.positioners = positioners_1;
  7107. var valueOrDefault$8 = helpers$1.valueOrDefault;
  7108. core_defaults._set('global', {
  7109. elements: {},
  7110. events: [
  7111. 'mousemove',
  7112. 'mouseout',
  7113. 'click',
  7114. 'touchstart',
  7115. 'touchmove'
  7116. ],
  7117. hover: {
  7118. onHover: null,
  7119. mode: 'nearest',
  7120. intersect: true,
  7121. animationDuration: 400
  7122. },
  7123. onClick: null,
  7124. maintainAspectRatio: true,
  7125. responsive: true,
  7126. responsiveAnimationDuration: 0
  7127. });
  7128. /**
  7129. * Recursively merge the given config objects representing the `scales` option
  7130. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7131. * returns a deep copy of the result, thus doesn't alter inputs.
  7132. */
  7133. function mergeScaleConfig(/* config objects ... */) {
  7134. return helpers$1.merge({}, [].slice.call(arguments), {
  7135. merger: function(key, target, source, options) {
  7136. if (key === 'xAxes' || key === 'yAxes') {
  7137. var slen = source[key].length;
  7138. var i, type, scale;
  7139. if (!target[key]) {
  7140. target[key] = [];
  7141. }
  7142. for (i = 0; i < slen; ++i) {
  7143. scale = source[key][i];
  7144. type = valueOrDefault$8(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7145. if (i >= target[key].length) {
  7146. target[key].push({});
  7147. }
  7148. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7149. // new/untyped scale or type changed: let's apply the new defaults
  7150. // then merge source scale to correctly overwrite the defaults.
  7151. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7152. } else {
  7153. // scales type are the same
  7154. helpers$1.merge(target[key][i], scale);
  7155. }
  7156. }
  7157. } else {
  7158. helpers$1._merger(key, target, source, options);
  7159. }
  7160. }
  7161. });
  7162. }
  7163. /**
  7164. * Recursively merge the given config objects as the root options by handling
  7165. * default scale options for the `scales` and `scale` properties, then returns
  7166. * a deep copy of the result, thus doesn't alter inputs.
  7167. */
  7168. function mergeConfig(/* config objects ... */) {
  7169. return helpers$1.merge({}, [].slice.call(arguments), {
  7170. merger: function(key, target, source, options) {
  7171. var tval = target[key] || {};
  7172. var sval = source[key];
  7173. if (key === 'scales') {
  7174. // scale config merging is complex. Add our own function here for that
  7175. target[key] = mergeScaleConfig(tval, sval);
  7176. } else if (key === 'scale') {
  7177. // used in polar area & radar charts since there is only one scale
  7178. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7179. } else {
  7180. helpers$1._merger(key, target, source, options);
  7181. }
  7182. }
  7183. });
  7184. }
  7185. function initConfig(config) {
  7186. config = config || {};
  7187. // Do NOT use mergeConfig for the data object because this method merges arrays
  7188. // and so would change references to labels and datasets, preventing data updates.
  7189. var data = config.data = config.data || {};
  7190. data.datasets = data.datasets || [];
  7191. data.labels = data.labels || [];
  7192. config.options = mergeConfig(
  7193. core_defaults.global,
  7194. core_defaults[config.type],
  7195. config.options || {});
  7196. return config;
  7197. }
  7198. function updateConfig(chart) {
  7199. var newOptions = chart.options;
  7200. helpers$1.each(chart.scales, function(scale) {
  7201. core_layouts.removeBox(chart, scale);
  7202. });
  7203. newOptions = mergeConfig(
  7204. core_defaults.global,
  7205. core_defaults[chart.config.type],
  7206. newOptions);
  7207. chart.options = chart.config.options = newOptions;
  7208. chart.ensureScalesHaveIDs();
  7209. chart.buildOrUpdateScales();
  7210. // Tooltip
  7211. chart.tooltip._options = newOptions.tooltips;
  7212. chart.tooltip.initialize();
  7213. }
  7214. function positionIsHorizontal(position) {
  7215. return position === 'top' || position === 'bottom';
  7216. }
  7217. var Chart = function(item, config) {
  7218. this.construct(item, config);
  7219. return this;
  7220. };
  7221. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  7222. /**
  7223. * @private
  7224. */
  7225. construct: function(item, config) {
  7226. var me = this;
  7227. config = initConfig(config);
  7228. var context = platform.acquireContext(item, config);
  7229. var canvas = context && context.canvas;
  7230. var height = canvas && canvas.height;
  7231. var width = canvas && canvas.width;
  7232. me.id = helpers$1.uid();
  7233. me.ctx = context;
  7234. me.canvas = canvas;
  7235. me.config = config;
  7236. me.width = width;
  7237. me.height = height;
  7238. me.aspectRatio = height ? width / height : null;
  7239. me.options = config.options;
  7240. me._bufferedRender = false;
  7241. /**
  7242. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  7243. * the "instance" still need to be defined since it might be called from plugins.
  7244. * @prop Chart#chart
  7245. * @deprecated since version 2.6.0
  7246. * @todo remove at version 3
  7247. * @private
  7248. */
  7249. me.chart = me;
  7250. me.controller = me; // chart.chart.controller #inception
  7251. // Add the chart instance to the global namespace
  7252. Chart.instances[me.id] = me;
  7253. // Define alias to the config data: `chart.data === chart.config.data`
  7254. Object.defineProperty(me, 'data', {
  7255. get: function() {
  7256. return me.config.data;
  7257. },
  7258. set: function(value) {
  7259. me.config.data = value;
  7260. }
  7261. });
  7262. if (!context || !canvas) {
  7263. // The given item is not a compatible context2d element, let's return before finalizing
  7264. // the chart initialization but after setting basic chart / controller properties that
  7265. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  7266. // https://github.com/chartjs/Chart.js/issues/2807
  7267. console.error("Failed to create chart: can't acquire context from the given item");
  7268. return;
  7269. }
  7270. me.initialize();
  7271. me.update();
  7272. },
  7273. /**
  7274. * @private
  7275. */
  7276. initialize: function() {
  7277. var me = this;
  7278. // Before init plugin notification
  7279. core_plugins.notify(me, 'beforeInit');
  7280. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  7281. me.bindEvents();
  7282. if (me.options.responsive) {
  7283. // Initial resize before chart draws (must be silent to preserve initial animations).
  7284. me.resize(true);
  7285. }
  7286. // Make sure scales have IDs and are built before we build any controllers.
  7287. me.ensureScalesHaveIDs();
  7288. me.buildOrUpdateScales();
  7289. me.initToolTip();
  7290. // After init plugin notification
  7291. core_plugins.notify(me, 'afterInit');
  7292. return me;
  7293. },
  7294. clear: function() {
  7295. helpers$1.canvas.clear(this);
  7296. return this;
  7297. },
  7298. stop: function() {
  7299. // Stops any current animation loop occurring
  7300. core_animations.cancelAnimation(this);
  7301. return this;
  7302. },
  7303. resize: function(silent) {
  7304. var me = this;
  7305. var options = me.options;
  7306. var canvas = me.canvas;
  7307. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  7308. // the canvas render width and height will be casted to integers so make sure that
  7309. // the canvas display style uses the same integer values to avoid blurring effect.
  7310. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  7311. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  7312. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  7313. if (me.width === newWidth && me.height === newHeight) {
  7314. return;
  7315. }
  7316. canvas.width = me.width = newWidth;
  7317. canvas.height = me.height = newHeight;
  7318. canvas.style.width = newWidth + 'px';
  7319. canvas.style.height = newHeight + 'px';
  7320. helpers$1.retinaScale(me, options.devicePixelRatio);
  7321. if (!silent) {
  7322. // Notify any plugins about the resize
  7323. var newSize = {width: newWidth, height: newHeight};
  7324. core_plugins.notify(me, 'resize', [newSize]);
  7325. // Notify of resize
  7326. if (options.onResize) {
  7327. options.onResize(me, newSize);
  7328. }
  7329. me.stop();
  7330. me.update({
  7331. duration: options.responsiveAnimationDuration
  7332. });
  7333. }
  7334. },
  7335. ensureScalesHaveIDs: function() {
  7336. var options = this.options;
  7337. var scalesOptions = options.scales || {};
  7338. var scaleOptions = options.scale;
  7339. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  7340. xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
  7341. });
  7342. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  7343. yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
  7344. });
  7345. if (scaleOptions) {
  7346. scaleOptions.id = scaleOptions.id || 'scale';
  7347. }
  7348. },
  7349. /**
  7350. * Builds a map of scale ID to scale object for future lookup.
  7351. */
  7352. buildOrUpdateScales: function() {
  7353. var me = this;
  7354. var options = me.options;
  7355. var scales = me.scales || {};
  7356. var items = [];
  7357. var updated = Object.keys(scales).reduce(function(obj, id) {
  7358. obj[id] = false;
  7359. return obj;
  7360. }, {});
  7361. if (options.scales) {
  7362. items = items.concat(
  7363. (options.scales.xAxes || []).map(function(xAxisOptions) {
  7364. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  7365. }),
  7366. (options.scales.yAxes || []).map(function(yAxisOptions) {
  7367. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  7368. })
  7369. );
  7370. }
  7371. if (options.scale) {
  7372. items.push({
  7373. options: options.scale,
  7374. dtype: 'radialLinear',
  7375. isDefault: true,
  7376. dposition: 'chartArea'
  7377. });
  7378. }
  7379. helpers$1.each(items, function(item) {
  7380. var scaleOptions = item.options;
  7381. var id = scaleOptions.id;
  7382. var scaleType = valueOrDefault$8(scaleOptions.type, item.dtype);
  7383. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  7384. scaleOptions.position = item.dposition;
  7385. }
  7386. updated[id] = true;
  7387. var scale = null;
  7388. if (id in scales && scales[id].type === scaleType) {
  7389. scale = scales[id];
  7390. scale.options = scaleOptions;
  7391. scale.ctx = me.ctx;
  7392. scale.chart = me;
  7393. } else {
  7394. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  7395. if (!scaleClass) {
  7396. return;
  7397. }
  7398. scale = new scaleClass({
  7399. id: id,
  7400. type: scaleType,
  7401. options: scaleOptions,
  7402. ctx: me.ctx,
  7403. chart: me
  7404. });
  7405. scales[scale.id] = scale;
  7406. }
  7407. scale.mergeTicksOptions();
  7408. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  7409. // and consider it as a regular scale part of the "scales"" map only! This would
  7410. // make the logic easier and remove some useless? custom code.
  7411. if (item.isDefault) {
  7412. me.scale = scale;
  7413. }
  7414. });
  7415. // clear up discarded scales
  7416. helpers$1.each(updated, function(hasUpdated, id) {
  7417. if (!hasUpdated) {
  7418. delete scales[id];
  7419. }
  7420. });
  7421. me.scales = scales;
  7422. core_scaleService.addScalesToLayout(this);
  7423. },
  7424. buildOrUpdateControllers: function() {
  7425. var me = this;
  7426. var newControllers = [];
  7427. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  7428. var meta = me.getDatasetMeta(datasetIndex);
  7429. var type = dataset.type || me.config.type;
  7430. if (meta.type && meta.type !== type) {
  7431. me.destroyDatasetMeta(datasetIndex);
  7432. meta = me.getDatasetMeta(datasetIndex);
  7433. }
  7434. meta.type = type;
  7435. if (meta.controller) {
  7436. meta.controller.updateIndex(datasetIndex);
  7437. meta.controller.linkScales();
  7438. } else {
  7439. var ControllerClass = controllers[meta.type];
  7440. if (ControllerClass === undefined) {
  7441. throw new Error('"' + meta.type + '" is not a chart type.');
  7442. }
  7443. meta.controller = new ControllerClass(me, datasetIndex);
  7444. newControllers.push(meta.controller);
  7445. }
  7446. }, me);
  7447. return newControllers;
  7448. },
  7449. /**
  7450. * Reset the elements of all datasets
  7451. * @private
  7452. */
  7453. resetElements: function() {
  7454. var me = this;
  7455. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  7456. me.getDatasetMeta(datasetIndex).controller.reset();
  7457. }, me);
  7458. },
  7459. /**
  7460. * Resets the chart back to it's state before the initial animation
  7461. */
  7462. reset: function() {
  7463. this.resetElements();
  7464. this.tooltip.initialize();
  7465. },
  7466. update: function(config) {
  7467. var me = this;
  7468. if (!config || typeof config !== 'object') {
  7469. // backwards compatibility
  7470. config = {
  7471. duration: config,
  7472. lazy: arguments[1]
  7473. };
  7474. }
  7475. updateConfig(me);
  7476. // plugins options references might have change, let's invalidate the cache
  7477. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  7478. core_plugins._invalidate(me);
  7479. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  7480. return;
  7481. }
  7482. // In case the entire data object changed
  7483. me.tooltip._data = me.data;
  7484. // Make sure dataset controllers are updated and new controllers are reset
  7485. var newControllers = me.buildOrUpdateControllers();
  7486. // Make sure all dataset controllers have correct meta data counts
  7487. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  7488. me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
  7489. }, me);
  7490. me.updateLayout();
  7491. // Can only reset the new controllers after the scales have been updated
  7492. if (me.options.animation && me.options.animation.duration) {
  7493. helpers$1.each(newControllers, function(controller) {
  7494. controller.reset();
  7495. });
  7496. }
  7497. me.updateDatasets();
  7498. // Need to reset tooltip in case it is displayed with elements that are removed
  7499. // after update.
  7500. me.tooltip.initialize();
  7501. // Last active contains items that were previously in the tooltip.
  7502. // When we reset the tooltip, we need to clear it
  7503. me.lastActive = [];
  7504. // Do this before render so that any plugins that need final scale updates can use it
  7505. core_plugins.notify(me, 'afterUpdate');
  7506. if (me._bufferedRender) {
  7507. me._bufferedRequest = {
  7508. duration: config.duration,
  7509. easing: config.easing,
  7510. lazy: config.lazy
  7511. };
  7512. } else {
  7513. me.render(config);
  7514. }
  7515. },
  7516. /**
  7517. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  7518. * hook, in which case, plugins will not be called on `afterLayout`.
  7519. * @private
  7520. */
  7521. updateLayout: function() {
  7522. var me = this;
  7523. if (core_plugins.notify(me, 'beforeLayout') === false) {
  7524. return;
  7525. }
  7526. core_layouts.update(this, this.width, this.height);
  7527. /**
  7528. * Provided for backward compatibility, use `afterLayout` instead.
  7529. * @method IPlugin#afterScaleUpdate
  7530. * @deprecated since version 2.5.0
  7531. * @todo remove at version 3
  7532. * @private
  7533. */
  7534. core_plugins.notify(me, 'afterScaleUpdate');
  7535. core_plugins.notify(me, 'afterLayout');
  7536. },
  7537. /**
  7538. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  7539. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  7540. * @private
  7541. */
  7542. updateDatasets: function() {
  7543. var me = this;
  7544. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  7545. return;
  7546. }
  7547. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  7548. me.updateDataset(i);
  7549. }
  7550. core_plugins.notify(me, 'afterDatasetsUpdate');
  7551. },
  7552. /**
  7553. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  7554. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  7555. * @private
  7556. */
  7557. updateDataset: function(index) {
  7558. var me = this;
  7559. var meta = me.getDatasetMeta(index);
  7560. var args = {
  7561. meta: meta,
  7562. index: index
  7563. };
  7564. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  7565. return;
  7566. }
  7567. meta.controller.update();
  7568. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  7569. },
  7570. render: function(config) {
  7571. var me = this;
  7572. if (!config || typeof config !== 'object') {
  7573. // backwards compatibility
  7574. config = {
  7575. duration: config,
  7576. lazy: arguments[1]
  7577. };
  7578. }
  7579. var animationOptions = me.options.animation;
  7580. var duration = valueOrDefault$8(config.duration, animationOptions && animationOptions.duration);
  7581. var lazy = config.lazy;
  7582. if (core_plugins.notify(me, 'beforeRender') === false) {
  7583. return;
  7584. }
  7585. var onComplete = function(animation) {
  7586. core_plugins.notify(me, 'afterRender');
  7587. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  7588. };
  7589. if (animationOptions && duration) {
  7590. var animation = new core_animation({
  7591. numSteps: duration / 16.66, // 60 fps
  7592. easing: config.easing || animationOptions.easing,
  7593. render: function(chart, animationObject) {
  7594. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  7595. var currentStep = animationObject.currentStep;
  7596. var stepDecimal = currentStep / animationObject.numSteps;
  7597. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  7598. },
  7599. onAnimationProgress: animationOptions.onProgress,
  7600. onAnimationComplete: onComplete
  7601. });
  7602. core_animations.addAnimation(me, animation, duration, lazy);
  7603. } else {
  7604. me.draw();
  7605. // See https://github.com/chartjs/Chart.js/issues/3781
  7606. onComplete(new core_animation({numSteps: 0, chart: me}));
  7607. }
  7608. return me;
  7609. },
  7610. draw: function(easingValue) {
  7611. var me = this;
  7612. me.clear();
  7613. if (helpers$1.isNullOrUndef(easingValue)) {
  7614. easingValue = 1;
  7615. }
  7616. me.transition(easingValue);
  7617. if (me.width <= 0 || me.height <= 0) {
  7618. return;
  7619. }
  7620. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  7621. return;
  7622. }
  7623. // Draw all the scales
  7624. helpers$1.each(me.boxes, function(box) {
  7625. box.draw(me.chartArea);
  7626. }, me);
  7627. me.drawDatasets(easingValue);
  7628. me._drawTooltip(easingValue);
  7629. core_plugins.notify(me, 'afterDraw', [easingValue]);
  7630. },
  7631. /**
  7632. * @private
  7633. */
  7634. transition: function(easingValue) {
  7635. var me = this;
  7636. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  7637. if (me.isDatasetVisible(i)) {
  7638. me.getDatasetMeta(i).controller.transition(easingValue);
  7639. }
  7640. }
  7641. me.tooltip.transition(easingValue);
  7642. },
  7643. /**
  7644. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  7645. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  7646. * @private
  7647. */
  7648. drawDatasets: function(easingValue) {
  7649. var me = this;
  7650. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  7651. return;
  7652. }
  7653. // Draw datasets reversed to support proper line stacking
  7654. for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {
  7655. if (me.isDatasetVisible(i)) {
  7656. me.drawDataset(i, easingValue);
  7657. }
  7658. }
  7659. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  7660. },
  7661. /**
  7662. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  7663. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  7664. * @private
  7665. */
  7666. drawDataset: function(index, easingValue) {
  7667. var me = this;
  7668. var meta = me.getDatasetMeta(index);
  7669. var args = {
  7670. meta: meta,
  7671. index: index,
  7672. easingValue: easingValue
  7673. };
  7674. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  7675. return;
  7676. }
  7677. meta.controller.draw(easingValue);
  7678. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  7679. },
  7680. /**
  7681. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  7682. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  7683. * @private
  7684. */
  7685. _drawTooltip: function(easingValue) {
  7686. var me = this;
  7687. var tooltip = me.tooltip;
  7688. var args = {
  7689. tooltip: tooltip,
  7690. easingValue: easingValue
  7691. };
  7692. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  7693. return;
  7694. }
  7695. tooltip.draw();
  7696. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  7697. },
  7698. /**
  7699. * Get the single element that was clicked on
  7700. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  7701. */
  7702. getElementAtEvent: function(e) {
  7703. return core_interaction.modes.single(this, e);
  7704. },
  7705. getElementsAtEvent: function(e) {
  7706. return core_interaction.modes.label(this, e, {intersect: true});
  7707. },
  7708. getElementsAtXAxis: function(e) {
  7709. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  7710. },
  7711. getElementsAtEventForMode: function(e, mode, options) {
  7712. var method = core_interaction.modes[mode];
  7713. if (typeof method === 'function') {
  7714. return method(this, e, options);
  7715. }
  7716. return [];
  7717. },
  7718. getDatasetAtEvent: function(e) {
  7719. return core_interaction.modes.dataset(this, e, {intersect: true});
  7720. },
  7721. getDatasetMeta: function(datasetIndex) {
  7722. var me = this;
  7723. var dataset = me.data.datasets[datasetIndex];
  7724. if (!dataset._meta) {
  7725. dataset._meta = {};
  7726. }
  7727. var meta = dataset._meta[me.id];
  7728. if (!meta) {
  7729. meta = dataset._meta[me.id] = {
  7730. type: null,
  7731. data: [],
  7732. dataset: null,
  7733. controller: null,
  7734. hidden: null, // See isDatasetVisible() comment
  7735. xAxisID: null,
  7736. yAxisID: null
  7737. };
  7738. }
  7739. return meta;
  7740. },
  7741. getVisibleDatasetCount: function() {
  7742. var count = 0;
  7743. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  7744. if (this.isDatasetVisible(i)) {
  7745. count++;
  7746. }
  7747. }
  7748. return count;
  7749. },
  7750. isDatasetVisible: function(datasetIndex) {
  7751. var meta = this.getDatasetMeta(datasetIndex);
  7752. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  7753. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  7754. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  7755. },
  7756. generateLegend: function() {
  7757. return this.options.legendCallback(this);
  7758. },
  7759. /**
  7760. * @private
  7761. */
  7762. destroyDatasetMeta: function(datasetIndex) {
  7763. var id = this.id;
  7764. var dataset = this.data.datasets[datasetIndex];
  7765. var meta = dataset._meta && dataset._meta[id];
  7766. if (meta) {
  7767. meta.controller.destroy();
  7768. delete dataset._meta[id];
  7769. }
  7770. },
  7771. destroy: function() {
  7772. var me = this;
  7773. var canvas = me.canvas;
  7774. var i, ilen;
  7775. me.stop();
  7776. // dataset controllers need to cleanup associated data
  7777. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  7778. me.destroyDatasetMeta(i);
  7779. }
  7780. if (canvas) {
  7781. me.unbindEvents();
  7782. helpers$1.canvas.clear(me);
  7783. platform.releaseContext(me.ctx);
  7784. me.canvas = null;
  7785. me.ctx = null;
  7786. }
  7787. core_plugins.notify(me, 'destroy');
  7788. delete Chart.instances[me.id];
  7789. },
  7790. toBase64Image: function() {
  7791. return this.canvas.toDataURL.apply(this.canvas, arguments);
  7792. },
  7793. initToolTip: function() {
  7794. var me = this;
  7795. me.tooltip = new core_tooltip({
  7796. _chart: me,
  7797. _chartInstance: me, // deprecated, backward compatibility
  7798. _data: me.data,
  7799. _options: me.options.tooltips
  7800. }, me);
  7801. },
  7802. /**
  7803. * @private
  7804. */
  7805. bindEvents: function() {
  7806. var me = this;
  7807. var listeners = me._listeners = {};
  7808. var listener = function() {
  7809. me.eventHandler.apply(me, arguments);
  7810. };
  7811. helpers$1.each(me.options.events, function(type) {
  7812. platform.addEventListener(me, type, listener);
  7813. listeners[type] = listener;
  7814. });
  7815. // Elements used to detect size change should not be injected for non responsive charts.
  7816. // See https://github.com/chartjs/Chart.js/issues/2210
  7817. if (me.options.responsive) {
  7818. listener = function() {
  7819. me.resize();
  7820. };
  7821. platform.addEventListener(me, 'resize', listener);
  7822. listeners.resize = listener;
  7823. }
  7824. },
  7825. /**
  7826. * @private
  7827. */
  7828. unbindEvents: function() {
  7829. var me = this;
  7830. var listeners = me._listeners;
  7831. if (!listeners) {
  7832. return;
  7833. }
  7834. delete me._listeners;
  7835. helpers$1.each(listeners, function(listener, type) {
  7836. platform.removeEventListener(me, type, listener);
  7837. });
  7838. },
  7839. updateHoverStyle: function(elements, mode, enabled) {
  7840. var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';
  7841. var element, i, ilen;
  7842. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  7843. element = elements[i];
  7844. if (element) {
  7845. this.getDatasetMeta(element._datasetIndex).controller[method](element);
  7846. }
  7847. }
  7848. },
  7849. /**
  7850. * @private
  7851. */
  7852. eventHandler: function(e) {
  7853. var me = this;
  7854. var tooltip = me.tooltip;
  7855. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  7856. return;
  7857. }
  7858. // Buffer any update calls so that renders do not occur
  7859. me._bufferedRender = true;
  7860. me._bufferedRequest = null;
  7861. var changed = me.handleEvent(e);
  7862. // for smooth tooltip animations issue #4989
  7863. // the tooltip should be the source of change
  7864. // Animation check workaround:
  7865. // tooltip._start will be null when tooltip isn't animating
  7866. if (tooltip) {
  7867. changed = tooltip._start
  7868. ? tooltip.handleEvent(e)
  7869. : changed | tooltip.handleEvent(e);
  7870. }
  7871. core_plugins.notify(me, 'afterEvent', [e]);
  7872. var bufferedRequest = me._bufferedRequest;
  7873. if (bufferedRequest) {
  7874. // If we have an update that was triggered, we need to do a normal render
  7875. me.render(bufferedRequest);
  7876. } else if (changed && !me.animating) {
  7877. // If entering, leaving, or changing elements, animate the change via pivot
  7878. me.stop();
  7879. // We only need to render at this point. Updating will cause scales to be
  7880. // recomputed generating flicker & using more memory than necessary.
  7881. me.render({
  7882. duration: me.options.hover.animationDuration,
  7883. lazy: true
  7884. });
  7885. }
  7886. me._bufferedRender = false;
  7887. me._bufferedRequest = null;
  7888. return me;
  7889. },
  7890. /**
  7891. * Handle an event
  7892. * @private
  7893. * @param {IEvent} event the event to handle
  7894. * @return {boolean} true if the chart needs to re-render
  7895. */
  7896. handleEvent: function(e) {
  7897. var me = this;
  7898. var options = me.options || {};
  7899. var hoverOptions = options.hover;
  7900. var changed = false;
  7901. me.lastActive = me.lastActive || [];
  7902. // Find Active Elements for hover and tooltips
  7903. if (e.type === 'mouseout') {
  7904. me.active = [];
  7905. } else {
  7906. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  7907. }
  7908. // Invoke onHover hook
  7909. // Need to call with native event here to not break backwards compatibility
  7910. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  7911. if (e.type === 'mouseup' || e.type === 'click') {
  7912. if (options.onClick) {
  7913. // Use e.native here for backwards compatibility
  7914. options.onClick.call(me, e.native, me.active);
  7915. }
  7916. }
  7917. // Remove styling for last active (even if it may still be active)
  7918. if (me.lastActive.length) {
  7919. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  7920. }
  7921. // Built in hover styling
  7922. if (me.active.length && hoverOptions.mode) {
  7923. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  7924. }
  7925. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  7926. // Remember Last Actives
  7927. me.lastActive = me.active;
  7928. return changed;
  7929. }
  7930. });
  7931. /**
  7932. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  7933. * for backward compatibility. Though, it can still be useful for plugins that
  7934. * would need to work on multiple charts?!
  7935. */
  7936. Chart.instances = {};
  7937. var core_controller = Chart;
  7938. // DEPRECATIONS
  7939. /**
  7940. * Provided for backward compatibility, use Chart instead.
  7941. * @class Chart.Controller
  7942. * @deprecated since version 2.6
  7943. * @todo remove at version 3
  7944. * @private
  7945. */
  7946. Chart.Controller = Chart;
  7947. /**
  7948. * Provided for backward compatibility, not available anymore.
  7949. * @namespace Chart
  7950. * @deprecated since version 2.8
  7951. * @todo remove at version 3
  7952. * @private
  7953. */
  7954. Chart.types = {};
  7955. /**
  7956. * Provided for backward compatibility, not available anymore.
  7957. * @namespace Chart.helpers.configMerge
  7958. * @deprecated since version 2.8.0
  7959. * @todo remove at version 3
  7960. * @private
  7961. */
  7962. helpers$1.configMerge = mergeConfig;
  7963. /**
  7964. * Provided for backward compatibility, not available anymore.
  7965. * @namespace Chart.helpers.scaleMerge
  7966. * @deprecated since version 2.8.0
  7967. * @todo remove at version 3
  7968. * @private
  7969. */
  7970. helpers$1.scaleMerge = mergeScaleConfig;
  7971. var core_helpers = function() {
  7972. // -- Basic js utility methods
  7973. helpers$1.where = function(collection, filterCallback) {
  7974. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  7975. return collection.filter(filterCallback);
  7976. }
  7977. var filtered = [];
  7978. helpers$1.each(collection, function(item) {
  7979. if (filterCallback(item)) {
  7980. filtered.push(item);
  7981. }
  7982. });
  7983. return filtered;
  7984. };
  7985. helpers$1.findIndex = Array.prototype.findIndex ?
  7986. function(array, callback, scope) {
  7987. return array.findIndex(callback, scope);
  7988. } :
  7989. function(array, callback, scope) {
  7990. scope = scope === undefined ? array : scope;
  7991. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  7992. if (callback.call(scope, array[i], i, array)) {
  7993. return i;
  7994. }
  7995. }
  7996. return -1;
  7997. };
  7998. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  7999. // Default to start of the array
  8000. if (helpers$1.isNullOrUndef(startIndex)) {
  8001. startIndex = -1;
  8002. }
  8003. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8004. var currentItem = arrayToSearch[i];
  8005. if (filterCallback(currentItem)) {
  8006. return currentItem;
  8007. }
  8008. }
  8009. };
  8010. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8011. // Default to end of the array
  8012. if (helpers$1.isNullOrUndef(startIndex)) {
  8013. startIndex = arrayToSearch.length;
  8014. }
  8015. for (var i = startIndex - 1; i >= 0; i--) {
  8016. var currentItem = arrayToSearch[i];
  8017. if (filterCallback(currentItem)) {
  8018. return currentItem;
  8019. }
  8020. }
  8021. };
  8022. // -- Math methods
  8023. helpers$1.isNumber = function(n) {
  8024. return !isNaN(parseFloat(n)) && isFinite(n);
  8025. };
  8026. helpers$1.almostEquals = function(x, y, epsilon) {
  8027. return Math.abs(x - y) < epsilon;
  8028. };
  8029. helpers$1.almostWhole = function(x, epsilon) {
  8030. var rounded = Math.round(x);
  8031. return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
  8032. };
  8033. helpers$1.max = function(array) {
  8034. return array.reduce(function(max, value) {
  8035. if (!isNaN(value)) {
  8036. return Math.max(max, value);
  8037. }
  8038. return max;
  8039. }, Number.NEGATIVE_INFINITY);
  8040. };
  8041. helpers$1.min = function(array) {
  8042. return array.reduce(function(min, value) {
  8043. if (!isNaN(value)) {
  8044. return Math.min(min, value);
  8045. }
  8046. return min;
  8047. }, Number.POSITIVE_INFINITY);
  8048. };
  8049. helpers$1.sign = Math.sign ?
  8050. function(x) {
  8051. return Math.sign(x);
  8052. } :
  8053. function(x) {
  8054. x = +x; // convert to a number
  8055. if (x === 0 || isNaN(x)) {
  8056. return x;
  8057. }
  8058. return x > 0 ? 1 : -1;
  8059. };
  8060. helpers$1.log10 = Math.log10 ?
  8061. function(x) {
  8062. return Math.log10(x);
  8063. } :
  8064. function(x) {
  8065. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  8066. // Check for whole powers of 10,
  8067. // which due to floating point rounding error should be corrected.
  8068. var powerOf10 = Math.round(exponent);
  8069. var isPowerOf10 = x === Math.pow(10, powerOf10);
  8070. return isPowerOf10 ? powerOf10 : exponent;
  8071. };
  8072. helpers$1.toRadians = function(degrees) {
  8073. return degrees * (Math.PI / 180);
  8074. };
  8075. helpers$1.toDegrees = function(radians) {
  8076. return radians * (180 / Math.PI);
  8077. };
  8078. /**
  8079. * Returns the number of decimal places
  8080. * i.e. the number of digits after the decimal point, of the value of this Number.
  8081. * @param {number} x - A number.
  8082. * @returns {number} The number of decimal places.
  8083. * @private
  8084. */
  8085. helpers$1._decimalPlaces = function(x) {
  8086. if (!helpers$1.isFinite(x)) {
  8087. return;
  8088. }
  8089. var e = 1;
  8090. var p = 0;
  8091. while (Math.round(x * e) / e !== x) {
  8092. e *= 10;
  8093. p++;
  8094. }
  8095. return p;
  8096. };
  8097. // Gets the angle from vertical upright to the point about a centre.
  8098. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  8099. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8100. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8101. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8102. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8103. if (angle < (-0.5 * Math.PI)) {
  8104. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8105. }
  8106. return {
  8107. angle: angle,
  8108. distance: radialDistanceFromCenter
  8109. };
  8110. };
  8111. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  8112. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8113. };
  8114. /**
  8115. * Provided for backward compatibility, not available anymore
  8116. * @function Chart.helpers.aliasPixel
  8117. * @deprecated since version 2.8.0
  8118. * @todo remove at version 3
  8119. */
  8120. helpers$1.aliasPixel = function(pixelWidth) {
  8121. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8122. };
  8123. /**
  8124. * Returns the aligned pixel value to avoid anti-aliasing blur
  8125. * @param {Chart} chart - The chart instance.
  8126. * @param {number} pixel - A pixel value.
  8127. * @param {number} width - The width of the element.
  8128. * @returns {number} The aligned pixel value.
  8129. * @private
  8130. */
  8131. helpers$1._alignPixel = function(chart, pixel, width) {
  8132. var devicePixelRatio = chart.currentDevicePixelRatio;
  8133. var halfWidth = width / 2;
  8134. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8135. };
  8136. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8137. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8138. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8139. // This function must also respect "skipped" points
  8140. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8141. var current = middlePoint;
  8142. var next = afterPoint.skip ? middlePoint : afterPoint;
  8143. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8144. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8145. var s01 = d01 / (d01 + d12);
  8146. var s12 = d12 / (d01 + d12);
  8147. // If all points are the same, s01 & s02 will be inf
  8148. s01 = isNaN(s01) ? 0 : s01;
  8149. s12 = isNaN(s12) ? 0 : s12;
  8150. var fa = t * s01; // scaling factor for triangle Ta
  8151. var fb = t * s12;
  8152. return {
  8153. previous: {
  8154. x: current.x - fa * (next.x - previous.x),
  8155. y: current.y - fa * (next.y - previous.y)
  8156. },
  8157. next: {
  8158. x: current.x + fb * (next.x - previous.x),
  8159. y: current.y + fb * (next.y - previous.y)
  8160. }
  8161. };
  8162. };
  8163. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  8164. helpers$1.splineCurveMonotone = function(points) {
  8165. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8166. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8167. // between the dataset discrete points due to the interpolation.
  8168. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8169. var pointsWithTangents = (points || []).map(function(point) {
  8170. return {
  8171. model: point._model,
  8172. deltaK: 0,
  8173. mK: 0
  8174. };
  8175. });
  8176. // Calculate slopes (deltaK) and initialize tangents (mK)
  8177. var pointsLen = pointsWithTangents.length;
  8178. var i, pointBefore, pointCurrent, pointAfter;
  8179. for (i = 0; i < pointsLen; ++i) {
  8180. pointCurrent = pointsWithTangents[i];
  8181. if (pointCurrent.model.skip) {
  8182. continue;
  8183. }
  8184. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8185. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8186. if (pointAfter && !pointAfter.model.skip) {
  8187. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8188. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  8189. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  8190. }
  8191. if (!pointBefore || pointBefore.model.skip) {
  8192. pointCurrent.mK = pointCurrent.deltaK;
  8193. } else if (!pointAfter || pointAfter.model.skip) {
  8194. pointCurrent.mK = pointBefore.deltaK;
  8195. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  8196. pointCurrent.mK = 0;
  8197. } else {
  8198. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  8199. }
  8200. }
  8201. // Adjust tangents to ensure monotonic properties
  8202. var alphaK, betaK, tauK, squaredMagnitude;
  8203. for (i = 0; i < pointsLen - 1; ++i) {
  8204. pointCurrent = pointsWithTangents[i];
  8205. pointAfter = pointsWithTangents[i + 1];
  8206. if (pointCurrent.model.skip || pointAfter.model.skip) {
  8207. continue;
  8208. }
  8209. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  8210. pointCurrent.mK = pointAfter.mK = 0;
  8211. continue;
  8212. }
  8213. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  8214. betaK = pointAfter.mK / pointCurrent.deltaK;
  8215. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  8216. if (squaredMagnitude <= 9) {
  8217. continue;
  8218. }
  8219. tauK = 3 / Math.sqrt(squaredMagnitude);
  8220. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  8221. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  8222. }
  8223. // Compute control points
  8224. var deltaX;
  8225. for (i = 0; i < pointsLen; ++i) {
  8226. pointCurrent = pointsWithTangents[i];
  8227. if (pointCurrent.model.skip) {
  8228. continue;
  8229. }
  8230. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8231. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8232. if (pointBefore && !pointBefore.model.skip) {
  8233. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  8234. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  8235. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  8236. }
  8237. if (pointAfter && !pointAfter.model.skip) {
  8238. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  8239. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  8240. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  8241. }
  8242. }
  8243. };
  8244. helpers$1.nextItem = function(collection, index, loop) {
  8245. if (loop) {
  8246. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  8247. }
  8248. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  8249. };
  8250. helpers$1.previousItem = function(collection, index, loop) {
  8251. if (loop) {
  8252. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  8253. }
  8254. return index <= 0 ? collection[0] : collection[index - 1];
  8255. };
  8256. // Implementation of the nice number algorithm used in determining where axis labels will go
  8257. helpers$1.niceNum = function(range, round) {
  8258. var exponent = Math.floor(helpers$1.log10(range));
  8259. var fraction = range / Math.pow(10, exponent);
  8260. var niceFraction;
  8261. if (round) {
  8262. if (fraction < 1.5) {
  8263. niceFraction = 1;
  8264. } else if (fraction < 3) {
  8265. niceFraction = 2;
  8266. } else if (fraction < 7) {
  8267. niceFraction = 5;
  8268. } else {
  8269. niceFraction = 10;
  8270. }
  8271. } else if (fraction <= 1.0) {
  8272. niceFraction = 1;
  8273. } else if (fraction <= 2) {
  8274. niceFraction = 2;
  8275. } else if (fraction <= 5) {
  8276. niceFraction = 5;
  8277. } else {
  8278. niceFraction = 10;
  8279. }
  8280. return niceFraction * Math.pow(10, exponent);
  8281. };
  8282. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  8283. helpers$1.requestAnimFrame = (function() {
  8284. if (typeof window === 'undefined') {
  8285. return function(callback) {
  8286. callback();
  8287. };
  8288. }
  8289. return window.requestAnimationFrame ||
  8290. window.webkitRequestAnimationFrame ||
  8291. window.mozRequestAnimationFrame ||
  8292. window.oRequestAnimationFrame ||
  8293. window.msRequestAnimationFrame ||
  8294. function(callback) {
  8295. return window.setTimeout(callback, 1000 / 60);
  8296. };
  8297. }());
  8298. // -- DOM methods
  8299. helpers$1.getRelativePosition = function(evt, chart) {
  8300. var mouseX, mouseY;
  8301. var e = evt.originalEvent || evt;
  8302. var canvas = evt.target || evt.srcElement;
  8303. var boundingRect = canvas.getBoundingClientRect();
  8304. var touches = e.touches;
  8305. if (touches && touches.length > 0) {
  8306. mouseX = touches[0].clientX;
  8307. mouseY = touches[0].clientY;
  8308. } else {
  8309. mouseX = e.clientX;
  8310. mouseY = e.clientY;
  8311. }
  8312. // Scale mouse coordinates into canvas coordinates
  8313. // by following the pattern laid out by 'jerryj' in the comments of
  8314. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  8315. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  8316. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  8317. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  8318. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  8319. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  8320. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  8321. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  8322. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  8323. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  8324. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  8325. return {
  8326. x: mouseX,
  8327. y: mouseY
  8328. };
  8329. };
  8330. // Private helper function to convert max-width/max-height values that may be percentages into a number
  8331. function parseMaxStyle(styleValue, node, parentProperty) {
  8332. var valueInPixels;
  8333. if (typeof styleValue === 'string') {
  8334. valueInPixels = parseInt(styleValue, 10);
  8335. if (styleValue.indexOf('%') !== -1) {
  8336. // percentage * size in dimension
  8337. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  8338. }
  8339. } else {
  8340. valueInPixels = styleValue;
  8341. }
  8342. return valueInPixels;
  8343. }
  8344. /**
  8345. * Returns if the given value contains an effective constraint.
  8346. * @private
  8347. */
  8348. function isConstrainedValue(value) {
  8349. return value !== undefined && value !== null && value !== 'none';
  8350. }
  8351. /**
  8352. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  8353. * @param {HTMLElement} domNode - the node to check the constraint on
  8354. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  8355. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  8356. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  8357. */
  8358. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  8359. var view = document.defaultView;
  8360. var parentNode = helpers$1._getParentNode(domNode);
  8361. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  8362. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  8363. var hasCNode = isConstrainedValue(constrainedNode);
  8364. var hasCContainer = isConstrainedValue(constrainedContainer);
  8365. var infinity = Number.POSITIVE_INFINITY;
  8366. if (hasCNode || hasCContainer) {
  8367. return Math.min(
  8368. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  8369. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  8370. }
  8371. return 'none';
  8372. }
  8373. // returns Number or undefined if no constraint
  8374. helpers$1.getConstraintWidth = function(domNode) {
  8375. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  8376. };
  8377. // returns Number or undefined if no constraint
  8378. helpers$1.getConstraintHeight = function(domNode) {
  8379. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  8380. };
  8381. /**
  8382. * @private
  8383. */
  8384. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  8385. padding = helpers$1.getStyle(container, padding);
  8386. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  8387. };
  8388. /**
  8389. * @private
  8390. */
  8391. helpers$1._getParentNode = function(domNode) {
  8392. var parent = domNode.parentNode;
  8393. if (parent && parent.toString() === '[object ShadowRoot]') {
  8394. parent = parent.host;
  8395. }
  8396. return parent;
  8397. };
  8398. helpers$1.getMaximumWidth = function(domNode) {
  8399. var container = helpers$1._getParentNode(domNode);
  8400. if (!container) {
  8401. return domNode.clientWidth;
  8402. }
  8403. var clientWidth = container.clientWidth;
  8404. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  8405. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  8406. var w = clientWidth - paddingLeft - paddingRight;
  8407. var cw = helpers$1.getConstraintWidth(domNode);
  8408. return isNaN(cw) ? w : Math.min(w, cw);
  8409. };
  8410. helpers$1.getMaximumHeight = function(domNode) {
  8411. var container = helpers$1._getParentNode(domNode);
  8412. if (!container) {
  8413. return domNode.clientHeight;
  8414. }
  8415. var clientHeight = container.clientHeight;
  8416. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  8417. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  8418. var h = clientHeight - paddingTop - paddingBottom;
  8419. var ch = helpers$1.getConstraintHeight(domNode);
  8420. return isNaN(ch) ? h : Math.min(h, ch);
  8421. };
  8422. helpers$1.getStyle = function(el, property) {
  8423. return el.currentStyle ?
  8424. el.currentStyle[property] :
  8425. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  8426. };
  8427. helpers$1.retinaScale = function(chart, forceRatio) {
  8428. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  8429. if (pixelRatio === 1) {
  8430. return;
  8431. }
  8432. var canvas = chart.canvas;
  8433. var height = chart.height;
  8434. var width = chart.width;
  8435. canvas.height = height * pixelRatio;
  8436. canvas.width = width * pixelRatio;
  8437. chart.ctx.scale(pixelRatio, pixelRatio);
  8438. // If no style has been set on the canvas, the render size is used as display size,
  8439. // making the chart visually bigger, so let's enforce it to the "correct" values.
  8440. // See https://github.com/chartjs/Chart.js/issues/3575
  8441. if (!canvas.style.height && !canvas.style.width) {
  8442. canvas.style.height = height + 'px';
  8443. canvas.style.width = width + 'px';
  8444. }
  8445. };
  8446. // -- Canvas methods
  8447. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  8448. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  8449. };
  8450. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  8451. cache = cache || {};
  8452. var data = cache.data = cache.data || {};
  8453. var gc = cache.garbageCollect = cache.garbageCollect || [];
  8454. if (cache.font !== font) {
  8455. data = cache.data = {};
  8456. gc = cache.garbageCollect = [];
  8457. cache.font = font;
  8458. }
  8459. ctx.font = font;
  8460. var longest = 0;
  8461. helpers$1.each(arrayOfThings, function(thing) {
  8462. // Undefined strings and arrays should not be measured
  8463. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  8464. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  8465. } else if (helpers$1.isArray(thing)) {
  8466. // if it is an array lets measure each element
  8467. // to do maybe simplify this function a bit so we can do this more recursively?
  8468. helpers$1.each(thing, function(nestedThing) {
  8469. // Undefined strings and arrays should not be measured
  8470. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  8471. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  8472. }
  8473. });
  8474. }
  8475. });
  8476. var gcLen = gc.length / 2;
  8477. if (gcLen > arrayOfThings.length) {
  8478. for (var i = 0; i < gcLen; i++) {
  8479. delete data[gc[i]];
  8480. }
  8481. gc.splice(0, gcLen);
  8482. }
  8483. return longest;
  8484. };
  8485. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  8486. var textWidth = data[string];
  8487. if (!textWidth) {
  8488. textWidth = data[string] = ctx.measureText(string).width;
  8489. gc.push(string);
  8490. }
  8491. if (textWidth > longest) {
  8492. longest = textWidth;
  8493. }
  8494. return longest;
  8495. };
  8496. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  8497. var numberOfLines = 1;
  8498. helpers$1.each(arrayOfThings, function(thing) {
  8499. if (helpers$1.isArray(thing)) {
  8500. if (thing.length > numberOfLines) {
  8501. numberOfLines = thing.length;
  8502. }
  8503. }
  8504. });
  8505. return numberOfLines;
  8506. };
  8507. helpers$1.color = !chartjsColor ?
  8508. function(value) {
  8509. console.error('Color.js not found!');
  8510. return value;
  8511. } :
  8512. function(value) {
  8513. /* global CanvasGradient */
  8514. if (value instanceof CanvasGradient) {
  8515. value = core_defaults.global.defaultColor;
  8516. }
  8517. return chartjsColor(value);
  8518. };
  8519. helpers$1.getHoverColor = function(colorValue) {
  8520. /* global CanvasPattern */
  8521. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  8522. colorValue :
  8523. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  8524. };
  8525. };
  8526. function abstract() {
  8527. throw new Error(
  8528. 'This method is not implemented: either no adapter can ' +
  8529. 'be found or an incomplete integration was provided.'
  8530. );
  8531. }
  8532. /**
  8533. * Date adapter (current used by the time scale)
  8534. * @namespace Chart._adapters._date
  8535. * @memberof Chart._adapters
  8536. * @private
  8537. */
  8538. /**
  8539. * Currently supported unit string values.
  8540. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  8541. * @memberof Chart._adapters._date
  8542. * @name Unit
  8543. */
  8544. /**
  8545. * @class
  8546. */
  8547. function DateAdapter(options) {
  8548. this.options = options || {};
  8549. }
  8550. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  8551. /**
  8552. * Returns a map of time formats for the supported formatting units defined
  8553. * in Unit as well as 'datetime' representing a detailed date/time string.
  8554. * @returns {{string: string}}
  8555. */
  8556. formats: abstract,
  8557. /**
  8558. * Parses the given `value` and return the associated timestamp.
  8559. * @param {any} value - the value to parse (usually comes from the data)
  8560. * @param {string} [format] - the expected data format
  8561. * @returns {(number|null)}
  8562. * @function
  8563. */
  8564. parse: abstract,
  8565. /**
  8566. * Returns the formatted date in the specified `format` for a given `timestamp`.
  8567. * @param {number} timestamp - the timestamp to format
  8568. * @param {string} format - the date/time token
  8569. * @return {string}
  8570. * @function
  8571. */
  8572. format: abstract,
  8573. /**
  8574. * Adds the specified `amount` of `unit` to the given `timestamp`.
  8575. * @param {number} timestamp - the input timestamp
  8576. * @param {number} amount - the amount to add
  8577. * @param {Unit} unit - the unit as string
  8578. * @return {number}
  8579. * @function
  8580. */
  8581. add: abstract,
  8582. /**
  8583. * Returns the number of `unit` between the given timestamps.
  8584. * @param {number} max - the input timestamp (reference)
  8585. * @param {number} min - the timestamp to substract
  8586. * @param {Unit} unit - the unit as string
  8587. * @return {number}
  8588. * @function
  8589. */
  8590. diff: abstract,
  8591. /**
  8592. * Returns start of `unit` for the given `timestamp`.
  8593. * @param {number} timestamp - the input timestamp
  8594. * @param {Unit} unit - the unit as string
  8595. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  8596. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  8597. * @function
  8598. */
  8599. startOf: abstract,
  8600. /**
  8601. * Returns end of `unit` for the given `timestamp`.
  8602. * @param {number} timestamp - the input timestamp
  8603. * @param {Unit} unit - the unit as string
  8604. * @function
  8605. */
  8606. endOf: abstract,
  8607. // DEPRECATIONS
  8608. /**
  8609. * Provided for backward compatibility for scale.getValueForPixel(),
  8610. * this method should be overridden only by the moment adapter.
  8611. * @deprecated since version 2.8.0
  8612. * @todo remove at version 3
  8613. * @private
  8614. */
  8615. _create: function(value) {
  8616. return value;
  8617. }
  8618. });
  8619. DateAdapter.override = function(members) {
  8620. helpers$1.extend(DateAdapter.prototype, members);
  8621. };
  8622. var _date = DateAdapter;
  8623. var core_adapters = {
  8624. _date: _date
  8625. };
  8626. /**
  8627. * Namespace to hold static tick generation functions
  8628. * @namespace Chart.Ticks
  8629. */
  8630. var core_ticks = {
  8631. /**
  8632. * Namespace to hold formatters for different types of ticks
  8633. * @namespace Chart.Ticks.formatters
  8634. */
  8635. formatters: {
  8636. /**
  8637. * Formatter for value labels
  8638. * @method Chart.Ticks.formatters.values
  8639. * @param value the value to display
  8640. * @return {string|string[]} the label to display
  8641. */
  8642. values: function(value) {
  8643. return helpers$1.isArray(value) ? value : '' + value;
  8644. },
  8645. /**
  8646. * Formatter for linear numeric ticks
  8647. * @method Chart.Ticks.formatters.linear
  8648. * @param tickValue {number} the value to be formatted
  8649. * @param index {number} the position of the tickValue parameter in the ticks array
  8650. * @param ticks {number[]} the list of ticks being converted
  8651. * @return {string} string representation of the tickValue parameter
  8652. */
  8653. linear: function(tickValue, index, ticks) {
  8654. // If we have lots of ticks, don't use the ones
  8655. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  8656. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  8657. if (Math.abs(delta) > 1) {
  8658. if (tickValue !== Math.floor(tickValue)) {
  8659. // not an integer
  8660. delta = tickValue - Math.floor(tickValue);
  8661. }
  8662. }
  8663. var logDelta = helpers$1.log10(Math.abs(delta));
  8664. var tickString = '';
  8665. if (tickValue !== 0) {
  8666. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  8667. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  8668. var logTick = helpers$1.log10(Math.abs(tickValue));
  8669. tickString = tickValue.toExponential(Math.floor(logTick) - Math.floor(logDelta));
  8670. } else {
  8671. var numDecimal = -1 * Math.floor(logDelta);
  8672. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  8673. tickString = tickValue.toFixed(numDecimal);
  8674. }
  8675. } else {
  8676. tickString = '0'; // never show decimal places for 0
  8677. }
  8678. return tickString;
  8679. },
  8680. logarithmic: function(tickValue, index, ticks) {
  8681. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  8682. if (tickValue === 0) {
  8683. return '0';
  8684. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  8685. return tickValue.toExponential();
  8686. }
  8687. return '';
  8688. }
  8689. }
  8690. };
  8691. var valueOrDefault$9 = helpers$1.valueOrDefault;
  8692. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  8693. core_defaults._set('scale', {
  8694. display: true,
  8695. position: 'left',
  8696. offset: false,
  8697. // grid line settings
  8698. gridLines: {
  8699. display: true,
  8700. color: 'rgba(0, 0, 0, 0.1)',
  8701. lineWidth: 1,
  8702. drawBorder: true,
  8703. drawOnChartArea: true,
  8704. drawTicks: true,
  8705. tickMarkLength: 10,
  8706. zeroLineWidth: 1,
  8707. zeroLineColor: 'rgba(0,0,0,0.25)',
  8708. zeroLineBorderDash: [],
  8709. zeroLineBorderDashOffset: 0.0,
  8710. offsetGridLines: false,
  8711. borderDash: [],
  8712. borderDashOffset: 0.0
  8713. },
  8714. // scale label
  8715. scaleLabel: {
  8716. // display property
  8717. display: false,
  8718. // actual label
  8719. labelString: '',
  8720. // top/bottom padding
  8721. padding: {
  8722. top: 4,
  8723. bottom: 4
  8724. }
  8725. },
  8726. // label settings
  8727. ticks: {
  8728. beginAtZero: false,
  8729. minRotation: 0,
  8730. maxRotation: 50,
  8731. mirror: false,
  8732. padding: 0,
  8733. reverse: false,
  8734. display: true,
  8735. autoSkip: true,
  8736. autoSkipPadding: 0,
  8737. labelOffset: 0,
  8738. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  8739. callback: core_ticks.formatters.values,
  8740. minor: {},
  8741. major: {}
  8742. }
  8743. });
  8744. function labelsFromTicks(ticks) {
  8745. var labels = [];
  8746. var i, ilen;
  8747. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  8748. labels.push(ticks[i].label);
  8749. }
  8750. return labels;
  8751. }
  8752. function getPixelForGridLine(scale, index, offsetGridLines) {
  8753. var lineValue = scale.getPixelForTick(index);
  8754. if (offsetGridLines) {
  8755. if (scale.getTicks().length === 1) {
  8756. lineValue -= scale.isHorizontal() ?
  8757. Math.max(lineValue - scale.left, scale.right - lineValue) :
  8758. Math.max(lineValue - scale.top, scale.bottom - lineValue);
  8759. } else if (index === 0) {
  8760. lineValue -= (scale.getPixelForTick(1) - lineValue) / 2;
  8761. } else {
  8762. lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2;
  8763. }
  8764. }
  8765. return lineValue;
  8766. }
  8767. function computeTextSize(context, tick, font) {
  8768. return helpers$1.isArray(tick) ?
  8769. helpers$1.longestText(context, font, tick) :
  8770. context.measureText(tick).width;
  8771. }
  8772. var core_scale = core_element.extend({
  8773. /**
  8774. * Get the padding needed for the scale
  8775. * @method getPadding
  8776. * @private
  8777. * @returns {Padding} the necessary padding
  8778. */
  8779. getPadding: function() {
  8780. var me = this;
  8781. return {
  8782. left: me.paddingLeft || 0,
  8783. top: me.paddingTop || 0,
  8784. right: me.paddingRight || 0,
  8785. bottom: me.paddingBottom || 0
  8786. };
  8787. },
  8788. /**
  8789. * Returns the scale tick objects ({label, major})
  8790. * @since 2.7
  8791. */
  8792. getTicks: function() {
  8793. return this._ticks;
  8794. },
  8795. // These methods are ordered by lifecyle. Utilities then follow.
  8796. // Any function defined here is inherited by all scale types.
  8797. // Any function can be extended by the scale type
  8798. mergeTicksOptions: function() {
  8799. var ticks = this.options.ticks;
  8800. if (ticks.minor === false) {
  8801. ticks.minor = {
  8802. display: false
  8803. };
  8804. }
  8805. if (ticks.major === false) {
  8806. ticks.major = {
  8807. display: false
  8808. };
  8809. }
  8810. for (var key in ticks) {
  8811. if (key !== 'major' && key !== 'minor') {
  8812. if (typeof ticks.minor[key] === 'undefined') {
  8813. ticks.minor[key] = ticks[key];
  8814. }
  8815. if (typeof ticks.major[key] === 'undefined') {
  8816. ticks.major[key] = ticks[key];
  8817. }
  8818. }
  8819. }
  8820. },
  8821. beforeUpdate: function() {
  8822. helpers$1.callback(this.options.beforeUpdate, [this]);
  8823. },
  8824. update: function(maxWidth, maxHeight, margins) {
  8825. var me = this;
  8826. var i, ilen, labels, label, ticks, tick;
  8827. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  8828. me.beforeUpdate();
  8829. // Absorb the master measurements
  8830. me.maxWidth = maxWidth;
  8831. me.maxHeight = maxHeight;
  8832. me.margins = helpers$1.extend({
  8833. left: 0,
  8834. right: 0,
  8835. top: 0,
  8836. bottom: 0
  8837. }, margins);
  8838. me._maxLabelLines = 0;
  8839. me.longestLabelWidth = 0;
  8840. me.longestTextCache = me.longestTextCache || {};
  8841. // Dimensions
  8842. me.beforeSetDimensions();
  8843. me.setDimensions();
  8844. me.afterSetDimensions();
  8845. // Data min/max
  8846. me.beforeDataLimits();
  8847. me.determineDataLimits();
  8848. me.afterDataLimits();
  8849. // Ticks - `this.ticks` is now DEPRECATED!
  8850. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  8851. // and must not be accessed directly from outside this class. `this.ticks` being
  8852. // around for long time and not marked as private, we can't change its structure
  8853. // without unexpected breaking changes. If you need to access the scale ticks,
  8854. // use scale.getTicks() instead.
  8855. me.beforeBuildTicks();
  8856. // New implementations should return an array of objects but for BACKWARD COMPAT,
  8857. // we still support no return (`this.ticks` internally set by calling this method).
  8858. ticks = me.buildTicks() || [];
  8859. // Allow modification of ticks in callback.
  8860. ticks = me.afterBuildTicks(ticks) || ticks;
  8861. me.beforeTickToLabelConversion();
  8862. // New implementations should return the formatted tick labels but for BACKWARD
  8863. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  8864. // this method and supposed to contain only string values).
  8865. labels = me.convertTicksToLabels(ticks) || me.ticks;
  8866. me.afterTickToLabelConversion();
  8867. me.ticks = labels; // BACKWARD COMPATIBILITY
  8868. // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change!
  8869. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  8870. for (i = 0, ilen = labels.length; i < ilen; ++i) {
  8871. label = labels[i];
  8872. tick = ticks[i];
  8873. if (!tick) {
  8874. ticks.push(tick = {
  8875. label: label,
  8876. major: false
  8877. });
  8878. } else {
  8879. tick.label = label;
  8880. }
  8881. }
  8882. me._ticks = ticks;
  8883. // Tick Rotation
  8884. me.beforeCalculateTickRotation();
  8885. me.calculateTickRotation();
  8886. me.afterCalculateTickRotation();
  8887. // Fit
  8888. me.beforeFit();
  8889. me.fit();
  8890. me.afterFit();
  8891. //
  8892. me.afterUpdate();
  8893. return me.minSize;
  8894. },
  8895. afterUpdate: function() {
  8896. helpers$1.callback(this.options.afterUpdate, [this]);
  8897. },
  8898. //
  8899. beforeSetDimensions: function() {
  8900. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  8901. },
  8902. setDimensions: function() {
  8903. var me = this;
  8904. // Set the unconstrained dimension before label rotation
  8905. if (me.isHorizontal()) {
  8906. // Reset position before calculating rotation
  8907. me.width = me.maxWidth;
  8908. me.left = 0;
  8909. me.right = me.width;
  8910. } else {
  8911. me.height = me.maxHeight;
  8912. // Reset position before calculating rotation
  8913. me.top = 0;
  8914. me.bottom = me.height;
  8915. }
  8916. // Reset padding
  8917. me.paddingLeft = 0;
  8918. me.paddingTop = 0;
  8919. me.paddingRight = 0;
  8920. me.paddingBottom = 0;
  8921. },
  8922. afterSetDimensions: function() {
  8923. helpers$1.callback(this.options.afterSetDimensions, [this]);
  8924. },
  8925. // Data limits
  8926. beforeDataLimits: function() {
  8927. helpers$1.callback(this.options.beforeDataLimits, [this]);
  8928. },
  8929. determineDataLimits: helpers$1.noop,
  8930. afterDataLimits: function() {
  8931. helpers$1.callback(this.options.afterDataLimits, [this]);
  8932. },
  8933. //
  8934. beforeBuildTicks: function() {
  8935. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  8936. },
  8937. buildTicks: helpers$1.noop,
  8938. afterBuildTicks: function(ticks) {
  8939. var me = this;
  8940. // ticks is empty for old axis implementations here
  8941. if (helpers$1.isArray(ticks) && ticks.length) {
  8942. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  8943. }
  8944. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  8945. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  8946. return ticks;
  8947. },
  8948. beforeTickToLabelConversion: function() {
  8949. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  8950. },
  8951. convertTicksToLabels: function() {
  8952. var me = this;
  8953. // Convert ticks to strings
  8954. var tickOpts = me.options.ticks;
  8955. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  8956. },
  8957. afterTickToLabelConversion: function() {
  8958. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  8959. },
  8960. //
  8961. beforeCalculateTickRotation: function() {
  8962. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  8963. },
  8964. calculateTickRotation: function() {
  8965. var me = this;
  8966. var context = me.ctx;
  8967. var tickOpts = me.options.ticks;
  8968. var labels = labelsFromTicks(me._ticks);
  8969. // Get the width of each grid by calculating the difference
  8970. // between x offsets between 0 and 1.
  8971. var tickFont = helpers$1.options._parseFont(tickOpts);
  8972. context.font = tickFont.string;
  8973. var labelRotation = tickOpts.minRotation || 0;
  8974. if (labels.length && me.options.display && me.isHorizontal()) {
  8975. var originalLabelWidth = helpers$1.longestText(context, tickFont.string, labels, me.longestTextCache);
  8976. var labelWidth = originalLabelWidth;
  8977. var cosRotation, sinRotation;
  8978. // Allow 3 pixels x2 padding either side for label readability
  8979. var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
  8980. // Max label rotation can be set or default to 90 - also act as a loop counter
  8981. while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {
  8982. var angleRadians = helpers$1.toRadians(labelRotation);
  8983. cosRotation = Math.cos(angleRadians);
  8984. sinRotation = Math.sin(angleRadians);
  8985. if (sinRotation * originalLabelWidth > me.maxHeight) {
  8986. // go back one step
  8987. labelRotation--;
  8988. break;
  8989. }
  8990. labelRotation++;
  8991. labelWidth = cosRotation * originalLabelWidth;
  8992. }
  8993. }
  8994. me.labelRotation = labelRotation;
  8995. },
  8996. afterCalculateTickRotation: function() {
  8997. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  8998. },
  8999. //
  9000. beforeFit: function() {
  9001. helpers$1.callback(this.options.beforeFit, [this]);
  9002. },
  9003. fit: function() {
  9004. var me = this;
  9005. // Reset
  9006. var minSize = me.minSize = {
  9007. width: 0,
  9008. height: 0
  9009. };
  9010. var labels = labelsFromTicks(me._ticks);
  9011. var opts = me.options;
  9012. var tickOpts = opts.ticks;
  9013. var scaleLabelOpts = opts.scaleLabel;
  9014. var gridLineOpts = opts.gridLines;
  9015. var display = me._isVisible();
  9016. var position = opts.position;
  9017. var isHorizontal = me.isHorizontal();
  9018. var parseFont = helpers$1.options._parseFont;
  9019. var tickFont = parseFont(tickOpts);
  9020. var tickMarkLength = opts.gridLines.tickMarkLength;
  9021. // Width
  9022. if (isHorizontal) {
  9023. // subtract the margins to line up with the chartArea if we are a full width scale
  9024. minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
  9025. } else {
  9026. minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
  9027. }
  9028. // height
  9029. if (isHorizontal) {
  9030. minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
  9031. } else {
  9032. minSize.height = me.maxHeight; // fill all the height
  9033. }
  9034. // Are we showing a title for the scale?
  9035. if (scaleLabelOpts.display && display) {
  9036. var scaleLabelFont = parseFont(scaleLabelOpts);
  9037. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabelOpts.padding);
  9038. var deltaHeight = scaleLabelFont.lineHeight + scaleLabelPadding.height;
  9039. if (isHorizontal) {
  9040. minSize.height += deltaHeight;
  9041. } else {
  9042. minSize.width += deltaHeight;
  9043. }
  9044. }
  9045. // Don't bother fitting the ticks if we are not showing the labels
  9046. if (tickOpts.display && display) {
  9047. var largestTextWidth = helpers$1.longestText(me.ctx, tickFont.string, labels, me.longestTextCache);
  9048. var tallestLabelHeightInLines = helpers$1.numberOfLabelLines(labels);
  9049. var lineSpace = tickFont.size * 0.5;
  9050. var tickPadding = me.options.ticks.padding;
  9051. // Store max number of lines and widest label for _autoSkip
  9052. me._maxLabelLines = tallestLabelHeightInLines;
  9053. me.longestLabelWidth = largestTextWidth;
  9054. if (isHorizontal) {
  9055. var angleRadians = helpers$1.toRadians(me.labelRotation);
  9056. var cosRotation = Math.cos(angleRadians);
  9057. var sinRotation = Math.sin(angleRadians);
  9058. // TODO - improve this calculation
  9059. var labelHeight = (sinRotation * largestTextWidth)
  9060. + (tickFont.lineHeight * tallestLabelHeightInLines)
  9061. + lineSpace; // padding
  9062. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  9063. me.ctx.font = tickFont.string;
  9064. var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.string);
  9065. var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.string);
  9066. var offsetLeft = me.getPixelForTick(0) - me.left;
  9067. var offsetRight = me.right - me.getPixelForTick(labels.length - 1);
  9068. var paddingLeft, paddingRight;
  9069. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  9070. // which means that the right padding is dominated by the font height
  9071. if (me.labelRotation !== 0) {
  9072. paddingLeft = position === 'bottom' ? (cosRotation * firstLabelWidth) : (cosRotation * lineSpace);
  9073. paddingRight = position === 'bottom' ? (cosRotation * lineSpace) : (cosRotation * lastLabelWidth);
  9074. } else {
  9075. paddingLeft = firstLabelWidth / 2;
  9076. paddingRight = lastLabelWidth / 2;
  9077. }
  9078. me.paddingLeft = Math.max(paddingLeft - offsetLeft, 0) + 3; // add 3 px to move away from canvas edges
  9079. me.paddingRight = Math.max(paddingRight - offsetRight, 0) + 3;
  9080. } else {
  9081. // A vertical axis is more constrained by the width. Labels are the
  9082. // dominant factor here, so get that length first and account for padding
  9083. if (tickOpts.mirror) {
  9084. largestTextWidth = 0;
  9085. } else {
  9086. // use lineSpace for consistency with horizontal axis
  9087. // tickPadding is not implemented for horizontal
  9088. largestTextWidth += tickPadding + lineSpace;
  9089. }
  9090. minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth);
  9091. me.paddingTop = tickFont.size / 2;
  9092. me.paddingBottom = tickFont.size / 2;
  9093. }
  9094. }
  9095. me.handleMargins();
  9096. me.width = minSize.width;
  9097. me.height = minSize.height;
  9098. },
  9099. /**
  9100. * Handle margins and padding interactions
  9101. * @private
  9102. */
  9103. handleMargins: function() {
  9104. var me = this;
  9105. if (me.margins) {
  9106. me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
  9107. me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
  9108. me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
  9109. me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
  9110. }
  9111. },
  9112. afterFit: function() {
  9113. helpers$1.callback(this.options.afterFit, [this]);
  9114. },
  9115. // Shared Methods
  9116. isHorizontal: function() {
  9117. return this.options.position === 'top' || this.options.position === 'bottom';
  9118. },
  9119. isFullWidth: function() {
  9120. return (this.options.fullWidth);
  9121. },
  9122. // 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
  9123. getRightValue: function(rawValue) {
  9124. // Null and undefined values first
  9125. if (helpers$1.isNullOrUndef(rawValue)) {
  9126. return NaN;
  9127. }
  9128. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  9129. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  9130. return NaN;
  9131. }
  9132. // If it is in fact an object, dive in one more level
  9133. if (rawValue) {
  9134. if (this.isHorizontal()) {
  9135. if (rawValue.x !== undefined) {
  9136. return this.getRightValue(rawValue.x);
  9137. }
  9138. } else if (rawValue.y !== undefined) {
  9139. return this.getRightValue(rawValue.y);
  9140. }
  9141. }
  9142. // Value is good, return it
  9143. return rawValue;
  9144. },
  9145. /**
  9146. * Used to get the value to display in the tooltip for the data at the given index
  9147. * @param index
  9148. * @param datasetIndex
  9149. */
  9150. getLabelForIndex: helpers$1.noop,
  9151. /**
  9152. * Returns the location of the given data point. Value can either be an index or a numerical value
  9153. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9154. * @param value
  9155. * @param index
  9156. * @param datasetIndex
  9157. */
  9158. getPixelForValue: helpers$1.noop,
  9159. /**
  9160. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  9161. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9162. * @param pixel
  9163. */
  9164. getValueForPixel: helpers$1.noop,
  9165. /**
  9166. * Returns the location of the tick at the given index
  9167. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9168. */
  9169. getPixelForTick: function(index) {
  9170. var me = this;
  9171. var offset = me.options.offset;
  9172. if (me.isHorizontal()) {
  9173. var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
  9174. var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
  9175. var pixel = (tickWidth * index) + me.paddingLeft;
  9176. if (offset) {
  9177. pixel += tickWidth / 2;
  9178. }
  9179. var finalVal = me.left + pixel;
  9180. finalVal += me.isFullWidth() ? me.margins.left : 0;
  9181. return finalVal;
  9182. }
  9183. var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
  9184. return me.top + (index * (innerHeight / (me._ticks.length - 1)));
  9185. },
  9186. /**
  9187. * Utility for getting the pixel location of a percentage of scale
  9188. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9189. */
  9190. getPixelForDecimal: function(decimal) {
  9191. var me = this;
  9192. if (me.isHorizontal()) {
  9193. var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
  9194. var valueOffset = (innerWidth * decimal) + me.paddingLeft;
  9195. var finalVal = me.left + valueOffset;
  9196. finalVal += me.isFullWidth() ? me.margins.left : 0;
  9197. return finalVal;
  9198. }
  9199. return me.top + (decimal * me.height);
  9200. },
  9201. /**
  9202. * Returns the pixel for the minimum chart value
  9203. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9204. */
  9205. getBasePixel: function() {
  9206. return this.getPixelForValue(this.getBaseValue());
  9207. },
  9208. getBaseValue: function() {
  9209. var me = this;
  9210. var min = me.min;
  9211. var max = me.max;
  9212. return me.beginAtZero ? 0 :
  9213. min < 0 && max < 0 ? max :
  9214. min > 0 && max > 0 ? min :
  9215. 0;
  9216. },
  9217. /**
  9218. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  9219. * @private
  9220. */
  9221. _autoSkip: function(ticks) {
  9222. var me = this;
  9223. var isHorizontal = me.isHorizontal();
  9224. var optionTicks = me.options.ticks.minor;
  9225. var tickCount = ticks.length;
  9226. var skipRatio = false;
  9227. var maxTicks = optionTicks.maxTicksLimit;
  9228. // Total space needed to display all ticks. First and last ticks are
  9229. // drawn as their center at end of axis, so tickCount-1
  9230. var ticksLength = me._tickSize() * (tickCount - 1);
  9231. // Axis length
  9232. var axisLength = isHorizontal
  9233. ? me.width - (me.paddingLeft + me.paddingRight)
  9234. : me.height - (me.paddingTop + me.PaddingBottom);
  9235. var result = [];
  9236. var i, tick;
  9237. if (ticksLength > axisLength) {
  9238. skipRatio = 1 + Math.floor(ticksLength / axisLength);
  9239. }
  9240. // if they defined a max number of optionTicks,
  9241. // increase skipRatio until that number is met
  9242. if (tickCount > maxTicks) {
  9243. skipRatio = Math.max(skipRatio, 1 + Math.floor(tickCount / maxTicks));
  9244. }
  9245. for (i = 0; i < tickCount; i++) {
  9246. tick = ticks[i];
  9247. if (skipRatio > 1 && i % skipRatio > 0) {
  9248. // leave tick in place but make sure it's not displayed (#4635)
  9249. delete tick.label;
  9250. }
  9251. result.push(tick);
  9252. }
  9253. return result;
  9254. },
  9255. /**
  9256. * @private
  9257. */
  9258. _tickSize: function() {
  9259. var me = this;
  9260. var isHorizontal = me.isHorizontal();
  9261. var optionTicks = me.options.ticks.minor;
  9262. // Calculate space needed by label in axis direction.
  9263. var rot = helpers$1.toRadians(me.labelRotation);
  9264. var cos = Math.abs(Math.cos(rot));
  9265. var sin = Math.abs(Math.sin(rot));
  9266. var padding = optionTicks.autoSkipPadding || 0;
  9267. var w = (me.longestLabelWidth + padding) || 0;
  9268. var tickFont = helpers$1.options._parseFont(optionTicks);
  9269. var h = (me._maxLabelLines * tickFont.lineHeight + padding) || 0;
  9270. // Calculate space needed for 1 tick in axis direction.
  9271. return isHorizontal
  9272. ? h * cos > w * sin ? w / cos : h / sin
  9273. : h * sin < w * cos ? h / cos : w / sin;
  9274. },
  9275. /**
  9276. * @private
  9277. */
  9278. _isVisible: function() {
  9279. var me = this;
  9280. var chart = me.chart;
  9281. var display = me.options.display;
  9282. var i, ilen, meta;
  9283. if (display !== 'auto') {
  9284. return !!display;
  9285. }
  9286. // When 'auto', the scale is visible if at least one associated dataset is visible.
  9287. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  9288. if (chart.isDatasetVisible(i)) {
  9289. meta = chart.getDatasetMeta(i);
  9290. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  9291. return true;
  9292. }
  9293. }
  9294. }
  9295. return false;
  9296. },
  9297. /**
  9298. * Actually draw the scale on the canvas
  9299. * @param {object} chartArea - the area of the chart to draw full grid lines on
  9300. */
  9301. draw: function(chartArea) {
  9302. var me = this;
  9303. var options = me.options;
  9304. if (!me._isVisible()) {
  9305. return;
  9306. }
  9307. var chart = me.chart;
  9308. var context = me.ctx;
  9309. var globalDefaults = core_defaults.global;
  9310. var defaultFontColor = globalDefaults.defaultFontColor;
  9311. var optionTicks = options.ticks.minor;
  9312. var optionMajorTicks = options.ticks.major || optionTicks;
  9313. var gridLines = options.gridLines;
  9314. var scaleLabel = options.scaleLabel;
  9315. var position = options.position;
  9316. var isRotated = me.labelRotation !== 0;
  9317. var isMirrored = optionTicks.mirror;
  9318. var isHorizontal = me.isHorizontal();
  9319. var parseFont = helpers$1.options._parseFont;
  9320. var ticks = optionTicks.display && optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks();
  9321. var tickFontColor = valueOrDefault$9(optionTicks.fontColor, defaultFontColor);
  9322. var tickFont = parseFont(optionTicks);
  9323. var lineHeight = tickFont.lineHeight;
  9324. var majorTickFontColor = valueOrDefault$9(optionMajorTicks.fontColor, defaultFontColor);
  9325. var majorTickFont = parseFont(optionMajorTicks);
  9326. var tickPadding = optionTicks.padding;
  9327. var labelOffset = optionTicks.labelOffset;
  9328. var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;
  9329. var scaleLabelFontColor = valueOrDefault$9(scaleLabel.fontColor, defaultFontColor);
  9330. var scaleLabelFont = parseFont(scaleLabel);
  9331. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  9332. var labelRotationRadians = helpers$1.toRadians(me.labelRotation);
  9333. var itemsToDraw = [];
  9334. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  9335. var alignPixel = helpers$1._alignPixel;
  9336. var borderValue, tickStart, tickEnd;
  9337. if (position === 'top') {
  9338. borderValue = alignPixel(chart, me.bottom, axisWidth);
  9339. tickStart = me.bottom - tl;
  9340. tickEnd = borderValue - axisWidth / 2;
  9341. } else if (position === 'bottom') {
  9342. borderValue = alignPixel(chart, me.top, axisWidth);
  9343. tickStart = borderValue + axisWidth / 2;
  9344. tickEnd = me.top + tl;
  9345. } else if (position === 'left') {
  9346. borderValue = alignPixel(chart, me.right, axisWidth);
  9347. tickStart = me.right - tl;
  9348. tickEnd = borderValue - axisWidth / 2;
  9349. } else {
  9350. borderValue = alignPixel(chart, me.left, axisWidth);
  9351. tickStart = borderValue + axisWidth / 2;
  9352. tickEnd = me.left + tl;
  9353. }
  9354. var epsilon = 0.0000001; // 0.0000001 is margin in pixels for Accumulated error.
  9355. helpers$1.each(ticks, function(tick, index) {
  9356. // autoskipper skipped this tick (#4635)
  9357. if (helpers$1.isNullOrUndef(tick.label)) {
  9358. return;
  9359. }
  9360. var label = tick.label;
  9361. var lineWidth, lineColor, borderDash, borderDashOffset;
  9362. if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) {
  9363. // Draw the first index specially
  9364. lineWidth = gridLines.zeroLineWidth;
  9365. lineColor = gridLines.zeroLineColor;
  9366. borderDash = gridLines.zeroLineBorderDash || [];
  9367. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  9368. } else {
  9369. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, index);
  9370. lineColor = valueAtIndexOrDefault(gridLines.color, index);
  9371. borderDash = gridLines.borderDash || [];
  9372. borderDashOffset = gridLines.borderDashOffset || 0.0;
  9373. }
  9374. // Common properties
  9375. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY, textOffset, textAlign;
  9376. var labelCount = helpers$1.isArray(label) ? label.length : 1;
  9377. var lineValue = getPixelForGridLine(me, index, gridLines.offsetGridLines);
  9378. if (isHorizontal) {
  9379. var labelYOffset = tl + tickPadding;
  9380. if (lineValue < me.left - epsilon) {
  9381. lineColor = 'rgba(0,0,0,0)';
  9382. }
  9383. tx1 = tx2 = x1 = x2 = alignPixel(chart, lineValue, lineWidth);
  9384. ty1 = tickStart;
  9385. ty2 = tickEnd;
  9386. labelX = me.getPixelForTick(index) + labelOffset; // x values for optionTicks (need to consider offsetLabel option)
  9387. if (position === 'top') {
  9388. y1 = alignPixel(chart, chartArea.top, axisWidth) + axisWidth / 2;
  9389. y2 = chartArea.bottom;
  9390. textOffset = ((!isRotated ? 0.5 : 1) - labelCount) * lineHeight;
  9391. textAlign = !isRotated ? 'center' : 'left';
  9392. labelY = me.bottom - labelYOffset;
  9393. } else {
  9394. y1 = chartArea.top;
  9395. y2 = alignPixel(chart, chartArea.bottom, axisWidth) - axisWidth / 2;
  9396. textOffset = (!isRotated ? 0.5 : 0) * lineHeight;
  9397. textAlign = !isRotated ? 'center' : 'right';
  9398. labelY = me.top + labelYOffset;
  9399. }
  9400. } else {
  9401. var labelXOffset = (isMirrored ? 0 : tl) + tickPadding;
  9402. if (lineValue < me.top - epsilon) {
  9403. lineColor = 'rgba(0,0,0,0)';
  9404. }
  9405. tx1 = tickStart;
  9406. tx2 = tickEnd;
  9407. ty1 = ty2 = y1 = y2 = alignPixel(chart, lineValue, lineWidth);
  9408. labelY = me.getPixelForTick(index) + labelOffset;
  9409. textOffset = (1 - labelCount) * lineHeight / 2;
  9410. if (position === 'left') {
  9411. x1 = alignPixel(chart, chartArea.left, axisWidth) + axisWidth / 2;
  9412. x2 = chartArea.right;
  9413. textAlign = isMirrored ? 'left' : 'right';
  9414. labelX = me.right - labelXOffset;
  9415. } else {
  9416. x1 = chartArea.left;
  9417. x2 = alignPixel(chart, chartArea.right, axisWidth) - axisWidth / 2;
  9418. textAlign = isMirrored ? 'right' : 'left';
  9419. labelX = me.left + labelXOffset;
  9420. }
  9421. }
  9422. itemsToDraw.push({
  9423. tx1: tx1,
  9424. ty1: ty1,
  9425. tx2: tx2,
  9426. ty2: ty2,
  9427. x1: x1,
  9428. y1: y1,
  9429. x2: x2,
  9430. y2: y2,
  9431. labelX: labelX,
  9432. labelY: labelY,
  9433. glWidth: lineWidth,
  9434. glColor: lineColor,
  9435. glBorderDash: borderDash,
  9436. glBorderDashOffset: borderDashOffset,
  9437. rotation: -1 * labelRotationRadians,
  9438. label: label,
  9439. major: tick.major,
  9440. textOffset: textOffset,
  9441. textAlign: textAlign
  9442. });
  9443. });
  9444. // Draw all of the tick labels, tick marks, and grid lines at the correct places
  9445. helpers$1.each(itemsToDraw, function(itemToDraw) {
  9446. var glWidth = itemToDraw.glWidth;
  9447. var glColor = itemToDraw.glColor;
  9448. if (gridLines.display && glWidth && glColor) {
  9449. context.save();
  9450. context.lineWidth = glWidth;
  9451. context.strokeStyle = glColor;
  9452. if (context.setLineDash) {
  9453. context.setLineDash(itemToDraw.glBorderDash);
  9454. context.lineDashOffset = itemToDraw.glBorderDashOffset;
  9455. }
  9456. context.beginPath();
  9457. if (gridLines.drawTicks) {
  9458. context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
  9459. context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
  9460. }
  9461. if (gridLines.drawOnChartArea) {
  9462. context.moveTo(itemToDraw.x1, itemToDraw.y1);
  9463. context.lineTo(itemToDraw.x2, itemToDraw.y2);
  9464. }
  9465. context.stroke();
  9466. context.restore();
  9467. }
  9468. if (optionTicks.display) {
  9469. // Make sure we draw text in the correct color and font
  9470. context.save();
  9471. context.translate(itemToDraw.labelX, itemToDraw.labelY);
  9472. context.rotate(itemToDraw.rotation);
  9473. context.font = itemToDraw.major ? majorTickFont.string : tickFont.string;
  9474. context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;
  9475. context.textBaseline = 'middle';
  9476. context.textAlign = itemToDraw.textAlign;
  9477. var label = itemToDraw.label;
  9478. var y = itemToDraw.textOffset;
  9479. if (helpers$1.isArray(label)) {
  9480. for (var i = 0; i < label.length; ++i) {
  9481. // We just make sure the multiline element is a string here..
  9482. context.fillText('' + label[i], 0, y);
  9483. y += lineHeight;
  9484. }
  9485. } else {
  9486. context.fillText(label, 0, y);
  9487. }
  9488. context.restore();
  9489. }
  9490. });
  9491. if (scaleLabel.display) {
  9492. // Draw the scale label
  9493. var scaleLabelX;
  9494. var scaleLabelY;
  9495. var rotation = 0;
  9496. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  9497. if (isHorizontal) {
  9498. scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
  9499. scaleLabelY = position === 'bottom'
  9500. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  9501. : me.top + halfLineHeight + scaleLabelPadding.top;
  9502. } else {
  9503. var isLeft = position === 'left';
  9504. scaleLabelX = isLeft
  9505. ? me.left + halfLineHeight + scaleLabelPadding.top
  9506. : me.right - halfLineHeight - scaleLabelPadding.top;
  9507. scaleLabelY = me.top + ((me.bottom - me.top) / 2);
  9508. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  9509. }
  9510. context.save();
  9511. context.translate(scaleLabelX, scaleLabelY);
  9512. context.rotate(rotation);
  9513. context.textAlign = 'center';
  9514. context.textBaseline = 'middle';
  9515. context.fillStyle = scaleLabelFontColor; // render in correct colour
  9516. context.font = scaleLabelFont.string;
  9517. context.fillText(scaleLabel.labelString, 0, 0);
  9518. context.restore();
  9519. }
  9520. if (axisWidth) {
  9521. // Draw the line at the edge of the axis
  9522. var firstLineWidth = axisWidth;
  9523. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, ticks.length - 1, 0);
  9524. var x1, x2, y1, y2;
  9525. if (isHorizontal) {
  9526. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  9527. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  9528. y1 = y2 = borderValue;
  9529. } else {
  9530. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  9531. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  9532. x1 = x2 = borderValue;
  9533. }
  9534. context.lineWidth = axisWidth;
  9535. context.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  9536. context.beginPath();
  9537. context.moveTo(x1, y1);
  9538. context.lineTo(x2, y2);
  9539. context.stroke();
  9540. }
  9541. }
  9542. });
  9543. var defaultConfig = {
  9544. position: 'bottom'
  9545. };
  9546. var scale_category = core_scale.extend({
  9547. /**
  9548. * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those
  9549. * else fall back to data.labels
  9550. * @private
  9551. */
  9552. getLabels: function() {
  9553. var data = this.chart.data;
  9554. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;
  9555. },
  9556. determineDataLimits: function() {
  9557. var me = this;
  9558. var labels = me.getLabels();
  9559. me.minIndex = 0;
  9560. me.maxIndex = labels.length - 1;
  9561. var findIndex;
  9562. if (me.options.ticks.min !== undefined) {
  9563. // user specified min value
  9564. findIndex = labels.indexOf(me.options.ticks.min);
  9565. me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
  9566. }
  9567. if (me.options.ticks.max !== undefined) {
  9568. // user specified max value
  9569. findIndex = labels.indexOf(me.options.ticks.max);
  9570. me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
  9571. }
  9572. me.min = labels[me.minIndex];
  9573. me.max = labels[me.maxIndex];
  9574. },
  9575. buildTicks: function() {
  9576. var me = this;
  9577. var labels = me.getLabels();
  9578. // If we are viewing some subset of labels, slice the original array
  9579. me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);
  9580. },
  9581. getLabelForIndex: function(index, datasetIndex) {
  9582. var me = this;
  9583. var chart = me.chart;
  9584. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  9585. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  9586. }
  9587. return me.ticks[index - me.minIndex];
  9588. },
  9589. // Used to get data value locations. Value can either be an index or a numerical value
  9590. getPixelForValue: function(value, index) {
  9591. var me = this;
  9592. var offset = me.options.offset;
  9593. // 1 is added because we need the length but we have the indexes
  9594. var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1);
  9595. // If value is a data object, then index is the index in the data array,
  9596. // not the index of the scale. We need to change that.
  9597. var valueCategory;
  9598. if (value !== undefined && value !== null) {
  9599. valueCategory = me.isHorizontal() ? value.x : value.y;
  9600. }
  9601. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  9602. var labels = me.getLabels();
  9603. value = valueCategory || value;
  9604. var idx = labels.indexOf(value);
  9605. index = idx !== -1 ? idx : index;
  9606. }
  9607. if (me.isHorizontal()) {
  9608. var valueWidth = me.width / offsetAmt;
  9609. var widthOffset = (valueWidth * (index - me.minIndex));
  9610. if (offset) {
  9611. widthOffset += (valueWidth / 2);
  9612. }
  9613. return me.left + widthOffset;
  9614. }
  9615. var valueHeight = me.height / offsetAmt;
  9616. var heightOffset = (valueHeight * (index - me.minIndex));
  9617. if (offset) {
  9618. heightOffset += (valueHeight / 2);
  9619. }
  9620. return me.top + heightOffset;
  9621. },
  9622. getPixelForTick: function(index) {
  9623. return this.getPixelForValue(this.ticks[index], index + this.minIndex, null);
  9624. },
  9625. getValueForPixel: function(pixel) {
  9626. var me = this;
  9627. var offset = me.options.offset;
  9628. var value;
  9629. var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
  9630. var horz = me.isHorizontal();
  9631. var valueDimension = (horz ? me.width : me.height) / offsetAmt;
  9632. pixel -= horz ? me.left : me.top;
  9633. if (offset) {
  9634. pixel -= (valueDimension / 2);
  9635. }
  9636. if (pixel <= 0) {
  9637. value = 0;
  9638. } else {
  9639. value = Math.round(pixel / valueDimension);
  9640. }
  9641. return value + me.minIndex;
  9642. },
  9643. getBasePixel: function() {
  9644. return this.bottom;
  9645. }
  9646. });
  9647. // INTERNAL: static default options, registered in src/index.js
  9648. var _defaults = defaultConfig;
  9649. scale_category._defaults = _defaults;
  9650. var noop = helpers$1.noop;
  9651. var isNullOrUndef = helpers$1.isNullOrUndef;
  9652. /**
  9653. * Generate a set of linear ticks
  9654. * @param generationOptions the options used to generate the ticks
  9655. * @param dataRange the range of the data
  9656. * @returns {number[]} array of tick values
  9657. */
  9658. function generateTicks(generationOptions, dataRange) {
  9659. var ticks = [];
  9660. // To get a "nice" value for the tick spacing, we will use the appropriately named
  9661. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  9662. // for details.
  9663. var MIN_SPACING = 1e-14;
  9664. var stepSize = generationOptions.stepSize;
  9665. var unit = stepSize || 1;
  9666. var maxNumSpaces = generationOptions.maxTicks - 1;
  9667. var min = generationOptions.min;
  9668. var max = generationOptions.max;
  9669. var precision = generationOptions.precision;
  9670. var rmin = dataRange.min;
  9671. var rmax = dataRange.max;
  9672. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  9673. var factor, niceMin, niceMax, numSpaces;
  9674. // Beyond MIN_SPACING floating point numbers being to lose precision
  9675. // such that we can't do the math necessary to generate ticks
  9676. if (spacing < MIN_SPACING && isNullOrUndef(min) && isNullOrUndef(max)) {
  9677. return [rmin, rmax];
  9678. }
  9679. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  9680. if (numSpaces > maxNumSpaces) {
  9681. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  9682. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  9683. }
  9684. if (stepSize || isNullOrUndef(precision)) {
  9685. // If a precision is not specified, calculate factor based on spacing
  9686. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  9687. } else {
  9688. // If the user specified a precision, round to that number of decimal places
  9689. factor = Math.pow(10, precision);
  9690. spacing = Math.ceil(spacing * factor) / factor;
  9691. }
  9692. niceMin = Math.floor(rmin / spacing) * spacing;
  9693. niceMax = Math.ceil(rmax / spacing) * spacing;
  9694. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  9695. if (stepSize) {
  9696. // If very close to our whole number, use it.
  9697. if (!isNullOrUndef(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  9698. niceMin = min;
  9699. }
  9700. if (!isNullOrUndef(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  9701. niceMax = max;
  9702. }
  9703. }
  9704. numSpaces = (niceMax - niceMin) / spacing;
  9705. // If very close to our rounded value, use it.
  9706. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  9707. numSpaces = Math.round(numSpaces);
  9708. } else {
  9709. numSpaces = Math.ceil(numSpaces);
  9710. }
  9711. niceMin = Math.round(niceMin * factor) / factor;
  9712. niceMax = Math.round(niceMax * factor) / factor;
  9713. ticks.push(isNullOrUndef(min) ? niceMin : min);
  9714. for (var j = 1; j < numSpaces; ++j) {
  9715. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  9716. }
  9717. ticks.push(isNullOrUndef(max) ? niceMax : max);
  9718. return ticks;
  9719. }
  9720. var scale_linearbase = core_scale.extend({
  9721. getRightValue: function(value) {
  9722. if (typeof value === 'string') {
  9723. return +value;
  9724. }
  9725. return core_scale.prototype.getRightValue.call(this, value);
  9726. },
  9727. handleTickRangeOptions: function() {
  9728. var me = this;
  9729. var opts = me.options;
  9730. var tickOpts = opts.ticks;
  9731. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  9732. // do nothing since that would make the chart weird. If the user really wants a weird chart
  9733. // axis, they can manually override it
  9734. if (tickOpts.beginAtZero) {
  9735. var minSign = helpers$1.sign(me.min);
  9736. var maxSign = helpers$1.sign(me.max);
  9737. if (minSign < 0 && maxSign < 0) {
  9738. // move the top up to 0
  9739. me.max = 0;
  9740. } else if (minSign > 0 && maxSign > 0) {
  9741. // move the bottom down to 0
  9742. me.min = 0;
  9743. }
  9744. }
  9745. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  9746. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  9747. if (tickOpts.min !== undefined) {
  9748. me.min = tickOpts.min;
  9749. } else if (tickOpts.suggestedMin !== undefined) {
  9750. if (me.min === null) {
  9751. me.min = tickOpts.suggestedMin;
  9752. } else {
  9753. me.min = Math.min(me.min, tickOpts.suggestedMin);
  9754. }
  9755. }
  9756. if (tickOpts.max !== undefined) {
  9757. me.max = tickOpts.max;
  9758. } else if (tickOpts.suggestedMax !== undefined) {
  9759. if (me.max === null) {
  9760. me.max = tickOpts.suggestedMax;
  9761. } else {
  9762. me.max = Math.max(me.max, tickOpts.suggestedMax);
  9763. }
  9764. }
  9765. if (setMin !== setMax) {
  9766. // We set the min or the max but not both.
  9767. // So ensure that our range is good
  9768. // Inverted or 0 length range can happen when
  9769. // ticks.min is set, and no datasets are visible
  9770. if (me.min >= me.max) {
  9771. if (setMin) {
  9772. me.max = me.min + 1;
  9773. } else {
  9774. me.min = me.max - 1;
  9775. }
  9776. }
  9777. }
  9778. if (me.min === me.max) {
  9779. me.max++;
  9780. if (!tickOpts.beginAtZero) {
  9781. me.min--;
  9782. }
  9783. }
  9784. },
  9785. getTickLimit: function() {
  9786. var me = this;
  9787. var tickOpts = me.options.ticks;
  9788. var stepSize = tickOpts.stepSize;
  9789. var maxTicksLimit = tickOpts.maxTicksLimit;
  9790. var maxTicks;
  9791. if (stepSize) {
  9792. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  9793. } else {
  9794. maxTicks = me._computeTickLimit();
  9795. maxTicksLimit = maxTicksLimit || 11;
  9796. }
  9797. if (maxTicksLimit) {
  9798. maxTicks = Math.min(maxTicksLimit, maxTicks);
  9799. }
  9800. return maxTicks;
  9801. },
  9802. _computeTickLimit: function() {
  9803. return Number.POSITIVE_INFINITY;
  9804. },
  9805. handleDirectionalChanges: noop,
  9806. buildTicks: function() {
  9807. var me = this;
  9808. var opts = me.options;
  9809. var tickOpts = opts.ticks;
  9810. // Figure out what the max number of ticks we can support it is based on the size of
  9811. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  9812. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  9813. // the graph. Make sure we always have at least 2 ticks
  9814. var maxTicks = me.getTickLimit();
  9815. maxTicks = Math.max(2, maxTicks);
  9816. var numericGeneratorOptions = {
  9817. maxTicks: maxTicks,
  9818. min: tickOpts.min,
  9819. max: tickOpts.max,
  9820. precision: tickOpts.precision,
  9821. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  9822. };
  9823. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  9824. me.handleDirectionalChanges();
  9825. // At this point, we need to update our max and min given the tick values since we have expanded the
  9826. // range of the scale
  9827. me.max = helpers$1.max(ticks);
  9828. me.min = helpers$1.min(ticks);
  9829. if (tickOpts.reverse) {
  9830. ticks.reverse();
  9831. me.start = me.max;
  9832. me.end = me.min;
  9833. } else {
  9834. me.start = me.min;
  9835. me.end = me.max;
  9836. }
  9837. },
  9838. convertTicksToLabels: function() {
  9839. var me = this;
  9840. me.ticksAsNumbers = me.ticks.slice();
  9841. me.zeroLineIndex = me.ticks.indexOf(0);
  9842. core_scale.prototype.convertTicksToLabels.call(me);
  9843. }
  9844. });
  9845. var defaultConfig$1 = {
  9846. position: 'left',
  9847. ticks: {
  9848. callback: core_ticks.formatters.linear
  9849. }
  9850. };
  9851. var scale_linear = scale_linearbase.extend({
  9852. determineDataLimits: function() {
  9853. var me = this;
  9854. var opts = me.options;
  9855. var chart = me.chart;
  9856. var data = chart.data;
  9857. var datasets = data.datasets;
  9858. var isHorizontal = me.isHorizontal();
  9859. var DEFAULT_MIN = 0;
  9860. var DEFAULT_MAX = 1;
  9861. function IDMatches(meta) {
  9862. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  9863. }
  9864. // First Calculate the range
  9865. me.min = null;
  9866. me.max = null;
  9867. var hasStacks = opts.stacked;
  9868. if (hasStacks === undefined) {
  9869. helpers$1.each(datasets, function(dataset, datasetIndex) {
  9870. if (hasStacks) {
  9871. return;
  9872. }
  9873. var meta = chart.getDatasetMeta(datasetIndex);
  9874. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  9875. meta.stack !== undefined) {
  9876. hasStacks = true;
  9877. }
  9878. });
  9879. }
  9880. if (opts.stacked || hasStacks) {
  9881. var valuesPerStack = {};
  9882. helpers$1.each(datasets, function(dataset, datasetIndex) {
  9883. var meta = chart.getDatasetMeta(datasetIndex);
  9884. var key = [
  9885. meta.type,
  9886. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  9887. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  9888. meta.stack
  9889. ].join('.');
  9890. if (valuesPerStack[key] === undefined) {
  9891. valuesPerStack[key] = {
  9892. positiveValues: [],
  9893. negativeValues: []
  9894. };
  9895. }
  9896. // Store these per type
  9897. var positiveValues = valuesPerStack[key].positiveValues;
  9898. var negativeValues = valuesPerStack[key].negativeValues;
  9899. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  9900. helpers$1.each(dataset.data, function(rawValue, index) {
  9901. var value = +me.getRightValue(rawValue);
  9902. if (isNaN(value) || meta.data[index].hidden) {
  9903. return;
  9904. }
  9905. positiveValues[index] = positiveValues[index] || 0;
  9906. negativeValues[index] = negativeValues[index] || 0;
  9907. if (opts.relativePoints) {
  9908. positiveValues[index] = 100;
  9909. } else if (value < 0) {
  9910. negativeValues[index] += value;
  9911. } else {
  9912. positiveValues[index] += value;
  9913. }
  9914. });
  9915. }
  9916. });
  9917. helpers$1.each(valuesPerStack, function(valuesForType) {
  9918. var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
  9919. var minVal = helpers$1.min(values);
  9920. var maxVal = helpers$1.max(values);
  9921. me.min = me.min === null ? minVal : Math.min(me.min, minVal);
  9922. me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
  9923. });
  9924. } else {
  9925. helpers$1.each(datasets, function(dataset, datasetIndex) {
  9926. var meta = chart.getDatasetMeta(datasetIndex);
  9927. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  9928. helpers$1.each(dataset.data, function(rawValue, index) {
  9929. var value = +me.getRightValue(rawValue);
  9930. if (isNaN(value) || meta.data[index].hidden) {
  9931. return;
  9932. }
  9933. if (me.min === null) {
  9934. me.min = value;
  9935. } else if (value < me.min) {
  9936. me.min = value;
  9937. }
  9938. if (me.max === null) {
  9939. me.max = value;
  9940. } else if (value > me.max) {
  9941. me.max = value;
  9942. }
  9943. });
  9944. }
  9945. });
  9946. }
  9947. me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  9948. me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  9949. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  9950. this.handleTickRangeOptions();
  9951. },
  9952. // Returns the maximum number of ticks based on the scale dimension
  9953. _computeTickLimit: function() {
  9954. var me = this;
  9955. var tickFont;
  9956. if (me.isHorizontal()) {
  9957. return Math.ceil(me.width / 40);
  9958. }
  9959. tickFont = helpers$1.options._parseFont(me.options.ticks);
  9960. return Math.ceil(me.height / tickFont.lineHeight);
  9961. },
  9962. // Called after the ticks are built. We need
  9963. handleDirectionalChanges: function() {
  9964. if (!this.isHorizontal()) {
  9965. // We are in a vertical orientation. The top value is the highest. So reverse the array
  9966. this.ticks.reverse();
  9967. }
  9968. },
  9969. getLabelForIndex: function(index, datasetIndex) {
  9970. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  9971. },
  9972. // Utils
  9973. getPixelForValue: function(value) {
  9974. // This must be called after fit has been run so that
  9975. // this.left, this.top, this.right, and this.bottom have been defined
  9976. var me = this;
  9977. var start = me.start;
  9978. var rightValue = +me.getRightValue(value);
  9979. var pixel;
  9980. var range = me.end - start;
  9981. if (me.isHorizontal()) {
  9982. pixel = me.left + (me.width / range * (rightValue - start));
  9983. } else {
  9984. pixel = me.bottom - (me.height / range * (rightValue - start));
  9985. }
  9986. return pixel;
  9987. },
  9988. getValueForPixel: function(pixel) {
  9989. var me = this;
  9990. var isHorizontal = me.isHorizontal();
  9991. var innerDimension = isHorizontal ? me.width : me.height;
  9992. var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;
  9993. return me.start + ((me.end - me.start) * offset);
  9994. },
  9995. getPixelForTick: function(index) {
  9996. return this.getPixelForValue(this.ticksAsNumbers[index]);
  9997. }
  9998. });
  9999. // INTERNAL: static default options, registered in src/index.js
  10000. var _defaults$1 = defaultConfig$1;
  10001. scale_linear._defaults = _defaults$1;
  10002. var valueOrDefault$a = helpers$1.valueOrDefault;
  10003. /**
  10004. * Generate a set of logarithmic ticks
  10005. * @param generationOptions the options used to generate the ticks
  10006. * @param dataRange the range of the data
  10007. * @returns {number[]} array of tick values
  10008. */
  10009. function generateTicks$1(generationOptions, dataRange) {
  10010. var ticks = [];
  10011. var tickVal = valueOrDefault$a(generationOptions.min, Math.pow(10, Math.floor(helpers$1.log10(dataRange.min))));
  10012. var endExp = Math.floor(helpers$1.log10(dataRange.max));
  10013. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  10014. var exp, significand;
  10015. if (tickVal === 0) {
  10016. exp = Math.floor(helpers$1.log10(dataRange.minNotZero));
  10017. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  10018. ticks.push(tickVal);
  10019. tickVal = significand * Math.pow(10, exp);
  10020. } else {
  10021. exp = Math.floor(helpers$1.log10(tickVal));
  10022. significand = Math.floor(tickVal / Math.pow(10, exp));
  10023. }
  10024. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  10025. do {
  10026. ticks.push(tickVal);
  10027. ++significand;
  10028. if (significand === 10) {
  10029. significand = 1;
  10030. ++exp;
  10031. precision = exp >= 0 ? 1 : precision;
  10032. }
  10033. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  10034. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  10035. var lastTick = valueOrDefault$a(generationOptions.max, tickVal);
  10036. ticks.push(lastTick);
  10037. return ticks;
  10038. }
  10039. var defaultConfig$2 = {
  10040. position: 'left',
  10041. // label settings
  10042. ticks: {
  10043. callback: core_ticks.formatters.logarithmic
  10044. }
  10045. };
  10046. // TODO(v3): change this to positiveOrDefault
  10047. function nonNegativeOrDefault(value, defaultValue) {
  10048. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  10049. }
  10050. var scale_logarithmic = core_scale.extend({
  10051. determineDataLimits: function() {
  10052. var me = this;
  10053. var opts = me.options;
  10054. var chart = me.chart;
  10055. var data = chart.data;
  10056. var datasets = data.datasets;
  10057. var isHorizontal = me.isHorizontal();
  10058. function IDMatches(meta) {
  10059. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  10060. }
  10061. // Calculate Range
  10062. me.min = null;
  10063. me.max = null;
  10064. me.minNotZero = null;
  10065. var hasStacks = opts.stacked;
  10066. if (hasStacks === undefined) {
  10067. helpers$1.each(datasets, function(dataset, datasetIndex) {
  10068. if (hasStacks) {
  10069. return;
  10070. }
  10071. var meta = chart.getDatasetMeta(datasetIndex);
  10072. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  10073. meta.stack !== undefined) {
  10074. hasStacks = true;
  10075. }
  10076. });
  10077. }
  10078. if (opts.stacked || hasStacks) {
  10079. var valuesPerStack = {};
  10080. helpers$1.each(datasets, function(dataset, datasetIndex) {
  10081. var meta = chart.getDatasetMeta(datasetIndex);
  10082. var key = [
  10083. meta.type,
  10084. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  10085. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  10086. meta.stack
  10087. ].join('.');
  10088. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  10089. if (valuesPerStack[key] === undefined) {
  10090. valuesPerStack[key] = [];
  10091. }
  10092. helpers$1.each(dataset.data, function(rawValue, index) {
  10093. var values = valuesPerStack[key];
  10094. var value = +me.getRightValue(rawValue);
  10095. // invalid, hidden and negative values are ignored
  10096. if (isNaN(value) || meta.data[index].hidden || value < 0) {
  10097. return;
  10098. }
  10099. values[index] = values[index] || 0;
  10100. values[index] += value;
  10101. });
  10102. }
  10103. });
  10104. helpers$1.each(valuesPerStack, function(valuesForType) {
  10105. if (valuesForType.length > 0) {
  10106. var minVal = helpers$1.min(valuesForType);
  10107. var maxVal = helpers$1.max(valuesForType);
  10108. me.min = me.min === null ? minVal : Math.min(me.min, minVal);
  10109. me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
  10110. }
  10111. });
  10112. } else {
  10113. helpers$1.each(datasets, function(dataset, datasetIndex) {
  10114. var meta = chart.getDatasetMeta(datasetIndex);
  10115. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  10116. helpers$1.each(dataset.data, function(rawValue, index) {
  10117. var value = +me.getRightValue(rawValue);
  10118. // invalid, hidden and negative values are ignored
  10119. if (isNaN(value) || meta.data[index].hidden || value < 0) {
  10120. return;
  10121. }
  10122. if (me.min === null) {
  10123. me.min = value;
  10124. } else if (value < me.min) {
  10125. me.min = value;
  10126. }
  10127. if (me.max === null) {
  10128. me.max = value;
  10129. } else if (value > me.max) {
  10130. me.max = value;
  10131. }
  10132. if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {
  10133. me.minNotZero = value;
  10134. }
  10135. });
  10136. }
  10137. });
  10138. }
  10139. // Common base implementation to handle ticks.min, ticks.max
  10140. this.handleTickRangeOptions();
  10141. },
  10142. handleTickRangeOptions: function() {
  10143. var me = this;
  10144. var tickOpts = me.options.ticks;
  10145. var DEFAULT_MIN = 1;
  10146. var DEFAULT_MAX = 10;
  10147. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  10148. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  10149. if (me.min === me.max) {
  10150. if (me.min !== 0 && me.min !== null) {
  10151. me.min = Math.pow(10, Math.floor(helpers$1.log10(me.min)) - 1);
  10152. me.max = Math.pow(10, Math.floor(helpers$1.log10(me.max)) + 1);
  10153. } else {
  10154. me.min = DEFAULT_MIN;
  10155. me.max = DEFAULT_MAX;
  10156. }
  10157. }
  10158. if (me.min === null) {
  10159. me.min = Math.pow(10, Math.floor(helpers$1.log10(me.max)) - 1);
  10160. }
  10161. if (me.max === null) {
  10162. me.max = me.min !== 0
  10163. ? Math.pow(10, Math.floor(helpers$1.log10(me.min)) + 1)
  10164. : DEFAULT_MAX;
  10165. }
  10166. if (me.minNotZero === null) {
  10167. if (me.min > 0) {
  10168. me.minNotZero = me.min;
  10169. } else if (me.max < 1) {
  10170. me.minNotZero = Math.pow(10, Math.floor(helpers$1.log10(me.max)));
  10171. } else {
  10172. me.minNotZero = DEFAULT_MIN;
  10173. }
  10174. }
  10175. },
  10176. buildTicks: function() {
  10177. var me = this;
  10178. var tickOpts = me.options.ticks;
  10179. var reverse = !me.isHorizontal();
  10180. var generationOptions = {
  10181. min: nonNegativeOrDefault(tickOpts.min),
  10182. max: nonNegativeOrDefault(tickOpts.max)
  10183. };
  10184. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  10185. // At this point, we need to update our max and min given the tick values since we have expanded the
  10186. // range of the scale
  10187. me.max = helpers$1.max(ticks);
  10188. me.min = helpers$1.min(ticks);
  10189. if (tickOpts.reverse) {
  10190. reverse = !reverse;
  10191. me.start = me.max;
  10192. me.end = me.min;
  10193. } else {
  10194. me.start = me.min;
  10195. me.end = me.max;
  10196. }
  10197. if (reverse) {
  10198. ticks.reverse();
  10199. }
  10200. },
  10201. convertTicksToLabels: function() {
  10202. this.tickValues = this.ticks.slice();
  10203. core_scale.prototype.convertTicksToLabels.call(this);
  10204. },
  10205. // Get the correct tooltip label
  10206. getLabelForIndex: function(index, datasetIndex) {
  10207. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  10208. },
  10209. getPixelForTick: function(index) {
  10210. return this.getPixelForValue(this.tickValues[index]);
  10211. },
  10212. /**
  10213. * Returns the value of the first tick.
  10214. * @param {number} value - The minimum not zero value.
  10215. * @return {number} The first tick value.
  10216. * @private
  10217. */
  10218. _getFirstTickValue: function(value) {
  10219. var exp = Math.floor(helpers$1.log10(value));
  10220. var significand = Math.floor(value / Math.pow(10, exp));
  10221. return significand * Math.pow(10, exp);
  10222. },
  10223. getPixelForValue: function(value) {
  10224. var me = this;
  10225. var tickOpts = me.options.ticks;
  10226. var reverse = tickOpts.reverse;
  10227. var log10 = helpers$1.log10;
  10228. var firstTickValue = me._getFirstTickValue(me.minNotZero);
  10229. var offset = 0;
  10230. var innerDimension, pixel, start, end, sign;
  10231. value = +me.getRightValue(value);
  10232. if (reverse) {
  10233. start = me.end;
  10234. end = me.start;
  10235. sign = -1;
  10236. } else {
  10237. start = me.start;
  10238. end = me.end;
  10239. sign = 1;
  10240. }
  10241. if (me.isHorizontal()) {
  10242. innerDimension = me.width;
  10243. pixel = reverse ? me.right : me.left;
  10244. } else {
  10245. innerDimension = me.height;
  10246. sign *= -1; // invert, since the upper-left corner of the canvas is at pixel (0, 0)
  10247. pixel = reverse ? me.top : me.bottom;
  10248. }
  10249. if (value !== start) {
  10250. if (start === 0) { // include zero tick
  10251. offset = valueOrDefault$a(tickOpts.fontSize, core_defaults.global.defaultFontSize);
  10252. innerDimension -= offset;
  10253. start = firstTickValue;
  10254. }
  10255. if (value !== 0) {
  10256. offset += innerDimension / (log10(end) - log10(start)) * (log10(value) - log10(start));
  10257. }
  10258. pixel += sign * offset;
  10259. }
  10260. return pixel;
  10261. },
  10262. getValueForPixel: function(pixel) {
  10263. var me = this;
  10264. var tickOpts = me.options.ticks;
  10265. var reverse = tickOpts.reverse;
  10266. var log10 = helpers$1.log10;
  10267. var firstTickValue = me._getFirstTickValue(me.minNotZero);
  10268. var innerDimension, start, end, value;
  10269. if (reverse) {
  10270. start = me.end;
  10271. end = me.start;
  10272. } else {
  10273. start = me.start;
  10274. end = me.end;
  10275. }
  10276. if (me.isHorizontal()) {
  10277. innerDimension = me.width;
  10278. value = reverse ? me.right - pixel : pixel - me.left;
  10279. } else {
  10280. innerDimension = me.height;
  10281. value = reverse ? pixel - me.top : me.bottom - pixel;
  10282. }
  10283. if (value !== start) {
  10284. if (start === 0) { // include zero tick
  10285. var offset = valueOrDefault$a(tickOpts.fontSize, core_defaults.global.defaultFontSize);
  10286. value -= offset;
  10287. innerDimension -= offset;
  10288. start = firstTickValue;
  10289. }
  10290. value *= log10(end) - log10(start);
  10291. value /= innerDimension;
  10292. value = Math.pow(10, log10(start) + value);
  10293. }
  10294. return value;
  10295. }
  10296. });
  10297. // INTERNAL: static default options, registered in src/index.js
  10298. var _defaults$2 = defaultConfig$2;
  10299. scale_logarithmic._defaults = _defaults$2;
  10300. var valueOrDefault$b = helpers$1.valueOrDefault;
  10301. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  10302. var resolve$7 = helpers$1.options.resolve;
  10303. var defaultConfig$3 = {
  10304. display: true,
  10305. // Boolean - Whether to animate scaling the chart from the centre
  10306. animate: true,
  10307. position: 'chartArea',
  10308. angleLines: {
  10309. display: true,
  10310. color: 'rgba(0, 0, 0, 0.1)',
  10311. lineWidth: 1,
  10312. borderDash: [],
  10313. borderDashOffset: 0.0
  10314. },
  10315. gridLines: {
  10316. circular: false
  10317. },
  10318. // label settings
  10319. ticks: {
  10320. // Boolean - Show a backdrop to the scale label
  10321. showLabelBackdrop: true,
  10322. // String - The colour of the label backdrop
  10323. backdropColor: 'rgba(255,255,255,0.75)',
  10324. // Number - The backdrop padding above & below the label in pixels
  10325. backdropPaddingY: 2,
  10326. // Number - The backdrop padding to the side of the label in pixels
  10327. backdropPaddingX: 2,
  10328. callback: core_ticks.formatters.linear
  10329. },
  10330. pointLabels: {
  10331. // Boolean - if true, show point labels
  10332. display: true,
  10333. // Number - Point label font size in pixels
  10334. fontSize: 10,
  10335. // Function - Used to convert point labels
  10336. callback: function(label) {
  10337. return label;
  10338. }
  10339. }
  10340. };
  10341. function getValueCount(scale) {
  10342. var opts = scale.options;
  10343. return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0;
  10344. }
  10345. function getTickBackdropHeight(opts) {
  10346. var tickOpts = opts.ticks;
  10347. if (tickOpts.display && opts.display) {
  10348. return valueOrDefault$b(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  10349. }
  10350. return 0;
  10351. }
  10352. function measureLabelSize(ctx, lineHeight, label) {
  10353. if (helpers$1.isArray(label)) {
  10354. return {
  10355. w: helpers$1.longestText(ctx, ctx.font, label),
  10356. h: label.length * lineHeight
  10357. };
  10358. }
  10359. return {
  10360. w: ctx.measureText(label).width,
  10361. h: lineHeight
  10362. };
  10363. }
  10364. function determineLimits(angle, pos, size, min, max) {
  10365. if (angle === min || angle === max) {
  10366. return {
  10367. start: pos - (size / 2),
  10368. end: pos + (size / 2)
  10369. };
  10370. } else if (angle < min || angle > max) {
  10371. return {
  10372. start: pos - size,
  10373. end: pos
  10374. };
  10375. }
  10376. return {
  10377. start: pos,
  10378. end: pos + size
  10379. };
  10380. }
  10381. /**
  10382. * Helper function to fit a radial linear scale with point labels
  10383. */
  10384. function fitWithPointLabels(scale) {
  10385. // Right, this is really confusing and there is a lot of maths going on here
  10386. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  10387. //
  10388. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  10389. //
  10390. // Solution:
  10391. //
  10392. // We assume the radius of the polygon is half the size of the canvas at first
  10393. // at each index we check if the text overlaps.
  10394. //
  10395. // Where it does, we store that angle and that index.
  10396. //
  10397. // After finding the largest index and angle we calculate how much we need to remove
  10398. // from the shape radius to move the point inwards by that x.
  10399. //
  10400. // We average the left and right distances to get the maximum shape radius that can fit in the box
  10401. // along with labels.
  10402. //
  10403. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  10404. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  10405. //
  10406. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  10407. // and position it in the most space efficient manner
  10408. //
  10409. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  10410. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  10411. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  10412. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  10413. var furthestLimits = {
  10414. l: 0,
  10415. r: scale.width,
  10416. t: 0,
  10417. b: scale.height - scale.paddingTop
  10418. };
  10419. var furthestAngles = {};
  10420. var i, textSize, pointPosition;
  10421. scale.ctx.font = plFont.string;
  10422. scale._pointLabelSizes = [];
  10423. var valueCount = getValueCount(scale);
  10424. for (i = 0; i < valueCount; i++) {
  10425. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  10426. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i] || '');
  10427. scale._pointLabelSizes[i] = textSize;
  10428. // Add quarter circle to make degree 0 mean top of circle
  10429. var angleRadians = scale.getIndexAngle(i);
  10430. var angle = helpers$1.toDegrees(angleRadians) % 360;
  10431. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  10432. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  10433. if (hLimits.start < furthestLimits.l) {
  10434. furthestLimits.l = hLimits.start;
  10435. furthestAngles.l = angleRadians;
  10436. }
  10437. if (hLimits.end > furthestLimits.r) {
  10438. furthestLimits.r = hLimits.end;
  10439. furthestAngles.r = angleRadians;
  10440. }
  10441. if (vLimits.start < furthestLimits.t) {
  10442. furthestLimits.t = vLimits.start;
  10443. furthestAngles.t = angleRadians;
  10444. }
  10445. if (vLimits.end > furthestLimits.b) {
  10446. furthestLimits.b = vLimits.end;
  10447. furthestAngles.b = angleRadians;
  10448. }
  10449. }
  10450. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  10451. }
  10452. function getTextAlignForAngle(angle) {
  10453. if (angle === 0 || angle === 180) {
  10454. return 'center';
  10455. } else if (angle < 180) {
  10456. return 'left';
  10457. }
  10458. return 'right';
  10459. }
  10460. function fillText(ctx, text, position, lineHeight) {
  10461. var y = position.y + lineHeight / 2;
  10462. var i, ilen;
  10463. if (helpers$1.isArray(text)) {
  10464. for (i = 0, ilen = text.length; i < ilen; ++i) {
  10465. ctx.fillText(text[i], position.x, y);
  10466. y += lineHeight;
  10467. }
  10468. } else {
  10469. ctx.fillText(text, position.x, y);
  10470. }
  10471. }
  10472. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  10473. if (angle === 90 || angle === 270) {
  10474. position.y -= (textSize.h / 2);
  10475. } else if (angle > 270 || angle < 90) {
  10476. position.y -= textSize.h;
  10477. }
  10478. }
  10479. function drawPointLabels(scale) {
  10480. var ctx = scale.ctx;
  10481. var opts = scale.options;
  10482. var angleLineOpts = opts.angleLines;
  10483. var gridLineOpts = opts.gridLines;
  10484. var pointLabelOpts = opts.pointLabels;
  10485. var lineWidth = valueOrDefault$b(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  10486. var lineColor = valueOrDefault$b(angleLineOpts.color, gridLineOpts.color);
  10487. var tickBackdropHeight = getTickBackdropHeight(opts);
  10488. ctx.save();
  10489. ctx.lineWidth = lineWidth;
  10490. ctx.strokeStyle = lineColor;
  10491. if (ctx.setLineDash) {
  10492. ctx.setLineDash(resolve$7([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  10493. ctx.lineDashOffset = resolve$7([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  10494. }
  10495. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  10496. // Point Label Font
  10497. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  10498. ctx.font = plFont.string;
  10499. ctx.textBaseline = 'middle';
  10500. for (var i = getValueCount(scale) - 1; i >= 0; i--) {
  10501. if (angleLineOpts.display && lineWidth && lineColor) {
  10502. var outerPosition = scale.getPointPosition(i, outerDistance);
  10503. ctx.beginPath();
  10504. ctx.moveTo(scale.xCenter, scale.yCenter);
  10505. ctx.lineTo(outerPosition.x, outerPosition.y);
  10506. ctx.stroke();
  10507. }
  10508. if (pointLabelOpts.display) {
  10509. // Extra pixels out for some label spacing
  10510. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  10511. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  10512. // Keep this in loop since we may support array properties here
  10513. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  10514. ctx.fillStyle = pointLabelFontColor;
  10515. var angleRadians = scale.getIndexAngle(i);
  10516. var angle = helpers$1.toDegrees(angleRadians);
  10517. ctx.textAlign = getTextAlignForAngle(angle);
  10518. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  10519. fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.lineHeight);
  10520. }
  10521. }
  10522. ctx.restore();
  10523. }
  10524. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  10525. var ctx = scale.ctx;
  10526. var circular = gridLineOpts.circular;
  10527. var valueCount = getValueCount(scale);
  10528. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  10529. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  10530. var pointPosition;
  10531. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  10532. return;
  10533. }
  10534. ctx.save();
  10535. ctx.strokeStyle = lineColor;
  10536. ctx.lineWidth = lineWidth;
  10537. if (ctx.setLineDash) {
  10538. ctx.setLineDash(gridLineOpts.borderDash || []);
  10539. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  10540. }
  10541. ctx.beginPath();
  10542. if (circular) {
  10543. // Draw circular arcs between the points
  10544. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  10545. } else {
  10546. // Draw straight lines connecting each index
  10547. pointPosition = scale.getPointPosition(0, radius);
  10548. ctx.moveTo(pointPosition.x, pointPosition.y);
  10549. for (var i = 1; i < valueCount; i++) {
  10550. pointPosition = scale.getPointPosition(i, radius);
  10551. ctx.lineTo(pointPosition.x, pointPosition.y);
  10552. }
  10553. }
  10554. ctx.closePath();
  10555. ctx.stroke();
  10556. ctx.restore();
  10557. }
  10558. function numberOrZero(param) {
  10559. return helpers$1.isNumber(param) ? param : 0;
  10560. }
  10561. var scale_radialLinear = scale_linearbase.extend({
  10562. setDimensions: function() {
  10563. var me = this;
  10564. // Set the unconstrained dimension before label rotation
  10565. me.width = me.maxWidth;
  10566. me.height = me.maxHeight;
  10567. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  10568. me.xCenter = Math.floor(me.width / 2);
  10569. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  10570. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  10571. },
  10572. determineDataLimits: function() {
  10573. var me = this;
  10574. var chart = me.chart;
  10575. var min = Number.POSITIVE_INFINITY;
  10576. var max = Number.NEGATIVE_INFINITY;
  10577. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  10578. if (chart.isDatasetVisible(datasetIndex)) {
  10579. var meta = chart.getDatasetMeta(datasetIndex);
  10580. helpers$1.each(dataset.data, function(rawValue, index) {
  10581. var value = +me.getRightValue(rawValue);
  10582. if (isNaN(value) || meta.data[index].hidden) {
  10583. return;
  10584. }
  10585. min = Math.min(value, min);
  10586. max = Math.max(value, max);
  10587. });
  10588. }
  10589. });
  10590. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  10591. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  10592. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  10593. me.handleTickRangeOptions();
  10594. },
  10595. // Returns the maximum number of ticks based on the scale dimension
  10596. _computeTickLimit: function() {
  10597. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  10598. },
  10599. convertTicksToLabels: function() {
  10600. var me = this;
  10601. scale_linearbase.prototype.convertTicksToLabels.call(me);
  10602. // Point labels
  10603. me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
  10604. },
  10605. getLabelForIndex: function(index, datasetIndex) {
  10606. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  10607. },
  10608. fit: function() {
  10609. var me = this;
  10610. var opts = me.options;
  10611. if (opts.display && opts.pointLabels.display) {
  10612. fitWithPointLabels(me);
  10613. } else {
  10614. me.setCenterPoint(0, 0, 0, 0);
  10615. }
  10616. },
  10617. /**
  10618. * Set radius reductions and determine new radius and center point
  10619. * @private
  10620. */
  10621. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  10622. var me = this;
  10623. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  10624. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  10625. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  10626. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  10627. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  10628. radiusReductionRight = numberOrZero(radiusReductionRight);
  10629. radiusReductionTop = numberOrZero(radiusReductionTop);
  10630. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  10631. me.drawingArea = Math.min(
  10632. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  10633. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  10634. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  10635. },
  10636. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  10637. var me = this;
  10638. var maxRight = me.width - rightMovement - me.drawingArea;
  10639. var maxLeft = leftMovement + me.drawingArea;
  10640. var maxTop = topMovement + me.drawingArea;
  10641. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  10642. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  10643. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  10644. },
  10645. getIndexAngle: function(index) {
  10646. var angleMultiplier = (Math.PI * 2) / getValueCount(this);
  10647. var startAngle = this.chart.options && this.chart.options.startAngle ?
  10648. this.chart.options.startAngle :
  10649. 0;
  10650. var startAngleRadians = startAngle * Math.PI * 2 / 360;
  10651. // Start from the top instead of right, so remove a quarter of the circle
  10652. return index * angleMultiplier + startAngleRadians;
  10653. },
  10654. getDistanceFromCenterForValue: function(value) {
  10655. var me = this;
  10656. if (value === null) {
  10657. return 0; // null always in center
  10658. }
  10659. // Take into account half font size + the yPadding of the top value
  10660. var scalingFactor = me.drawingArea / (me.max - me.min);
  10661. if (me.options.ticks.reverse) {
  10662. return (me.max - value) * scalingFactor;
  10663. }
  10664. return (value - me.min) * scalingFactor;
  10665. },
  10666. getPointPosition: function(index, distanceFromCenter) {
  10667. var me = this;
  10668. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  10669. return {
  10670. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  10671. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  10672. };
  10673. },
  10674. getPointPositionForValue: function(index, value) {
  10675. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  10676. },
  10677. getBasePosition: function() {
  10678. var me = this;
  10679. var min = me.min;
  10680. var max = me.max;
  10681. return me.getPointPositionForValue(0,
  10682. me.beginAtZero ? 0 :
  10683. min < 0 && max < 0 ? max :
  10684. min > 0 && max > 0 ? min :
  10685. 0);
  10686. },
  10687. draw: function() {
  10688. var me = this;
  10689. var opts = me.options;
  10690. var gridLineOpts = opts.gridLines;
  10691. var tickOpts = opts.ticks;
  10692. if (opts.display) {
  10693. var ctx = me.ctx;
  10694. var startAngle = this.getIndexAngle(0);
  10695. var tickFont = helpers$1.options._parseFont(tickOpts);
  10696. if (opts.angleLines.display || opts.pointLabels.display) {
  10697. drawPointLabels(me);
  10698. }
  10699. helpers$1.each(me.ticks, function(label, index) {
  10700. // Don't draw a centre value (if it is minimum)
  10701. if (index > 0 || tickOpts.reverse) {
  10702. var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  10703. // Draw circular lines around the scale
  10704. if (gridLineOpts.display && index !== 0) {
  10705. drawRadiusLine(me, gridLineOpts, yCenterOffset, index);
  10706. }
  10707. if (tickOpts.display) {
  10708. var tickFontColor = valueOrDefault$b(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  10709. ctx.font = tickFont.string;
  10710. ctx.save();
  10711. ctx.translate(me.xCenter, me.yCenter);
  10712. ctx.rotate(startAngle);
  10713. if (tickOpts.showLabelBackdrop) {
  10714. var labelWidth = ctx.measureText(label).width;
  10715. ctx.fillStyle = tickOpts.backdropColor;
  10716. ctx.fillRect(
  10717. -labelWidth / 2 - tickOpts.backdropPaddingX,
  10718. -yCenterOffset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  10719. labelWidth + tickOpts.backdropPaddingX * 2,
  10720. tickFont.size + tickOpts.backdropPaddingY * 2
  10721. );
  10722. }
  10723. ctx.textAlign = 'center';
  10724. ctx.textBaseline = 'middle';
  10725. ctx.fillStyle = tickFontColor;
  10726. ctx.fillText(label, 0, -yCenterOffset);
  10727. ctx.restore();
  10728. }
  10729. }
  10730. });
  10731. }
  10732. }
  10733. });
  10734. // INTERNAL: static default options, registered in src/index.js
  10735. var _defaults$3 = defaultConfig$3;
  10736. scale_radialLinear._defaults = _defaults$3;
  10737. var valueOrDefault$c = helpers$1.valueOrDefault;
  10738. // Integer constants are from the ES6 spec.
  10739. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  10740. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  10741. var INTERVALS = {
  10742. millisecond: {
  10743. common: true,
  10744. size: 1,
  10745. steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
  10746. },
  10747. second: {
  10748. common: true,
  10749. size: 1000,
  10750. steps: [1, 2, 5, 10, 15, 30]
  10751. },
  10752. minute: {
  10753. common: true,
  10754. size: 60000,
  10755. steps: [1, 2, 5, 10, 15, 30]
  10756. },
  10757. hour: {
  10758. common: true,
  10759. size: 3600000,
  10760. steps: [1, 2, 3, 6, 12]
  10761. },
  10762. day: {
  10763. common: true,
  10764. size: 86400000,
  10765. steps: [1, 2, 5]
  10766. },
  10767. week: {
  10768. common: false,
  10769. size: 604800000,
  10770. steps: [1, 2, 3, 4]
  10771. },
  10772. month: {
  10773. common: true,
  10774. size: 2.628e9,
  10775. steps: [1, 2, 3]
  10776. },
  10777. quarter: {
  10778. common: false,
  10779. size: 7.884e9,
  10780. steps: [1, 2, 3, 4]
  10781. },
  10782. year: {
  10783. common: true,
  10784. size: 3.154e10
  10785. }
  10786. };
  10787. var UNITS = Object.keys(INTERVALS);
  10788. function sorter(a, b) {
  10789. return a - b;
  10790. }
  10791. function arrayUnique(items) {
  10792. var hash = {};
  10793. var out = [];
  10794. var i, ilen, item;
  10795. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10796. item = items[i];
  10797. if (!hash[item]) {
  10798. hash[item] = true;
  10799. out.push(item);
  10800. }
  10801. }
  10802. return out;
  10803. }
  10804. /**
  10805. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  10806. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  10807. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  10808. * extremity (left + width or top + height). Note that it would be more optimized to directly
  10809. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  10810. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  10811. *
  10812. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  10813. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  10814. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  10815. * If 'series', timestamps will be positioned at the same distance from each other. In this
  10816. * case, only timestamps that break the time linearity are registered, meaning that in the
  10817. * best case, all timestamps are linear, the table contains only min and max.
  10818. */
  10819. function buildLookupTable(timestamps, min, max, distribution) {
  10820. if (distribution === 'linear' || !timestamps.length) {
  10821. return [
  10822. {time: min, pos: 0},
  10823. {time: max, pos: 1}
  10824. ];
  10825. }
  10826. var table = [];
  10827. var items = [min];
  10828. var i, ilen, prev, curr, next;
  10829. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  10830. curr = timestamps[i];
  10831. if (curr > min && curr < max) {
  10832. items.push(curr);
  10833. }
  10834. }
  10835. items.push(max);
  10836. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10837. next = items[i + 1];
  10838. prev = items[i - 1];
  10839. curr = items[i];
  10840. // only add points that breaks the scale linearity
  10841. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  10842. table.push({time: curr, pos: i / (ilen - 1)});
  10843. }
  10844. }
  10845. return table;
  10846. }
  10847. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  10848. function lookup(table, key, value) {
  10849. var lo = 0;
  10850. var hi = table.length - 1;
  10851. var mid, i0, i1;
  10852. while (lo >= 0 && lo <= hi) {
  10853. mid = (lo + hi) >> 1;
  10854. i0 = table[mid - 1] || null;
  10855. i1 = table[mid];
  10856. if (!i0) {
  10857. // given value is outside table (before first item)
  10858. return {lo: null, hi: i1};
  10859. } else if (i1[key] < value) {
  10860. lo = mid + 1;
  10861. } else if (i0[key] > value) {
  10862. hi = mid - 1;
  10863. } else {
  10864. return {lo: i0, hi: i1};
  10865. }
  10866. }
  10867. // given value is outside table (after last item)
  10868. return {lo: i1, hi: null};
  10869. }
  10870. /**
  10871. * Linearly interpolates the given source `value` using the table items `skey` values and
  10872. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  10873. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  10874. * index [0, 1] or [n - 1, n] are used for the interpolation.
  10875. */
  10876. function interpolate$1(table, skey, sval, tkey) {
  10877. var range = lookup(table, skey, sval);
  10878. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  10879. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  10880. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  10881. var span = next[skey] - prev[skey];
  10882. var ratio = span ? (sval - prev[skey]) / span : 0;
  10883. var offset = (next[tkey] - prev[tkey]) * ratio;
  10884. return prev[tkey] + offset;
  10885. }
  10886. function toTimestamp(scale, input) {
  10887. var adapter = scale._adapter;
  10888. var options = scale.options.time;
  10889. var parser = options.parser;
  10890. var format = parser || options.format;
  10891. var value = input;
  10892. if (typeof parser === 'function') {
  10893. value = parser(value);
  10894. }
  10895. // Only parse if its not a timestamp already
  10896. if (!helpers$1.isFinite(value)) {
  10897. value = typeof format === 'string'
  10898. ? adapter.parse(value, format)
  10899. : adapter.parse(value);
  10900. }
  10901. if (value !== null) {
  10902. return +value;
  10903. }
  10904. // Labels are in an incompatible format and no `parser` has been provided.
  10905. // The user might still use the deprecated `format` option for parsing.
  10906. if (!parser && typeof format === 'function') {
  10907. value = format(input);
  10908. // `format` could return something else than a timestamp, if so, parse it
  10909. if (!helpers$1.isFinite(value)) {
  10910. value = adapter.parse(value);
  10911. }
  10912. }
  10913. return value;
  10914. }
  10915. function parse(scale, input) {
  10916. if (helpers$1.isNullOrUndef(input)) {
  10917. return null;
  10918. }
  10919. var options = scale.options.time;
  10920. var value = toTimestamp(scale, scale.getRightValue(input));
  10921. if (value === null) {
  10922. return value;
  10923. }
  10924. if (options.round) {
  10925. value = +scale._adapter.startOf(value, options.round);
  10926. }
  10927. return value;
  10928. }
  10929. /**
  10930. * Returns the number of unit to skip to be able to display up to `capacity` number of ticks
  10931. * in `unit` for the given `min` / `max` range and respecting the interval steps constraints.
  10932. */
  10933. function determineStepSize(min, max, unit, capacity) {
  10934. var range = max - min;
  10935. var interval = INTERVALS[unit];
  10936. var milliseconds = interval.size;
  10937. var steps = interval.steps;
  10938. var i, ilen, factor;
  10939. if (!steps) {
  10940. return Math.ceil(range / (capacity * milliseconds));
  10941. }
  10942. for (i = 0, ilen = steps.length; i < ilen; ++i) {
  10943. factor = steps[i];
  10944. if (Math.ceil(range / (milliseconds * factor)) <= capacity) {
  10945. break;
  10946. }
  10947. }
  10948. return factor;
  10949. }
  10950. /**
  10951. * Figures out what unit results in an appropriate number of auto-generated ticks
  10952. */
  10953. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  10954. var ilen = UNITS.length;
  10955. var i, interval, factor;
  10956. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  10957. interval = INTERVALS[UNITS[i]];
  10958. factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;
  10959. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  10960. return UNITS[i];
  10961. }
  10962. }
  10963. return UNITS[ilen - 1];
  10964. }
  10965. /**
  10966. * Figures out what unit to format a set of ticks with
  10967. */
  10968. function determineUnitForFormatting(scale, ticks, minUnit, min, max) {
  10969. var ilen = UNITS.length;
  10970. var i, unit;
  10971. for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) {
  10972. unit = UNITS[i];
  10973. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= ticks.length) {
  10974. return unit;
  10975. }
  10976. }
  10977. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  10978. }
  10979. function determineMajorUnit(unit) {
  10980. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  10981. if (INTERVALS[UNITS[i]].common) {
  10982. return UNITS[i];
  10983. }
  10984. }
  10985. }
  10986. /**
  10987. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  10988. * `minor` unit, aligned on the `major` unit and using the given scale time `options`.
  10989. * Important: this method can return ticks outside the min and max range, it's the
  10990. * responsibility of the calling code to clamp values if needed.
  10991. */
  10992. function generate(scale, min, max, capacity) {
  10993. var adapter = scale._adapter;
  10994. var options = scale.options;
  10995. var timeOpts = options.time;
  10996. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  10997. var major = determineMajorUnit(minor);
  10998. var stepSize = valueOrDefault$c(timeOpts.stepSize, timeOpts.unitStepSize);
  10999. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  11000. var majorTicksEnabled = options.ticks.major.enabled;
  11001. var interval = INTERVALS[minor];
  11002. var first = min;
  11003. var last = max;
  11004. var ticks = [];
  11005. var time;
  11006. if (!stepSize) {
  11007. stepSize = determineStepSize(min, max, minor, capacity);
  11008. }
  11009. // For 'week' unit, handle the first day of week option
  11010. if (weekday) {
  11011. first = +adapter.startOf(first, 'isoWeek', weekday);
  11012. last = +adapter.startOf(last, 'isoWeek', weekday);
  11013. }
  11014. // Align first/last ticks on unit
  11015. first = +adapter.startOf(first, weekday ? 'day' : minor);
  11016. last = +adapter.startOf(last, weekday ? 'day' : minor);
  11017. // Make sure that the last tick include max
  11018. if (last < max) {
  11019. last = +adapter.add(last, 1, minor);
  11020. }
  11021. time = first;
  11022. if (majorTicksEnabled && major && !weekday && !timeOpts.round) {
  11023. // Align the first tick on the previous `minor` unit aligned on the `major` unit:
  11024. // we first aligned time on the previous `major` unit then add the number of full
  11025. // stepSize there is between first and the previous major time.
  11026. time = +adapter.startOf(time, major);
  11027. time = +adapter.add(time, ~~((first - time) / (interval.size * stepSize)) * stepSize, minor);
  11028. }
  11029. for (; time < last; time = +adapter.add(time, stepSize, minor)) {
  11030. ticks.push(+time);
  11031. }
  11032. ticks.push(+time);
  11033. return ticks;
  11034. }
  11035. /**
  11036. * Returns the start and end offsets from edges in the form of {start, end}
  11037. * where each value is a relative width to the scale and ranges between 0 and 1.
  11038. * They add extra margins on the both sides by scaling down the original scale.
  11039. * Offsets are added when the `offset` option is true.
  11040. */
  11041. function computeOffsets(table, ticks, min, max, options) {
  11042. var start = 0;
  11043. var end = 0;
  11044. var first, last;
  11045. if (options.offset && ticks.length) {
  11046. if (!options.time.min) {
  11047. first = interpolate$1(table, 'time', ticks[0], 'pos');
  11048. if (ticks.length === 1) {
  11049. start = 1 - first;
  11050. } else {
  11051. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  11052. }
  11053. }
  11054. if (!options.time.max) {
  11055. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  11056. if (ticks.length === 1) {
  11057. end = last;
  11058. } else {
  11059. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  11060. }
  11061. }
  11062. }
  11063. return {start: start, end: end};
  11064. }
  11065. function ticksFromTimestamps(scale, values, majorUnit) {
  11066. var ticks = [];
  11067. var i, ilen, value, major;
  11068. for (i = 0, ilen = values.length; i < ilen; ++i) {
  11069. value = values[i];
  11070. major = majorUnit ? value === +scale._adapter.startOf(value, majorUnit) : false;
  11071. ticks.push({
  11072. value: value,
  11073. major: major
  11074. });
  11075. }
  11076. return ticks;
  11077. }
  11078. var defaultConfig$4 = {
  11079. position: 'bottom',
  11080. /**
  11081. * Data distribution along the scale:
  11082. * - 'linear': data are spread according to their time (distances can vary),
  11083. * - 'series': data are spread at the same distance from each other.
  11084. * @see https://github.com/chartjs/Chart.js/pull/4507
  11085. * @since 2.7.0
  11086. */
  11087. distribution: 'linear',
  11088. /**
  11089. * Scale boundary strategy (bypassed by min/max time options)
  11090. * - `data`: make sure data are fully visible, ticks outside are removed
  11091. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  11092. * @see https://github.com/chartjs/Chart.js/pull/4556
  11093. * @since 2.7.0
  11094. */
  11095. bounds: 'data',
  11096. adapters: {},
  11097. time: {
  11098. 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
  11099. format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from https://momentjs.com/docs/#/parsing/string-format/
  11100. unit: false, // false == automatic or override with week, month, year, etc.
  11101. round: false, // none, or override with week, month, year, etc.
  11102. displayFormat: false, // DEPRECATED
  11103. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  11104. minUnit: 'millisecond',
  11105. displayFormats: {}
  11106. },
  11107. ticks: {
  11108. autoSkip: false,
  11109. /**
  11110. * Ticks generation input values:
  11111. * - 'auto': generates "optimal" ticks based on scale size and time options.
  11112. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  11113. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  11114. * @see https://github.com/chartjs/Chart.js/pull/4507
  11115. * @since 2.7.0
  11116. */
  11117. source: 'auto',
  11118. major: {
  11119. enabled: false
  11120. }
  11121. }
  11122. };
  11123. var scale_time = core_scale.extend({
  11124. initialize: function() {
  11125. this.mergeTicksOptions();
  11126. core_scale.prototype.initialize.call(this);
  11127. },
  11128. update: function() {
  11129. var me = this;
  11130. var options = me.options;
  11131. var time = options.time || (options.time = {});
  11132. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  11133. // DEPRECATIONS: output a message only one time per update
  11134. if (time.format) {
  11135. console.warn('options.time.format is deprecated and replaced by options.time.parser.');
  11136. }
  11137. // Backward compatibility: before introducing adapter, `displayFormats` was
  11138. // supposed to contain *all* unit/string pairs but this can't be resolved
  11139. // when loading the scale (adapters are loaded afterward), so let's populate
  11140. // missing formats on update
  11141. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  11142. return core_scale.prototype.update.apply(me, arguments);
  11143. },
  11144. /**
  11145. * Allows data to be referenced via 't' attribute
  11146. */
  11147. getRightValue: function(rawValue) {
  11148. if (rawValue && rawValue.t !== undefined) {
  11149. rawValue = rawValue.t;
  11150. }
  11151. return core_scale.prototype.getRightValue.call(this, rawValue);
  11152. },
  11153. determineDataLimits: function() {
  11154. var me = this;
  11155. var chart = me.chart;
  11156. var adapter = me._adapter;
  11157. var timeOpts = me.options.time;
  11158. var unit = timeOpts.unit || 'day';
  11159. var min = MAX_INTEGER;
  11160. var max = MIN_INTEGER;
  11161. var timestamps = [];
  11162. var datasets = [];
  11163. var labels = [];
  11164. var i, j, ilen, jlen, data, timestamp;
  11165. var dataLabels = chart.data.labels || [];
  11166. // Convert labels to timestamps
  11167. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  11168. labels.push(parse(me, dataLabels[i]));
  11169. }
  11170. // Convert data to timestamps
  11171. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  11172. if (chart.isDatasetVisible(i)) {
  11173. data = chart.data.datasets[i].data;
  11174. // Let's consider that all data have the same format.
  11175. if (helpers$1.isObject(data[0])) {
  11176. datasets[i] = [];
  11177. for (j = 0, jlen = data.length; j < jlen; ++j) {
  11178. timestamp = parse(me, data[j]);
  11179. timestamps.push(timestamp);
  11180. datasets[i][j] = timestamp;
  11181. }
  11182. } else {
  11183. for (j = 0, jlen = labels.length; j < jlen; ++j) {
  11184. timestamps.push(labels[j]);
  11185. }
  11186. datasets[i] = labels.slice(0);
  11187. }
  11188. } else {
  11189. datasets[i] = [];
  11190. }
  11191. }
  11192. if (labels.length) {
  11193. // Sort labels **after** data have been converted
  11194. labels = arrayUnique(labels).sort(sorter);
  11195. min = Math.min(min, labels[0]);
  11196. max = Math.max(max, labels[labels.length - 1]);
  11197. }
  11198. if (timestamps.length) {
  11199. timestamps = arrayUnique(timestamps).sort(sorter);
  11200. min = Math.min(min, timestamps[0]);
  11201. max = Math.max(max, timestamps[timestamps.length - 1]);
  11202. }
  11203. min = parse(me, timeOpts.min) || min;
  11204. max = parse(me, timeOpts.max) || max;
  11205. // In case there is no valid min/max, set limits based on unit time option
  11206. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  11207. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  11208. // Make sure that max is strictly higher than min (required by the lookup table)
  11209. me.min = Math.min(min, max);
  11210. me.max = Math.max(min + 1, max);
  11211. // PRIVATE
  11212. me._horizontal = me.isHorizontal();
  11213. me._table = [];
  11214. me._timestamps = {
  11215. data: timestamps,
  11216. datasets: datasets,
  11217. labels: labels
  11218. };
  11219. },
  11220. buildTicks: function() {
  11221. var me = this;
  11222. var min = me.min;
  11223. var max = me.max;
  11224. var options = me.options;
  11225. var timeOpts = options.time;
  11226. var timestamps = [];
  11227. var ticks = [];
  11228. var i, ilen, timestamp;
  11229. switch (options.ticks.source) {
  11230. case 'data':
  11231. timestamps = me._timestamps.data;
  11232. break;
  11233. case 'labels':
  11234. timestamps = me._timestamps.labels;
  11235. break;
  11236. case 'auto':
  11237. default:
  11238. timestamps = generate(me, min, max, me.getLabelCapacity(min), options);
  11239. }
  11240. if (options.bounds === 'ticks' && timestamps.length) {
  11241. min = timestamps[0];
  11242. max = timestamps[timestamps.length - 1];
  11243. }
  11244. // Enforce limits with user min/max options
  11245. min = parse(me, timeOpts.min) || min;
  11246. max = parse(me, timeOpts.max) || max;
  11247. // Remove ticks outside the min/max range
  11248. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  11249. timestamp = timestamps[i];
  11250. if (timestamp >= min && timestamp <= max) {
  11251. ticks.push(timestamp);
  11252. }
  11253. }
  11254. me.min = min;
  11255. me.max = max;
  11256. // PRIVATE
  11257. me._unit = timeOpts.unit || determineUnitForFormatting(me, ticks, timeOpts.minUnit, me.min, me.max);
  11258. me._majorUnit = determineMajorUnit(me._unit);
  11259. me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
  11260. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  11261. if (options.ticks.reverse) {
  11262. ticks.reverse();
  11263. }
  11264. return ticksFromTimestamps(me, ticks, me._majorUnit);
  11265. },
  11266. getLabelForIndex: function(index, datasetIndex) {
  11267. var me = this;
  11268. var adapter = me._adapter;
  11269. var data = me.chart.data;
  11270. var timeOpts = me.options.time;
  11271. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  11272. var value = data.datasets[datasetIndex].data[index];
  11273. if (helpers$1.isObject(value)) {
  11274. label = me.getRightValue(value);
  11275. }
  11276. if (timeOpts.tooltipFormat) {
  11277. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  11278. }
  11279. if (typeof label === 'string') {
  11280. return label;
  11281. }
  11282. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  11283. },
  11284. /**
  11285. * Function to format an individual tick mark
  11286. * @private
  11287. */
  11288. tickFormatFunction: function(time, index, ticks, format) {
  11289. var me = this;
  11290. var adapter = me._adapter;
  11291. var options = me.options;
  11292. var formats = options.time.displayFormats;
  11293. var minorFormat = formats[me._unit];
  11294. var majorUnit = me._majorUnit;
  11295. var majorFormat = formats[majorUnit];
  11296. var majorTime = +adapter.startOf(time, majorUnit);
  11297. var majorTickOpts = options.ticks.major;
  11298. var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime;
  11299. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  11300. var tickOpts = major ? majorTickOpts : options.ticks.minor;
  11301. var formatter = valueOrDefault$c(tickOpts.callback, tickOpts.userCallback);
  11302. return formatter ? formatter(label, index, ticks) : label;
  11303. },
  11304. convertTicksToLabels: function(ticks) {
  11305. var labels = [];
  11306. var i, ilen;
  11307. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  11308. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  11309. }
  11310. return labels;
  11311. },
  11312. /**
  11313. * @private
  11314. */
  11315. getPixelForOffset: function(time) {
  11316. var me = this;
  11317. var isReverse = me.options.ticks.reverse;
  11318. var size = me._horizontal ? me.width : me.height;
  11319. var start = me._horizontal ? isReverse ? me.right : me.left : isReverse ? me.bottom : me.top;
  11320. var pos = interpolate$1(me._table, 'time', time, 'pos');
  11321. var offset = size * (me._offsets.start + pos) / (me._offsets.start + 1 + me._offsets.end);
  11322. return isReverse ? start - offset : start + offset;
  11323. },
  11324. getPixelForValue: function(value, index, datasetIndex) {
  11325. var me = this;
  11326. var time = null;
  11327. if (index !== undefined && datasetIndex !== undefined) {
  11328. time = me._timestamps.datasets[datasetIndex][index];
  11329. }
  11330. if (time === null) {
  11331. time = parse(me, value);
  11332. }
  11333. if (time !== null) {
  11334. return me.getPixelForOffset(time);
  11335. }
  11336. },
  11337. getPixelForTick: function(index) {
  11338. var ticks = this.getTicks();
  11339. return index >= 0 && index < ticks.length ?
  11340. this.getPixelForOffset(ticks[index].value) :
  11341. null;
  11342. },
  11343. getValueForPixel: function(pixel) {
  11344. var me = this;
  11345. var size = me._horizontal ? me.width : me.height;
  11346. var start = me._horizontal ? me.left : me.top;
  11347. var pos = (size ? (pixel - start) / size : 0) * (me._offsets.start + 1 + me._offsets.start) - me._offsets.end;
  11348. var time = interpolate$1(me._table, 'pos', pos, 'time');
  11349. // DEPRECATION, we should return time directly
  11350. return me._adapter._create(time);
  11351. },
  11352. /**
  11353. * Crude approximation of what the label width might be
  11354. * @private
  11355. */
  11356. getLabelWidth: function(label) {
  11357. var me = this;
  11358. var ticksOpts = me.options.ticks;
  11359. var tickLabelWidth = me.ctx.measureText(label).width;
  11360. var angle = helpers$1.toRadians(ticksOpts.maxRotation);
  11361. var cosRotation = Math.cos(angle);
  11362. var sinRotation = Math.sin(angle);
  11363. var tickFontSize = valueOrDefault$c(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  11364. return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
  11365. },
  11366. /**
  11367. * @private
  11368. */
  11369. getLabelCapacity: function(exampleTime) {
  11370. var me = this;
  11371. // pick the longest format (milliseconds) for guestimation
  11372. var format = me.options.time.displayFormats.millisecond;
  11373. var exampleLabel = me.tickFormatFunction(exampleTime, 0, [], format);
  11374. var tickLabelWidth = me.getLabelWidth(exampleLabel);
  11375. var innerWidth = me.isHorizontal() ? me.width : me.height;
  11376. var capacity = Math.floor(innerWidth / tickLabelWidth);
  11377. return capacity > 0 ? capacity : 1;
  11378. }
  11379. });
  11380. // INTERNAL: static default options, registered in src/index.js
  11381. var _defaults$4 = defaultConfig$4;
  11382. scale_time._defaults = _defaults$4;
  11383. var scales = {
  11384. category: scale_category,
  11385. linear: scale_linear,
  11386. logarithmic: scale_logarithmic,
  11387. radialLinear: scale_radialLinear,
  11388. time: scale_time
  11389. };
  11390. var FORMATS = {
  11391. datetime: 'MMM D, YYYY, h:mm:ss a',
  11392. millisecond: 'h:mm:ss.SSS a',
  11393. second: 'h:mm:ss a',
  11394. minute: 'h:mm a',
  11395. hour: 'hA',
  11396. day: 'MMM D',
  11397. week: 'll',
  11398. month: 'MMM YYYY',
  11399. quarter: '[Q]Q - YYYY',
  11400. year: 'YYYY'
  11401. };
  11402. core_adapters._date.override(typeof moment === 'function' ? {
  11403. _id: 'moment', // DEBUG ONLY
  11404. formats: function() {
  11405. return FORMATS;
  11406. },
  11407. parse: function(value, format) {
  11408. if (typeof value === 'string' && typeof format === 'string') {
  11409. value = moment(value, format);
  11410. } else if (!(value instanceof moment)) {
  11411. value = moment(value);
  11412. }
  11413. return value.isValid() ? value.valueOf() : null;
  11414. },
  11415. format: function(time, format) {
  11416. return moment(time).format(format);
  11417. },
  11418. add: function(time, amount, unit) {
  11419. return moment(time).add(amount, unit).valueOf();
  11420. },
  11421. diff: function(max, min, unit) {
  11422. return moment.duration(moment(max).diff(moment(min))).as(unit);
  11423. },
  11424. startOf: function(time, unit, weekday) {
  11425. time = moment(time);
  11426. if (unit === 'isoWeek') {
  11427. return time.isoWeekday(weekday).valueOf();
  11428. }
  11429. return time.startOf(unit).valueOf();
  11430. },
  11431. endOf: function(time, unit) {
  11432. return moment(time).endOf(unit).valueOf();
  11433. },
  11434. // DEPRECATIONS
  11435. /**
  11436. * Provided for backward compatibility with scale.getValueForPixel().
  11437. * @deprecated since version 2.8.0
  11438. * @todo remove at version 3
  11439. * @private
  11440. */
  11441. _create: function(time) {
  11442. return moment(time);
  11443. },
  11444. } : {});
  11445. core_defaults._set('global', {
  11446. plugins: {
  11447. filler: {
  11448. propagate: true
  11449. }
  11450. }
  11451. });
  11452. var mappers = {
  11453. dataset: function(source) {
  11454. var index = source.fill;
  11455. var chart = source.chart;
  11456. var meta = chart.getDatasetMeta(index);
  11457. var visible = meta && chart.isDatasetVisible(index);
  11458. var points = (visible && meta.dataset._children) || [];
  11459. var length = points.length || 0;
  11460. return !length ? null : function(point, i) {
  11461. return (i < length && points[i]._view) || null;
  11462. };
  11463. },
  11464. boundary: function(source) {
  11465. var boundary = source.boundary;
  11466. var x = boundary ? boundary.x : null;
  11467. var y = boundary ? boundary.y : null;
  11468. return function(point) {
  11469. return {
  11470. x: x === null ? point.x : x,
  11471. y: y === null ? point.y : y,
  11472. };
  11473. };
  11474. }
  11475. };
  11476. // @todo if (fill[0] === '#')
  11477. function decodeFill(el, index, count) {
  11478. var model = el._model || {};
  11479. var fill = model.fill;
  11480. var target;
  11481. if (fill === undefined) {
  11482. fill = !!model.backgroundColor;
  11483. }
  11484. if (fill === false || fill === null) {
  11485. return false;
  11486. }
  11487. if (fill === true) {
  11488. return 'origin';
  11489. }
  11490. target = parseFloat(fill, 10);
  11491. if (isFinite(target) && Math.floor(target) === target) {
  11492. if (fill[0] === '-' || fill[0] === '+') {
  11493. target = index + target;
  11494. }
  11495. if (target === index || target < 0 || target >= count) {
  11496. return false;
  11497. }
  11498. return target;
  11499. }
  11500. switch (fill) {
  11501. // compatibility
  11502. case 'bottom':
  11503. return 'start';
  11504. case 'top':
  11505. return 'end';
  11506. case 'zero':
  11507. return 'origin';
  11508. // supported boundaries
  11509. case 'origin':
  11510. case 'start':
  11511. case 'end':
  11512. return fill;
  11513. // invalid fill values
  11514. default:
  11515. return false;
  11516. }
  11517. }
  11518. function computeBoundary(source) {
  11519. var model = source.el._model || {};
  11520. var scale = source.el._scale || {};
  11521. var fill = source.fill;
  11522. var target = null;
  11523. var horizontal;
  11524. if (isFinite(fill)) {
  11525. return null;
  11526. }
  11527. // Backward compatibility: until v3, we still need to support boundary values set on
  11528. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  11529. // controllers might still use it (e.g. the Smith chart).
  11530. if (fill === 'start') {
  11531. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  11532. } else if (fill === 'end') {
  11533. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  11534. } else if (model.scaleZero !== undefined) {
  11535. target = model.scaleZero;
  11536. } else if (scale.getBasePosition) {
  11537. target = scale.getBasePosition();
  11538. } else if (scale.getBasePixel) {
  11539. target = scale.getBasePixel();
  11540. }
  11541. if (target !== undefined && target !== null) {
  11542. if (target.x !== undefined && target.y !== undefined) {
  11543. return target;
  11544. }
  11545. if (helpers$1.isFinite(target)) {
  11546. horizontal = scale.isHorizontal();
  11547. return {
  11548. x: horizontal ? target : null,
  11549. y: horizontal ? null : target
  11550. };
  11551. }
  11552. }
  11553. return null;
  11554. }
  11555. function resolveTarget(sources, index, propagate) {
  11556. var source = sources[index];
  11557. var fill = source.fill;
  11558. var visited = [index];
  11559. var target;
  11560. if (!propagate) {
  11561. return fill;
  11562. }
  11563. while (fill !== false && visited.indexOf(fill) === -1) {
  11564. if (!isFinite(fill)) {
  11565. return fill;
  11566. }
  11567. target = sources[fill];
  11568. if (!target) {
  11569. return false;
  11570. }
  11571. if (target.visible) {
  11572. return fill;
  11573. }
  11574. visited.push(fill);
  11575. fill = target.fill;
  11576. }
  11577. return false;
  11578. }
  11579. function createMapper(source) {
  11580. var fill = source.fill;
  11581. var type = 'dataset';
  11582. if (fill === false) {
  11583. return null;
  11584. }
  11585. if (!isFinite(fill)) {
  11586. type = 'boundary';
  11587. }
  11588. return mappers[type](source);
  11589. }
  11590. function isDrawable(point) {
  11591. return point && !point.skip;
  11592. }
  11593. function drawArea(ctx, curve0, curve1, len0, len1) {
  11594. var i;
  11595. if (!len0 || !len1) {
  11596. return;
  11597. }
  11598. // building first area curve (normal)
  11599. ctx.moveTo(curve0[0].x, curve0[0].y);
  11600. for (i = 1; i < len0; ++i) {
  11601. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  11602. }
  11603. // joining the two area curves
  11604. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  11605. // building opposite area curve (reverse)
  11606. for (i = len1 - 1; i > 0; --i) {
  11607. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  11608. }
  11609. }
  11610. function doFill(ctx, points, mapper, view, color, loop) {
  11611. var count = points.length;
  11612. var span = view.spanGaps;
  11613. var curve0 = [];
  11614. var curve1 = [];
  11615. var len0 = 0;
  11616. var len1 = 0;
  11617. var i, ilen, index, p0, p1, d0, d1;
  11618. ctx.beginPath();
  11619. for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {
  11620. index = i % count;
  11621. p0 = points[index]._view;
  11622. p1 = mapper(p0, index, view);
  11623. d0 = isDrawable(p0);
  11624. d1 = isDrawable(p1);
  11625. if (d0 && d1) {
  11626. len0 = curve0.push(p0);
  11627. len1 = curve1.push(p1);
  11628. } else if (len0 && len1) {
  11629. if (!span) {
  11630. drawArea(ctx, curve0, curve1, len0, len1);
  11631. len0 = len1 = 0;
  11632. curve0 = [];
  11633. curve1 = [];
  11634. } else {
  11635. if (d0) {
  11636. curve0.push(p0);
  11637. }
  11638. if (d1) {
  11639. curve1.push(p1);
  11640. }
  11641. }
  11642. }
  11643. }
  11644. drawArea(ctx, curve0, curve1, len0, len1);
  11645. ctx.closePath();
  11646. ctx.fillStyle = color;
  11647. ctx.fill();
  11648. }
  11649. var plugin_filler = {
  11650. id: 'filler',
  11651. afterDatasetsUpdate: function(chart, options) {
  11652. var count = (chart.data.datasets || []).length;
  11653. var propagate = options.propagate;
  11654. var sources = [];
  11655. var meta, i, el, source;
  11656. for (i = 0; i < count; ++i) {
  11657. meta = chart.getDatasetMeta(i);
  11658. el = meta.dataset;
  11659. source = null;
  11660. if (el && el._model && el instanceof elements.Line) {
  11661. source = {
  11662. visible: chart.isDatasetVisible(i),
  11663. fill: decodeFill(el, i, count),
  11664. chart: chart,
  11665. el: el
  11666. };
  11667. }
  11668. meta.$filler = source;
  11669. sources.push(source);
  11670. }
  11671. for (i = 0; i < count; ++i) {
  11672. source = sources[i];
  11673. if (!source) {
  11674. continue;
  11675. }
  11676. source.fill = resolveTarget(sources, i, propagate);
  11677. source.boundary = computeBoundary(source);
  11678. source.mapper = createMapper(source);
  11679. }
  11680. },
  11681. beforeDatasetDraw: function(chart, args) {
  11682. var meta = args.meta.$filler;
  11683. if (!meta) {
  11684. return;
  11685. }
  11686. var ctx = chart.ctx;
  11687. var el = meta.el;
  11688. var view = el._view;
  11689. var points = el._children || [];
  11690. var mapper = meta.mapper;
  11691. var color = view.backgroundColor || core_defaults.global.defaultColor;
  11692. if (mapper && color && points.length) {
  11693. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  11694. doFill(ctx, points, mapper, view, color, el._loop);
  11695. helpers$1.canvas.unclipArea(ctx);
  11696. }
  11697. }
  11698. };
  11699. var noop$1 = helpers$1.noop;
  11700. var valueOrDefault$d = helpers$1.valueOrDefault;
  11701. core_defaults._set('global', {
  11702. legend: {
  11703. display: true,
  11704. position: 'top',
  11705. fullWidth: true,
  11706. reverse: false,
  11707. weight: 1000,
  11708. // a callback that will handle
  11709. onClick: function(e, legendItem) {
  11710. var index = legendItem.datasetIndex;
  11711. var ci = this.chart;
  11712. var meta = ci.getDatasetMeta(index);
  11713. // See controller.isDatasetVisible comment
  11714. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  11715. // We hid a dataset ... rerender the chart
  11716. ci.update();
  11717. },
  11718. onHover: null,
  11719. onLeave: null,
  11720. labels: {
  11721. boxWidth: 40,
  11722. padding: 10,
  11723. // Generates labels shown in the legend
  11724. // Valid properties to return:
  11725. // text : text to display
  11726. // fillStyle : fill of coloured box
  11727. // strokeStyle: stroke of coloured box
  11728. // hidden : if this legend item refers to a hidden item
  11729. // lineCap : cap style for line
  11730. // lineDash
  11731. // lineDashOffset :
  11732. // lineJoin :
  11733. // lineWidth :
  11734. generateLabels: function(chart) {
  11735. var data = chart.data;
  11736. return helpers$1.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
  11737. return {
  11738. text: dataset.label,
  11739. fillStyle: (!helpers$1.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
  11740. hidden: !chart.isDatasetVisible(i),
  11741. lineCap: dataset.borderCapStyle,
  11742. lineDash: dataset.borderDash,
  11743. lineDashOffset: dataset.borderDashOffset,
  11744. lineJoin: dataset.borderJoinStyle,
  11745. lineWidth: dataset.borderWidth,
  11746. strokeStyle: dataset.borderColor,
  11747. pointStyle: dataset.pointStyle,
  11748. // Below is extra data used for toggling the datasets
  11749. datasetIndex: i
  11750. };
  11751. }, this) : [];
  11752. }
  11753. }
  11754. },
  11755. legendCallback: function(chart) {
  11756. var text = [];
  11757. text.push('<ul class="' + chart.id + '-legend">');
  11758. for (var i = 0; i < chart.data.datasets.length; i++) {
  11759. text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
  11760. if (chart.data.datasets[i].label) {
  11761. text.push(chart.data.datasets[i].label);
  11762. }
  11763. text.push('</li>');
  11764. }
  11765. text.push('</ul>');
  11766. return text.join('');
  11767. }
  11768. });
  11769. /**
  11770. * Helper function to get the box width based on the usePointStyle option
  11771. * @param {object} labelopts - the label options on the legend
  11772. * @param {number} fontSize - the label font size
  11773. * @return {number} width of the color box area
  11774. */
  11775. function getBoxWidth(labelOpts, fontSize) {
  11776. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  11777. fontSize :
  11778. labelOpts.boxWidth;
  11779. }
  11780. /**
  11781. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  11782. */
  11783. var Legend = core_element.extend({
  11784. initialize: function(config) {
  11785. helpers$1.extend(this, config);
  11786. // Contains hit boxes for each dataset (in dataset order)
  11787. this.legendHitBoxes = [];
  11788. /**
  11789. * @private
  11790. */
  11791. this._hoveredItem = null;
  11792. // Are we in doughnut mode which has a different data type
  11793. this.doughnutMode = false;
  11794. },
  11795. // These methods are ordered by lifecycle. Utilities then follow.
  11796. // Any function defined here is inherited by all legend types.
  11797. // Any function can be extended by the legend type
  11798. beforeUpdate: noop$1,
  11799. update: function(maxWidth, maxHeight, margins) {
  11800. var me = this;
  11801. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  11802. me.beforeUpdate();
  11803. // Absorb the master measurements
  11804. me.maxWidth = maxWidth;
  11805. me.maxHeight = maxHeight;
  11806. me.margins = margins;
  11807. // Dimensions
  11808. me.beforeSetDimensions();
  11809. me.setDimensions();
  11810. me.afterSetDimensions();
  11811. // Labels
  11812. me.beforeBuildLabels();
  11813. me.buildLabels();
  11814. me.afterBuildLabels();
  11815. // Fit
  11816. me.beforeFit();
  11817. me.fit();
  11818. me.afterFit();
  11819. //
  11820. me.afterUpdate();
  11821. return me.minSize;
  11822. },
  11823. afterUpdate: noop$1,
  11824. //
  11825. beforeSetDimensions: noop$1,
  11826. setDimensions: function() {
  11827. var me = this;
  11828. // Set the unconstrained dimension before label rotation
  11829. if (me.isHorizontal()) {
  11830. // Reset position before calculating rotation
  11831. me.width = me.maxWidth;
  11832. me.left = 0;
  11833. me.right = me.width;
  11834. } else {
  11835. me.height = me.maxHeight;
  11836. // Reset position before calculating rotation
  11837. me.top = 0;
  11838. me.bottom = me.height;
  11839. }
  11840. // Reset padding
  11841. me.paddingLeft = 0;
  11842. me.paddingTop = 0;
  11843. me.paddingRight = 0;
  11844. me.paddingBottom = 0;
  11845. // Reset minSize
  11846. me.minSize = {
  11847. width: 0,
  11848. height: 0
  11849. };
  11850. },
  11851. afterSetDimensions: noop$1,
  11852. //
  11853. beforeBuildLabels: noop$1,
  11854. buildLabels: function() {
  11855. var me = this;
  11856. var labelOpts = me.options.labels || {};
  11857. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  11858. if (labelOpts.filter) {
  11859. legendItems = legendItems.filter(function(item) {
  11860. return labelOpts.filter(item, me.chart.data);
  11861. });
  11862. }
  11863. if (me.options.reverse) {
  11864. legendItems.reverse();
  11865. }
  11866. me.legendItems = legendItems;
  11867. },
  11868. afterBuildLabels: noop$1,
  11869. //
  11870. beforeFit: noop$1,
  11871. fit: function() {
  11872. var me = this;
  11873. var opts = me.options;
  11874. var labelOpts = opts.labels;
  11875. var display = opts.display;
  11876. var ctx = me.ctx;
  11877. var labelFont = helpers$1.options._parseFont(labelOpts);
  11878. var fontSize = labelFont.size;
  11879. // Reset hit boxes
  11880. var hitboxes = me.legendHitBoxes = [];
  11881. var minSize = me.minSize;
  11882. var isHorizontal = me.isHorizontal();
  11883. if (isHorizontal) {
  11884. minSize.width = me.maxWidth; // fill all the width
  11885. minSize.height = display ? 10 : 0;
  11886. } else {
  11887. minSize.width = display ? 10 : 0;
  11888. minSize.height = me.maxHeight; // fill all the height
  11889. }
  11890. // Increase sizes here
  11891. if (display) {
  11892. ctx.font = labelFont.string;
  11893. if (isHorizontal) {
  11894. // Labels
  11895. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  11896. var lineWidths = me.lineWidths = [0];
  11897. var totalHeight = 0;
  11898. ctx.textAlign = 'left';
  11899. ctx.textBaseline = 'top';
  11900. helpers$1.each(me.legendItems, function(legendItem, i) {
  11901. var boxWidth = getBoxWidth(labelOpts, fontSize);
  11902. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  11903. if (i === 0 || lineWidths[lineWidths.length - 1] + width + labelOpts.padding > minSize.width) {
  11904. totalHeight += fontSize + labelOpts.padding;
  11905. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = labelOpts.padding;
  11906. }
  11907. // Store the hitbox width and height here. Final position will be updated in `draw`
  11908. hitboxes[i] = {
  11909. left: 0,
  11910. top: 0,
  11911. width: width,
  11912. height: fontSize
  11913. };
  11914. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  11915. });
  11916. minSize.height += totalHeight;
  11917. } else {
  11918. var vPadding = labelOpts.padding;
  11919. var columnWidths = me.columnWidths = [];
  11920. var totalWidth = labelOpts.padding;
  11921. var currentColWidth = 0;
  11922. var currentColHeight = 0;
  11923. var itemHeight = fontSize + vPadding;
  11924. helpers$1.each(me.legendItems, function(legendItem, i) {
  11925. var boxWidth = getBoxWidth(labelOpts, fontSize);
  11926. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  11927. // If too tall, go to new column
  11928. if (i > 0 && currentColHeight + itemHeight > minSize.height - vPadding) {
  11929. totalWidth += currentColWidth + labelOpts.padding;
  11930. columnWidths.push(currentColWidth); // previous column width
  11931. currentColWidth = 0;
  11932. currentColHeight = 0;
  11933. }
  11934. // Get max width
  11935. currentColWidth = Math.max(currentColWidth, itemWidth);
  11936. currentColHeight += itemHeight;
  11937. // Store the hitbox width and height here. Final position will be updated in `draw`
  11938. hitboxes[i] = {
  11939. left: 0,
  11940. top: 0,
  11941. width: itemWidth,
  11942. height: fontSize
  11943. };
  11944. });
  11945. totalWidth += currentColWidth;
  11946. columnWidths.push(currentColWidth);
  11947. minSize.width += totalWidth;
  11948. }
  11949. }
  11950. me.width = minSize.width;
  11951. me.height = minSize.height;
  11952. },
  11953. afterFit: noop$1,
  11954. // Shared Methods
  11955. isHorizontal: function() {
  11956. return this.options.position === 'top' || this.options.position === 'bottom';
  11957. },
  11958. // Actually draw the legend on the canvas
  11959. draw: function() {
  11960. var me = this;
  11961. var opts = me.options;
  11962. var labelOpts = opts.labels;
  11963. var globalDefaults = core_defaults.global;
  11964. var defaultColor = globalDefaults.defaultColor;
  11965. var lineDefault = globalDefaults.elements.line;
  11966. var legendWidth = me.width;
  11967. var lineWidths = me.lineWidths;
  11968. if (opts.display) {
  11969. var ctx = me.ctx;
  11970. var fontColor = valueOrDefault$d(labelOpts.fontColor, globalDefaults.defaultFontColor);
  11971. var labelFont = helpers$1.options._parseFont(labelOpts);
  11972. var fontSize = labelFont.size;
  11973. var cursor;
  11974. // Canvas setup
  11975. ctx.textAlign = 'left';
  11976. ctx.textBaseline = 'middle';
  11977. ctx.lineWidth = 0.5;
  11978. ctx.strokeStyle = fontColor; // for strikethrough effect
  11979. ctx.fillStyle = fontColor; // render in correct colour
  11980. ctx.font = labelFont.string;
  11981. var boxWidth = getBoxWidth(labelOpts, fontSize);
  11982. var hitboxes = me.legendHitBoxes;
  11983. // current position
  11984. var drawLegendBox = function(x, y, legendItem) {
  11985. if (isNaN(boxWidth) || boxWidth <= 0) {
  11986. return;
  11987. }
  11988. // Set the ctx for the box
  11989. ctx.save();
  11990. var lineWidth = valueOrDefault$d(legendItem.lineWidth, lineDefault.borderWidth);
  11991. ctx.fillStyle = valueOrDefault$d(legendItem.fillStyle, defaultColor);
  11992. ctx.lineCap = valueOrDefault$d(legendItem.lineCap, lineDefault.borderCapStyle);
  11993. ctx.lineDashOffset = valueOrDefault$d(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  11994. ctx.lineJoin = valueOrDefault$d(legendItem.lineJoin, lineDefault.borderJoinStyle);
  11995. ctx.lineWidth = lineWidth;
  11996. ctx.strokeStyle = valueOrDefault$d(legendItem.strokeStyle, defaultColor);
  11997. if (ctx.setLineDash) {
  11998. // IE 9 and 10 do not support line dash
  11999. ctx.setLineDash(valueOrDefault$d(legendItem.lineDash, lineDefault.borderDash));
  12000. }
  12001. if (opts.labels && opts.labels.usePointStyle) {
  12002. // Recalculate x and y for drawPoint() because its expecting
  12003. // x and y to be center of figure (instead of top left)
  12004. var radius = boxWidth * Math.SQRT2 / 2;
  12005. var centerX = x + boxWidth / 2;
  12006. var centerY = y + fontSize / 2;
  12007. // Draw pointStyle as legend symbol
  12008. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
  12009. } else {
  12010. // Draw box as legend symbol
  12011. if (lineWidth !== 0) {
  12012. ctx.strokeRect(x, y, boxWidth, fontSize);
  12013. }
  12014. ctx.fillRect(x, y, boxWidth, fontSize);
  12015. }
  12016. ctx.restore();
  12017. };
  12018. var fillText = function(x, y, legendItem, textWidth) {
  12019. var halfFontSize = fontSize / 2;
  12020. var xLeft = boxWidth + halfFontSize + x;
  12021. var yMiddle = y + halfFontSize;
  12022. ctx.fillText(legendItem.text, xLeft, yMiddle);
  12023. if (legendItem.hidden) {
  12024. // Strikethrough the text if hidden
  12025. ctx.beginPath();
  12026. ctx.lineWidth = 2;
  12027. ctx.moveTo(xLeft, yMiddle);
  12028. ctx.lineTo(xLeft + textWidth, yMiddle);
  12029. ctx.stroke();
  12030. }
  12031. };
  12032. // Horizontal
  12033. var isHorizontal = me.isHorizontal();
  12034. if (isHorizontal) {
  12035. cursor = {
  12036. x: me.left + ((legendWidth - lineWidths[0]) / 2) + labelOpts.padding,
  12037. y: me.top + labelOpts.padding,
  12038. line: 0
  12039. };
  12040. } else {
  12041. cursor = {
  12042. x: me.left + labelOpts.padding,
  12043. y: me.top + labelOpts.padding,
  12044. line: 0
  12045. };
  12046. }
  12047. var itemHeight = fontSize + labelOpts.padding;
  12048. helpers$1.each(me.legendItems, function(legendItem, i) {
  12049. var textWidth = ctx.measureText(legendItem.text).width;
  12050. var width = boxWidth + (fontSize / 2) + textWidth;
  12051. var x = cursor.x;
  12052. var y = cursor.y;
  12053. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  12054. // instead of me.right and me.bottom because me.width and me.height
  12055. // may have been changed since me.minSize was calculated
  12056. if (isHorizontal) {
  12057. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  12058. y = cursor.y += itemHeight;
  12059. cursor.line++;
  12060. x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2) + labelOpts.padding;
  12061. }
  12062. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  12063. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  12064. y = cursor.y = me.top + labelOpts.padding;
  12065. cursor.line++;
  12066. }
  12067. drawLegendBox(x, y, legendItem);
  12068. hitboxes[i].left = x;
  12069. hitboxes[i].top = y;
  12070. // Fill the actual label
  12071. fillText(x, y, legendItem, textWidth);
  12072. if (isHorizontal) {
  12073. cursor.x += width + labelOpts.padding;
  12074. } else {
  12075. cursor.y += itemHeight;
  12076. }
  12077. });
  12078. }
  12079. },
  12080. /**
  12081. * @private
  12082. */
  12083. _getLegendItemAt: function(x, y) {
  12084. var me = this;
  12085. var i, hitBox, lh;
  12086. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  12087. // See if we are touching one of the dataset boxes
  12088. lh = me.legendHitBoxes;
  12089. for (i = 0; i < lh.length; ++i) {
  12090. hitBox = lh[i];
  12091. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  12092. // Touching an element
  12093. return me.legendItems[i];
  12094. }
  12095. }
  12096. }
  12097. return null;
  12098. },
  12099. /**
  12100. * Handle an event
  12101. * @private
  12102. * @param {IEvent} event - The event to handle
  12103. */
  12104. handleEvent: function(e) {
  12105. var me = this;
  12106. var opts = me.options;
  12107. var type = e.type === 'mouseup' ? 'click' : e.type;
  12108. var hoveredItem;
  12109. if (type === 'mousemove') {
  12110. if (!opts.onHover && !opts.onLeave) {
  12111. return;
  12112. }
  12113. } else if (type === 'click') {
  12114. if (!opts.onClick) {
  12115. return;
  12116. }
  12117. } else {
  12118. return;
  12119. }
  12120. // Chart event already has relative position in it
  12121. hoveredItem = me._getLegendItemAt(e.x, e.y);
  12122. if (type === 'click') {
  12123. if (hoveredItem && opts.onClick) {
  12124. // use e.native for backwards compatibility
  12125. opts.onClick.call(me, e.native, hoveredItem);
  12126. }
  12127. } else {
  12128. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  12129. if (me._hoveredItem) {
  12130. opts.onLeave.call(me, e.native, me._hoveredItem);
  12131. }
  12132. me._hoveredItem = hoveredItem;
  12133. }
  12134. if (opts.onHover && hoveredItem) {
  12135. // use e.native for backwards compatibility
  12136. opts.onHover.call(me, e.native, hoveredItem);
  12137. }
  12138. }
  12139. }
  12140. });
  12141. function createNewLegendAndAttach(chart, legendOpts) {
  12142. var legend = new Legend({
  12143. ctx: chart.ctx,
  12144. options: legendOpts,
  12145. chart: chart
  12146. });
  12147. core_layouts.configure(chart, legend, legendOpts);
  12148. core_layouts.addBox(chart, legend);
  12149. chart.legend = legend;
  12150. }
  12151. var plugin_legend = {
  12152. id: 'legend',
  12153. /**
  12154. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  12155. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  12156. * the plugin, which one will be re-exposed in the chart.js file.
  12157. * https://github.com/chartjs/Chart.js/pull/2640
  12158. * @private
  12159. */
  12160. _element: Legend,
  12161. beforeInit: function(chart) {
  12162. var legendOpts = chart.options.legend;
  12163. if (legendOpts) {
  12164. createNewLegendAndAttach(chart, legendOpts);
  12165. }
  12166. },
  12167. beforeUpdate: function(chart) {
  12168. var legendOpts = chart.options.legend;
  12169. var legend = chart.legend;
  12170. if (legendOpts) {
  12171. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  12172. if (legend) {
  12173. core_layouts.configure(chart, legend, legendOpts);
  12174. legend.options = legendOpts;
  12175. } else {
  12176. createNewLegendAndAttach(chart, legendOpts);
  12177. }
  12178. } else if (legend) {
  12179. core_layouts.removeBox(chart, legend);
  12180. delete chart.legend;
  12181. }
  12182. },
  12183. afterEvent: function(chart, e) {
  12184. var legend = chart.legend;
  12185. if (legend) {
  12186. legend.handleEvent(e);
  12187. }
  12188. }
  12189. };
  12190. var noop$2 = helpers$1.noop;
  12191. core_defaults._set('global', {
  12192. title: {
  12193. display: false,
  12194. fontStyle: 'bold',
  12195. fullWidth: true,
  12196. padding: 10,
  12197. position: 'top',
  12198. text: '',
  12199. weight: 2000 // by default greater than legend (1000) to be above
  12200. }
  12201. });
  12202. /**
  12203. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  12204. */
  12205. var Title = core_element.extend({
  12206. initialize: function(config) {
  12207. var me = this;
  12208. helpers$1.extend(me, config);
  12209. // Contains hit boxes for each dataset (in dataset order)
  12210. me.legendHitBoxes = [];
  12211. },
  12212. // These methods are ordered by lifecycle. Utilities then follow.
  12213. beforeUpdate: noop$2,
  12214. update: function(maxWidth, maxHeight, margins) {
  12215. var me = this;
  12216. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  12217. me.beforeUpdate();
  12218. // Absorb the master measurements
  12219. me.maxWidth = maxWidth;
  12220. me.maxHeight = maxHeight;
  12221. me.margins = margins;
  12222. // Dimensions
  12223. me.beforeSetDimensions();
  12224. me.setDimensions();
  12225. me.afterSetDimensions();
  12226. // Labels
  12227. me.beforeBuildLabels();
  12228. me.buildLabels();
  12229. me.afterBuildLabels();
  12230. // Fit
  12231. me.beforeFit();
  12232. me.fit();
  12233. me.afterFit();
  12234. //
  12235. me.afterUpdate();
  12236. return me.minSize;
  12237. },
  12238. afterUpdate: noop$2,
  12239. //
  12240. beforeSetDimensions: noop$2,
  12241. setDimensions: function() {
  12242. var me = this;
  12243. // Set the unconstrained dimension before label rotation
  12244. if (me.isHorizontal()) {
  12245. // Reset position before calculating rotation
  12246. me.width = me.maxWidth;
  12247. me.left = 0;
  12248. me.right = me.width;
  12249. } else {
  12250. me.height = me.maxHeight;
  12251. // Reset position before calculating rotation
  12252. me.top = 0;
  12253. me.bottom = me.height;
  12254. }
  12255. // Reset padding
  12256. me.paddingLeft = 0;
  12257. me.paddingTop = 0;
  12258. me.paddingRight = 0;
  12259. me.paddingBottom = 0;
  12260. // Reset minSize
  12261. me.minSize = {
  12262. width: 0,
  12263. height: 0
  12264. };
  12265. },
  12266. afterSetDimensions: noop$2,
  12267. //
  12268. beforeBuildLabels: noop$2,
  12269. buildLabels: noop$2,
  12270. afterBuildLabels: noop$2,
  12271. //
  12272. beforeFit: noop$2,
  12273. fit: function() {
  12274. var me = this;
  12275. var opts = me.options;
  12276. var display = opts.display;
  12277. var minSize = me.minSize;
  12278. var lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  12279. var fontOpts = helpers$1.options._parseFont(opts);
  12280. var textSize = display ? (lineCount * fontOpts.lineHeight) + (opts.padding * 2) : 0;
  12281. if (me.isHorizontal()) {
  12282. minSize.width = me.maxWidth; // fill all the width
  12283. minSize.height = textSize;
  12284. } else {
  12285. minSize.width = textSize;
  12286. minSize.height = me.maxHeight; // fill all the height
  12287. }
  12288. me.width = minSize.width;
  12289. me.height = minSize.height;
  12290. },
  12291. afterFit: noop$2,
  12292. // Shared Methods
  12293. isHorizontal: function() {
  12294. var pos = this.options.position;
  12295. return pos === 'top' || pos === 'bottom';
  12296. },
  12297. // Actually draw the title block on the canvas
  12298. draw: function() {
  12299. var me = this;
  12300. var ctx = me.ctx;
  12301. var opts = me.options;
  12302. if (opts.display) {
  12303. var fontOpts = helpers$1.options._parseFont(opts);
  12304. var lineHeight = fontOpts.lineHeight;
  12305. var offset = lineHeight / 2 + opts.padding;
  12306. var rotation = 0;
  12307. var top = me.top;
  12308. var left = me.left;
  12309. var bottom = me.bottom;
  12310. var right = me.right;
  12311. var maxWidth, titleX, titleY;
  12312. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  12313. ctx.font = fontOpts.string;
  12314. // Horizontal
  12315. if (me.isHorizontal()) {
  12316. titleX = left + ((right - left) / 2); // midpoint of the width
  12317. titleY = top + offset;
  12318. maxWidth = right - left;
  12319. } else {
  12320. titleX = opts.position === 'left' ? left + offset : right - offset;
  12321. titleY = top + ((bottom - top) / 2);
  12322. maxWidth = bottom - top;
  12323. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  12324. }
  12325. ctx.save();
  12326. ctx.translate(titleX, titleY);
  12327. ctx.rotate(rotation);
  12328. ctx.textAlign = 'center';
  12329. ctx.textBaseline = 'middle';
  12330. var text = opts.text;
  12331. if (helpers$1.isArray(text)) {
  12332. var y = 0;
  12333. for (var i = 0; i < text.length; ++i) {
  12334. ctx.fillText(text[i], 0, y, maxWidth);
  12335. y += lineHeight;
  12336. }
  12337. } else {
  12338. ctx.fillText(text, 0, 0, maxWidth);
  12339. }
  12340. ctx.restore();
  12341. }
  12342. }
  12343. });
  12344. function createNewTitleBlockAndAttach(chart, titleOpts) {
  12345. var title = new Title({
  12346. ctx: chart.ctx,
  12347. options: titleOpts,
  12348. chart: chart
  12349. });
  12350. core_layouts.configure(chart, title, titleOpts);
  12351. core_layouts.addBox(chart, title);
  12352. chart.titleBlock = title;
  12353. }
  12354. var plugin_title = {
  12355. id: 'title',
  12356. /**
  12357. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  12358. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  12359. * the plugin, which one will be re-exposed in the chart.js file.
  12360. * https://github.com/chartjs/Chart.js/pull/2640
  12361. * @private
  12362. */
  12363. _element: Title,
  12364. beforeInit: function(chart) {
  12365. var titleOpts = chart.options.title;
  12366. if (titleOpts) {
  12367. createNewTitleBlockAndAttach(chart, titleOpts);
  12368. }
  12369. },
  12370. beforeUpdate: function(chart) {
  12371. var titleOpts = chart.options.title;
  12372. var titleBlock = chart.titleBlock;
  12373. if (titleOpts) {
  12374. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  12375. if (titleBlock) {
  12376. core_layouts.configure(chart, titleBlock, titleOpts);
  12377. titleBlock.options = titleOpts;
  12378. } else {
  12379. createNewTitleBlockAndAttach(chart, titleOpts);
  12380. }
  12381. } else if (titleBlock) {
  12382. core_layouts.removeBox(chart, titleBlock);
  12383. delete chart.titleBlock;
  12384. }
  12385. }
  12386. };
  12387. var plugins = {};
  12388. var filler = plugin_filler;
  12389. var legend = plugin_legend;
  12390. var title = plugin_title;
  12391. plugins.filler = filler;
  12392. plugins.legend = legend;
  12393. plugins.title = title;
  12394. /**
  12395. * @namespace Chart
  12396. */
  12397. core_controller.helpers = helpers$1;
  12398. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  12399. core_helpers(core_controller);
  12400. core_controller._adapters = core_adapters;
  12401. core_controller.Animation = core_animation;
  12402. core_controller.animationService = core_animations;
  12403. core_controller.controllers = controllers;
  12404. core_controller.DatasetController = core_datasetController;
  12405. core_controller.defaults = core_defaults;
  12406. core_controller.Element = core_element;
  12407. core_controller.elements = elements;
  12408. core_controller.Interaction = core_interaction;
  12409. core_controller.layouts = core_layouts;
  12410. core_controller.platform = platform;
  12411. core_controller.plugins = core_plugins;
  12412. core_controller.Scale = core_scale;
  12413. core_controller.scaleService = core_scaleService;
  12414. core_controller.Ticks = core_ticks;
  12415. core_controller.Tooltip = core_tooltip;
  12416. // Register built-in scales
  12417. core_controller.helpers.each(scales, function(scale, type) {
  12418. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  12419. });
  12420. // Load to register built-in adapters (as side effects)
  12421. // Loading built-in plugins
  12422. for (var k in plugins) {
  12423. if (plugins.hasOwnProperty(k)) {
  12424. core_controller.plugins.register(plugins[k]);
  12425. }
  12426. }
  12427. core_controller.platform.initialize();
  12428. var src = core_controller;
  12429. if (typeof window !== 'undefined') {
  12430. window.Chart = core_controller;
  12431. }
  12432. // DEPRECATIONS
  12433. /**
  12434. * Provided for backward compatibility, not available anymore
  12435. * @namespace Chart.Chart
  12436. * @deprecated since version 2.8.0
  12437. * @todo remove at version 3
  12438. * @private
  12439. */
  12440. core_controller.Chart = core_controller;
  12441. /**
  12442. * Provided for backward compatibility, not available anymore
  12443. * @namespace Chart.Legend
  12444. * @deprecated since version 2.1.5
  12445. * @todo remove at version 3
  12446. * @private
  12447. */
  12448. core_controller.Legend = plugins.legend._element;
  12449. /**
  12450. * Provided for backward compatibility, not available anymore
  12451. * @namespace Chart.Title
  12452. * @deprecated since version 2.1.5
  12453. * @todo remove at version 3
  12454. * @private
  12455. */
  12456. core_controller.Title = plugins.title._element;
  12457. /**
  12458. * Provided for backward compatibility, use Chart.plugins instead
  12459. * @namespace Chart.pluginService
  12460. * @deprecated since version 2.1.5
  12461. * @todo remove at version 3
  12462. * @private
  12463. */
  12464. core_controller.pluginService = core_controller.plugins;
  12465. /**
  12466. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  12467. * effect, instead simply create/register plugins via plain JavaScript objects.
  12468. * @interface Chart.PluginBase
  12469. * @deprecated since version 2.5.0
  12470. * @todo remove at version 3
  12471. * @private
  12472. */
  12473. core_controller.PluginBase = core_controller.Element.extend({});
  12474. /**
  12475. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  12476. * @namespace Chart.canvasHelpers
  12477. * @deprecated since version 2.6.0
  12478. * @todo remove at version 3
  12479. * @private
  12480. */
  12481. core_controller.canvasHelpers = core_controller.helpers.canvas;
  12482. /**
  12483. * Provided for backward compatibility, use Chart.layouts instead.
  12484. * @namespace Chart.layoutService
  12485. * @deprecated since version 2.7.3
  12486. * @todo remove at version 3
  12487. * @private
  12488. */
  12489. core_controller.layoutService = core_controller.layouts;
  12490. /**
  12491. * Provided for backward compatibility, not available anymore.
  12492. * @namespace Chart.LinearScaleBase
  12493. * @deprecated since version 2.8
  12494. * @todo remove at version 3
  12495. * @private
  12496. */
  12497. core_controller.LinearScaleBase = scale_linearbase;
  12498. /**
  12499. * Provided for backward compatibility, instead we should create a new Chart
  12500. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  12501. * @deprecated since version 2.8.0
  12502. * @todo remove at version 3
  12503. */
  12504. core_controller.helpers.each(
  12505. [
  12506. 'Bar',
  12507. 'Bubble',
  12508. 'Doughnut',
  12509. 'Line',
  12510. 'PolarArea',
  12511. 'Radar',
  12512. 'Scatter'
  12513. ],
  12514. function(klass) {
  12515. core_controller[klass] = function(ctx, cfg) {
  12516. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  12517. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  12518. }));
  12519. };
  12520. }
  12521. );
  12522. return src;
  12523. })));