chart.js 393 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462
  1. /*!
  2. * Chart.js v4.4.2
  3. * https://www.chartjs.org
  4. * (c) 2024 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. import { r as requestAnimFrame, a as resolve, e as effects, c as color, i as isObject, d as defaults, b as isArray, v as valueOrDefault, u as unlistenArrayEvents, l as listenArrayEvents, f as resolveObjectKey, g as isNumberFinite, h as defined, s as sign, j as createContext, k as isNullOrUndef, _ as _arrayUnique, t as toRadians, m as toPercentage, n as toDimension, T as TAU, o as formatNumber, p as _angleBetween, H as HALF_PI, P as PI, q as _getStartAndCountOfVisiblePoints, w as _scaleRangesChanged, x as isNumber, y as _parseObjectDataRadialScale, z as getRelativePosition, A as _rlookupByKey, B as _lookupByKey, C as _isPointInArea, D as getAngleFromPoint, E as toPadding, F as each, G as getMaximumSize, I as _getParentNode, J as readUsedSize, K as supportsEventListenerOptions, L as throttled, M as _isDomSupported, N as _factorize, O as finiteOrDefault, Q as callback, R as _addGrace, S as _limitValue, U as toDegrees, V as _measureText, W as _int16Range, X as _alignPixel, Y as clipArea, Z as renderText, $ as unclipArea, a0 as toFont, a1 as _toLeftRightCenter, a2 as _alignStartEnd, a3 as overrides, a4 as merge, a5 as _capitalize, a6 as descriptors, a7 as isFunction, a8 as _attachContext, a9 as _createResolver, aa as _descriptors, ab as mergeIf, ac as uid, ad as debounce, ae as retinaScale, af as clearCanvas, ag as setsEqual, ah as _elementsEqual, ai as _isClickEvent, aj as _isBetween, ak as _readValueToProps, al as _updateBezierControlPoints, am as _computeSegments, an as _boundSegments, ao as _steppedInterpolation, ap as _bezierInterpolation, aq as _pointInLine, ar as _steppedLineTo, as as _bezierCurveTo, at as drawPoint, au as addRoundedRectPath, av as toTRBL, aw as toTRBLCorners, ax as _boundSegment, ay as _normalizeAngle, az as getRtlAdapter, aA as overrideTextDirection, aB as _textX, aC as restoreTextDirection, aD as drawPointLegend, aE as distanceBetweenPoints, aF as noop, aG as _setMinAndMaxByKey, aH as niceNum, aI as almostWhole, aJ as almostEquals, aK as _decimalPlaces, aL as Ticks, aM as log10, aN as _longestText, aO as _filterBetween, aP as _lookup } from './chunks/helpers.segment.js';
  8. import '@kurkle/color';
  9. class Animator {
  10. constructor(){
  11. this._request = null;
  12. this._charts = new Map();
  13. this._running = false;
  14. this._lastDate = undefined;
  15. }
  16. _notify(chart, anims, date, type) {
  17. const callbacks = anims.listeners[type];
  18. const numSteps = anims.duration;
  19. callbacks.forEach((fn)=>fn({
  20. chart,
  21. initial: anims.initial,
  22. numSteps,
  23. currentStep: Math.min(date - anims.start, numSteps)
  24. }));
  25. }
  26. _refresh() {
  27. if (this._request) {
  28. return;
  29. }
  30. this._running = true;
  31. this._request = requestAnimFrame.call(window, ()=>{
  32. this._update();
  33. this._request = null;
  34. if (this._running) {
  35. this._refresh();
  36. }
  37. });
  38. }
  39. _update(date = Date.now()) {
  40. let remaining = 0;
  41. this._charts.forEach((anims, chart)=>{
  42. if (!anims.running || !anims.items.length) {
  43. return;
  44. }
  45. const items = anims.items;
  46. let i = items.length - 1;
  47. let draw = false;
  48. let item;
  49. for(; i >= 0; --i){
  50. item = items[i];
  51. if (item._active) {
  52. if (item._total > anims.duration) {
  53. anims.duration = item._total;
  54. }
  55. item.tick(date);
  56. draw = true;
  57. } else {
  58. items[i] = items[items.length - 1];
  59. items.pop();
  60. }
  61. }
  62. if (draw) {
  63. chart.draw();
  64. this._notify(chart, anims, date, 'progress');
  65. }
  66. if (!items.length) {
  67. anims.running = false;
  68. this._notify(chart, anims, date, 'complete');
  69. anims.initial = false;
  70. }
  71. remaining += items.length;
  72. });
  73. this._lastDate = date;
  74. if (remaining === 0) {
  75. this._running = false;
  76. }
  77. }
  78. _getAnims(chart) {
  79. const charts = this._charts;
  80. let anims = charts.get(chart);
  81. if (!anims) {
  82. anims = {
  83. running: false,
  84. initial: true,
  85. items: [],
  86. listeners: {
  87. complete: [],
  88. progress: []
  89. }
  90. };
  91. charts.set(chart, anims);
  92. }
  93. return anims;
  94. }
  95. listen(chart, event, cb) {
  96. this._getAnims(chart).listeners[event].push(cb);
  97. }
  98. add(chart, items) {
  99. if (!items || !items.length) {
  100. return;
  101. }
  102. this._getAnims(chart).items.push(...items);
  103. }
  104. has(chart) {
  105. return this._getAnims(chart).items.length > 0;
  106. }
  107. start(chart) {
  108. const anims = this._charts.get(chart);
  109. if (!anims) {
  110. return;
  111. }
  112. anims.running = true;
  113. anims.start = Date.now();
  114. anims.duration = anims.items.reduce((acc, cur)=>Math.max(acc, cur._duration), 0);
  115. this._refresh();
  116. }
  117. running(chart) {
  118. if (!this._running) {
  119. return false;
  120. }
  121. const anims = this._charts.get(chart);
  122. if (!anims || !anims.running || !anims.items.length) {
  123. return false;
  124. }
  125. return true;
  126. }
  127. stop(chart) {
  128. const anims = this._charts.get(chart);
  129. if (!anims || !anims.items.length) {
  130. return;
  131. }
  132. const items = anims.items;
  133. let i = items.length - 1;
  134. for(; i >= 0; --i){
  135. items[i].cancel();
  136. }
  137. anims.items = [];
  138. this._notify(chart, anims, Date.now(), 'complete');
  139. }
  140. remove(chart) {
  141. return this._charts.delete(chart);
  142. }
  143. }
  144. var animator = /* #__PURE__ */ new Animator();
  145. const transparent = 'transparent';
  146. const interpolators = {
  147. boolean (from, to, factor) {
  148. return factor > 0.5 ? to : from;
  149. },
  150. color (from, to, factor) {
  151. const c0 = color(from || transparent);
  152. const c1 = c0.valid && color(to || transparent);
  153. return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to;
  154. },
  155. number (from, to, factor) {
  156. return from + (to - from) * factor;
  157. }
  158. };
  159. class Animation {
  160. constructor(cfg, target, prop, to){
  161. const currentValue = target[prop];
  162. to = resolve([
  163. cfg.to,
  164. to,
  165. currentValue,
  166. cfg.from
  167. ]);
  168. const from = resolve([
  169. cfg.from,
  170. currentValue,
  171. to
  172. ]);
  173. this._active = true;
  174. this._fn = cfg.fn || interpolators[cfg.type || typeof from];
  175. this._easing = effects[cfg.easing] || effects.linear;
  176. this._start = Math.floor(Date.now() + (cfg.delay || 0));
  177. this._duration = this._total = Math.floor(cfg.duration);
  178. this._loop = !!cfg.loop;
  179. this._target = target;
  180. this._prop = prop;
  181. this._from = from;
  182. this._to = to;
  183. this._promises = undefined;
  184. }
  185. active() {
  186. return this._active;
  187. }
  188. update(cfg, to, date) {
  189. if (this._active) {
  190. this._notify(false);
  191. const currentValue = this._target[this._prop];
  192. const elapsed = date - this._start;
  193. const remain = this._duration - elapsed;
  194. this._start = date;
  195. this._duration = Math.floor(Math.max(remain, cfg.duration));
  196. this._total += elapsed;
  197. this._loop = !!cfg.loop;
  198. this._to = resolve([
  199. cfg.to,
  200. to,
  201. currentValue,
  202. cfg.from
  203. ]);
  204. this._from = resolve([
  205. cfg.from,
  206. currentValue,
  207. to
  208. ]);
  209. }
  210. }
  211. cancel() {
  212. if (this._active) {
  213. this.tick(Date.now());
  214. this._active = false;
  215. this._notify(false);
  216. }
  217. }
  218. tick(date) {
  219. const elapsed = date - this._start;
  220. const duration = this._duration;
  221. const prop = this._prop;
  222. const from = this._from;
  223. const loop = this._loop;
  224. const to = this._to;
  225. let factor;
  226. this._active = from !== to && (loop || elapsed < duration);
  227. if (!this._active) {
  228. this._target[prop] = to;
  229. this._notify(true);
  230. return;
  231. }
  232. if (elapsed < 0) {
  233. this._target[prop] = from;
  234. return;
  235. }
  236. factor = elapsed / duration % 2;
  237. factor = loop && factor > 1 ? 2 - factor : factor;
  238. factor = this._easing(Math.min(1, Math.max(0, factor)));
  239. this._target[prop] = this._fn(from, to, factor);
  240. }
  241. wait() {
  242. const promises = this._promises || (this._promises = []);
  243. return new Promise((res, rej)=>{
  244. promises.push({
  245. res,
  246. rej
  247. });
  248. });
  249. }
  250. _notify(resolved) {
  251. const method = resolved ? 'res' : 'rej';
  252. const promises = this._promises || [];
  253. for(let i = 0; i < promises.length; i++){
  254. promises[i][method]();
  255. }
  256. }
  257. }
  258. class Animations {
  259. constructor(chart, config){
  260. this._chart = chart;
  261. this._properties = new Map();
  262. this.configure(config);
  263. }
  264. configure(config) {
  265. if (!isObject(config)) {
  266. return;
  267. }
  268. const animationOptions = Object.keys(defaults.animation);
  269. const animatedProps = this._properties;
  270. Object.getOwnPropertyNames(config).forEach((key)=>{
  271. const cfg = config[key];
  272. if (!isObject(cfg)) {
  273. return;
  274. }
  275. const resolved = {};
  276. for (const option of animationOptions){
  277. resolved[option] = cfg[option];
  278. }
  279. (isArray(cfg.properties) && cfg.properties || [
  280. key
  281. ]).forEach((prop)=>{
  282. if (prop === key || !animatedProps.has(prop)) {
  283. animatedProps.set(prop, resolved);
  284. }
  285. });
  286. });
  287. }
  288. _animateOptions(target, values) {
  289. const newOptions = values.options;
  290. const options = resolveTargetOptions(target, newOptions);
  291. if (!options) {
  292. return [];
  293. }
  294. const animations = this._createAnimations(options, newOptions);
  295. if (newOptions.$shared) {
  296. awaitAll(target.options.$animations, newOptions).then(()=>{
  297. target.options = newOptions;
  298. }, ()=>{
  299. });
  300. }
  301. return animations;
  302. }
  303. _createAnimations(target, values) {
  304. const animatedProps = this._properties;
  305. const animations = [];
  306. const running = target.$animations || (target.$animations = {});
  307. const props = Object.keys(values);
  308. const date = Date.now();
  309. let i;
  310. for(i = props.length - 1; i >= 0; --i){
  311. const prop = props[i];
  312. if (prop.charAt(0) === '$') {
  313. continue;
  314. }
  315. if (prop === 'options') {
  316. animations.push(...this._animateOptions(target, values));
  317. continue;
  318. }
  319. const value = values[prop];
  320. let animation = running[prop];
  321. const cfg = animatedProps.get(prop);
  322. if (animation) {
  323. if (cfg && animation.active()) {
  324. animation.update(cfg, value, date);
  325. continue;
  326. } else {
  327. animation.cancel();
  328. }
  329. }
  330. if (!cfg || !cfg.duration) {
  331. target[prop] = value;
  332. continue;
  333. }
  334. running[prop] = animation = new Animation(cfg, target, prop, value);
  335. animations.push(animation);
  336. }
  337. return animations;
  338. }
  339. update(target, values) {
  340. if (this._properties.size === 0) {
  341. Object.assign(target, values);
  342. return;
  343. }
  344. const animations = this._createAnimations(target, values);
  345. if (animations.length) {
  346. animator.add(this._chart, animations);
  347. return true;
  348. }
  349. }
  350. }
  351. function awaitAll(animations, properties) {
  352. const running = [];
  353. const keys = Object.keys(properties);
  354. for(let i = 0; i < keys.length; i++){
  355. const anim = animations[keys[i]];
  356. if (anim && anim.active()) {
  357. running.push(anim.wait());
  358. }
  359. }
  360. return Promise.all(running);
  361. }
  362. function resolveTargetOptions(target, newOptions) {
  363. if (!newOptions) {
  364. return;
  365. }
  366. let options = target.options;
  367. if (!options) {
  368. target.options = newOptions;
  369. return;
  370. }
  371. if (options.$shared) {
  372. target.options = options = Object.assign({}, options, {
  373. $shared: false,
  374. $animations: {}
  375. });
  376. }
  377. return options;
  378. }
  379. function scaleClip(scale, allowedOverflow) {
  380. const opts = scale && scale.options || {};
  381. const reverse = opts.reverse;
  382. const min = opts.min === undefined ? allowedOverflow : 0;
  383. const max = opts.max === undefined ? allowedOverflow : 0;
  384. return {
  385. start: reverse ? max : min,
  386. end: reverse ? min : max
  387. };
  388. }
  389. function defaultClip(xScale, yScale, allowedOverflow) {
  390. if (allowedOverflow === false) {
  391. return false;
  392. }
  393. const x = scaleClip(xScale, allowedOverflow);
  394. const y = scaleClip(yScale, allowedOverflow);
  395. return {
  396. top: y.end,
  397. right: x.end,
  398. bottom: y.start,
  399. left: x.start
  400. };
  401. }
  402. function toClip(value) {
  403. let t, r, b, l;
  404. if (isObject(value)) {
  405. t = value.top;
  406. r = value.right;
  407. b = value.bottom;
  408. l = value.left;
  409. } else {
  410. t = r = b = l = value;
  411. }
  412. return {
  413. top: t,
  414. right: r,
  415. bottom: b,
  416. left: l,
  417. disabled: value === false
  418. };
  419. }
  420. function getSortedDatasetIndices(chart, filterVisible) {
  421. const keys = [];
  422. const metasets = chart._getSortedDatasetMetas(filterVisible);
  423. let i, ilen;
  424. for(i = 0, ilen = metasets.length; i < ilen; ++i){
  425. keys.push(metasets[i].index);
  426. }
  427. return keys;
  428. }
  429. function applyStack(stack, value, dsIndex, options = {}) {
  430. const keys = stack.keys;
  431. const singleMode = options.mode === 'single';
  432. let i, ilen, datasetIndex, otherValue;
  433. if (value === null) {
  434. return;
  435. }
  436. for(i = 0, ilen = keys.length; i < ilen; ++i){
  437. datasetIndex = +keys[i];
  438. if (datasetIndex === dsIndex) {
  439. if (options.all) {
  440. continue;
  441. }
  442. break;
  443. }
  444. otherValue = stack.values[datasetIndex];
  445. if (isNumberFinite(otherValue) && (singleMode || value === 0 || sign(value) === sign(otherValue))) {
  446. value += otherValue;
  447. }
  448. }
  449. return value;
  450. }
  451. function convertObjectDataToArray(data) {
  452. const keys = Object.keys(data);
  453. const adata = new Array(keys.length);
  454. let i, ilen, key;
  455. for(i = 0, ilen = keys.length; i < ilen; ++i){
  456. key = keys[i];
  457. adata[i] = {
  458. x: key,
  459. y: data[key]
  460. };
  461. }
  462. return adata;
  463. }
  464. function isStacked(scale, meta) {
  465. const stacked = scale && scale.options.stacked;
  466. return stacked || stacked === undefined && meta.stack !== undefined;
  467. }
  468. function getStackKey(indexScale, valueScale, meta) {
  469. return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
  470. }
  471. function getUserBounds(scale) {
  472. const { min , max , minDefined , maxDefined } = scale.getUserBounds();
  473. return {
  474. min: minDefined ? min : Number.NEGATIVE_INFINITY,
  475. max: maxDefined ? max : Number.POSITIVE_INFINITY
  476. };
  477. }
  478. function getOrCreateStack(stacks, stackKey, indexValue) {
  479. const subStack = stacks[stackKey] || (stacks[stackKey] = {});
  480. return subStack[indexValue] || (subStack[indexValue] = {});
  481. }
  482. function getLastIndexInStack(stack, vScale, positive, type) {
  483. for (const meta of vScale.getMatchingVisibleMetas(type).reverse()){
  484. const value = stack[meta.index];
  485. if (positive && value > 0 || !positive && value < 0) {
  486. return meta.index;
  487. }
  488. }
  489. return null;
  490. }
  491. function updateStacks(controller, parsed) {
  492. const { chart , _cachedMeta: meta } = controller;
  493. const stacks = chart._stacks || (chart._stacks = {});
  494. const { iScale , vScale , index: datasetIndex } = meta;
  495. const iAxis = iScale.axis;
  496. const vAxis = vScale.axis;
  497. const key = getStackKey(iScale, vScale, meta);
  498. const ilen = parsed.length;
  499. let stack;
  500. for(let i = 0; i < ilen; ++i){
  501. const item = parsed[i];
  502. const { [iAxis]: index , [vAxis]: value } = item;
  503. const itemStacks = item._stacks || (item._stacks = {});
  504. stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
  505. stack[datasetIndex] = value;
  506. stack._top = getLastIndexInStack(stack, vScale, true, meta.type);
  507. stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);
  508. const visualValues = stack._visualValues || (stack._visualValues = {});
  509. visualValues[datasetIndex] = value;
  510. }
  511. }
  512. function getFirstScaleId(chart, axis) {
  513. const scales = chart.scales;
  514. return Object.keys(scales).filter((key)=>scales[key].axis === axis).shift();
  515. }
  516. function createDatasetContext(parent, index) {
  517. return createContext(parent, {
  518. active: false,
  519. dataset: undefined,
  520. datasetIndex: index,
  521. index,
  522. mode: 'default',
  523. type: 'dataset'
  524. });
  525. }
  526. function createDataContext(parent, index, element) {
  527. return createContext(parent, {
  528. active: false,
  529. dataIndex: index,
  530. parsed: undefined,
  531. raw: undefined,
  532. element,
  533. index,
  534. mode: 'default',
  535. type: 'data'
  536. });
  537. }
  538. function clearStacks(meta, items) {
  539. const datasetIndex = meta.controller.index;
  540. const axis = meta.vScale && meta.vScale.axis;
  541. if (!axis) {
  542. return;
  543. }
  544. items = items || meta._parsed;
  545. for (const parsed of items){
  546. const stacks = parsed._stacks;
  547. if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {
  548. return;
  549. }
  550. delete stacks[axis][datasetIndex];
  551. if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {
  552. delete stacks[axis]._visualValues[datasetIndex];
  553. }
  554. }
  555. }
  556. const isDirectUpdateMode = (mode)=>mode === 'reset' || mode === 'none';
  557. const cloneIfNotShared = (cached, shared)=>shared ? cached : Object.assign({}, cached);
  558. const createStack = (canStack, meta, chart)=>canStack && !meta.hidden && meta._stacked && {
  559. keys: getSortedDatasetIndices(chart, true),
  560. values: null
  561. };
  562. class DatasetController {
  563. static defaults = {};
  564. static datasetElementType = null;
  565. static dataElementType = null;
  566. constructor(chart, datasetIndex){
  567. this.chart = chart;
  568. this._ctx = chart.ctx;
  569. this.index = datasetIndex;
  570. this._cachedDataOpts = {};
  571. this._cachedMeta = this.getMeta();
  572. this._type = this._cachedMeta.type;
  573. this.options = undefined;
  574. this._parsing = false;
  575. this._data = undefined;
  576. this._objectData = undefined;
  577. this._sharedOptions = undefined;
  578. this._drawStart = undefined;
  579. this._drawCount = undefined;
  580. this.enableOptionSharing = false;
  581. this.supportsDecimation = false;
  582. this.$context = undefined;
  583. this._syncList = [];
  584. this.datasetElementType = new.target.datasetElementType;
  585. this.dataElementType = new.target.dataElementType;
  586. this.initialize();
  587. }
  588. initialize() {
  589. const meta = this._cachedMeta;
  590. this.configure();
  591. this.linkScales();
  592. meta._stacked = isStacked(meta.vScale, meta);
  593. this.addElements();
  594. if (this.options.fill && !this.chart.isPluginEnabled('filler')) {
  595. console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options");
  596. }
  597. }
  598. updateIndex(datasetIndex) {
  599. if (this.index !== datasetIndex) {
  600. clearStacks(this._cachedMeta);
  601. }
  602. this.index = datasetIndex;
  603. }
  604. linkScales() {
  605. const chart = this.chart;
  606. const meta = this._cachedMeta;
  607. const dataset = this.getDataset();
  608. const chooseId = (axis, x, y, r)=>axis === 'x' ? x : axis === 'r' ? r : y;
  609. const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
  610. const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
  611. const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
  612. const indexAxis = meta.indexAxis;
  613. const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
  614. const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
  615. meta.xScale = this.getScaleForId(xid);
  616. meta.yScale = this.getScaleForId(yid);
  617. meta.rScale = this.getScaleForId(rid);
  618. meta.iScale = this.getScaleForId(iid);
  619. meta.vScale = this.getScaleForId(vid);
  620. }
  621. getDataset() {
  622. return this.chart.data.datasets[this.index];
  623. }
  624. getMeta() {
  625. return this.chart.getDatasetMeta(this.index);
  626. }
  627. getScaleForId(scaleID) {
  628. return this.chart.scales[scaleID];
  629. }
  630. _getOtherScale(scale) {
  631. const meta = this._cachedMeta;
  632. return scale === meta.iScale ? meta.vScale : meta.iScale;
  633. }
  634. reset() {
  635. this._update('reset');
  636. }
  637. _destroy() {
  638. const meta = this._cachedMeta;
  639. if (this._data) {
  640. unlistenArrayEvents(this._data, this);
  641. }
  642. if (meta._stacked) {
  643. clearStacks(meta);
  644. }
  645. }
  646. _dataCheck() {
  647. const dataset = this.getDataset();
  648. const data = dataset.data || (dataset.data = []);
  649. const _data = this._data;
  650. if (isObject(data)) {
  651. this._data = convertObjectDataToArray(data);
  652. } else if (_data !== data) {
  653. if (_data) {
  654. unlistenArrayEvents(_data, this);
  655. const meta = this._cachedMeta;
  656. clearStacks(meta);
  657. meta._parsed = [];
  658. }
  659. if (data && Object.isExtensible(data)) {
  660. listenArrayEvents(data, this);
  661. }
  662. this._syncList = [];
  663. this._data = data;
  664. }
  665. }
  666. addElements() {
  667. const meta = this._cachedMeta;
  668. this._dataCheck();
  669. if (this.datasetElementType) {
  670. meta.dataset = new this.datasetElementType();
  671. }
  672. }
  673. buildOrUpdateElements(resetNewElements) {
  674. const meta = this._cachedMeta;
  675. const dataset = this.getDataset();
  676. let stackChanged = false;
  677. this._dataCheck();
  678. const oldStacked = meta._stacked;
  679. meta._stacked = isStacked(meta.vScale, meta);
  680. if (meta.stack !== dataset.stack) {
  681. stackChanged = true;
  682. clearStacks(meta);
  683. meta.stack = dataset.stack;
  684. }
  685. this._resyncElements(resetNewElements);
  686. if (stackChanged || oldStacked !== meta._stacked) {
  687. updateStacks(this, meta._parsed);
  688. }
  689. }
  690. configure() {
  691. const config = this.chart.config;
  692. const scopeKeys = config.datasetScopeKeys(this._type);
  693. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);
  694. this.options = config.createResolver(scopes, this.getContext());
  695. this._parsing = this.options.parsing;
  696. this._cachedDataOpts = {};
  697. }
  698. parse(start, count) {
  699. const { _cachedMeta: meta , _data: data } = this;
  700. const { iScale , _stacked } = meta;
  701. const iAxis = iScale.axis;
  702. let sorted = start === 0 && count === data.length ? true : meta._sorted;
  703. let prev = start > 0 && meta._parsed[start - 1];
  704. let i, cur, parsed;
  705. if (this._parsing === false) {
  706. meta._parsed = data;
  707. meta._sorted = true;
  708. parsed = data;
  709. } else {
  710. if (isArray(data[start])) {
  711. parsed = this.parseArrayData(meta, data, start, count);
  712. } else if (isObject(data[start])) {
  713. parsed = this.parseObjectData(meta, data, start, count);
  714. } else {
  715. parsed = this.parsePrimitiveData(meta, data, start, count);
  716. }
  717. const isNotInOrderComparedToPrev = ()=>cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis];
  718. for(i = 0; i < count; ++i){
  719. meta._parsed[i + start] = cur = parsed[i];
  720. if (sorted) {
  721. if (isNotInOrderComparedToPrev()) {
  722. sorted = false;
  723. }
  724. prev = cur;
  725. }
  726. }
  727. meta._sorted = sorted;
  728. }
  729. if (_stacked) {
  730. updateStacks(this, parsed);
  731. }
  732. }
  733. parsePrimitiveData(meta, data, start, count) {
  734. const { iScale , vScale } = meta;
  735. const iAxis = iScale.axis;
  736. const vAxis = vScale.axis;
  737. const labels = iScale.getLabels();
  738. const singleScale = iScale === vScale;
  739. const parsed = new Array(count);
  740. let i, ilen, index;
  741. for(i = 0, ilen = count; i < ilen; ++i){
  742. index = i + start;
  743. parsed[i] = {
  744. [iAxis]: singleScale || iScale.parse(labels[index], index),
  745. [vAxis]: vScale.parse(data[index], index)
  746. };
  747. }
  748. return parsed;
  749. }
  750. parseArrayData(meta, data, start, count) {
  751. const { xScale , yScale } = meta;
  752. const parsed = new Array(count);
  753. let i, ilen, index, item;
  754. for(i = 0, ilen = count; i < ilen; ++i){
  755. index = i + start;
  756. item = data[index];
  757. parsed[i] = {
  758. x: xScale.parse(item[0], index),
  759. y: yScale.parse(item[1], index)
  760. };
  761. }
  762. return parsed;
  763. }
  764. parseObjectData(meta, data, start, count) {
  765. const { xScale , yScale } = meta;
  766. const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing;
  767. const parsed = new Array(count);
  768. let i, ilen, index, item;
  769. for(i = 0, ilen = count; i < ilen; ++i){
  770. index = i + start;
  771. item = data[index];
  772. parsed[i] = {
  773. x: xScale.parse(resolveObjectKey(item, xAxisKey), index),
  774. y: yScale.parse(resolveObjectKey(item, yAxisKey), index)
  775. };
  776. }
  777. return parsed;
  778. }
  779. getParsed(index) {
  780. return this._cachedMeta._parsed[index];
  781. }
  782. getDataElement(index) {
  783. return this._cachedMeta.data[index];
  784. }
  785. applyStack(scale, parsed, mode) {
  786. const chart = this.chart;
  787. const meta = this._cachedMeta;
  788. const value = parsed[scale.axis];
  789. const stack = {
  790. keys: getSortedDatasetIndices(chart, true),
  791. values: parsed._stacks[scale.axis]._visualValues
  792. };
  793. return applyStack(stack, value, meta.index, {
  794. mode
  795. });
  796. }
  797. updateRangeFromParsed(range, scale, parsed, stack) {
  798. const parsedValue = parsed[scale.axis];
  799. let value = parsedValue === null ? NaN : parsedValue;
  800. const values = stack && parsed._stacks[scale.axis];
  801. if (stack && values) {
  802. stack.values = values;
  803. value = applyStack(stack, parsedValue, this._cachedMeta.index);
  804. }
  805. range.min = Math.min(range.min, value);
  806. range.max = Math.max(range.max, value);
  807. }
  808. getMinMax(scale, canStack) {
  809. const meta = this._cachedMeta;
  810. const _parsed = meta._parsed;
  811. const sorted = meta._sorted && scale === meta.iScale;
  812. const ilen = _parsed.length;
  813. const otherScale = this._getOtherScale(scale);
  814. const stack = createStack(canStack, meta, this.chart);
  815. const range = {
  816. min: Number.POSITIVE_INFINITY,
  817. max: Number.NEGATIVE_INFINITY
  818. };
  819. const { min: otherMin , max: otherMax } = getUserBounds(otherScale);
  820. let i, parsed;
  821. function _skip() {
  822. parsed = _parsed[i];
  823. const otherValue = parsed[otherScale.axis];
  824. return !isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;
  825. }
  826. for(i = 0; i < ilen; ++i){
  827. if (_skip()) {
  828. continue;
  829. }
  830. this.updateRangeFromParsed(range, scale, parsed, stack);
  831. if (sorted) {
  832. break;
  833. }
  834. }
  835. if (sorted) {
  836. for(i = ilen - 1; i >= 0; --i){
  837. if (_skip()) {
  838. continue;
  839. }
  840. this.updateRangeFromParsed(range, scale, parsed, stack);
  841. break;
  842. }
  843. }
  844. return range;
  845. }
  846. getAllParsedValues(scale) {
  847. const parsed = this._cachedMeta._parsed;
  848. const values = [];
  849. let i, ilen, value;
  850. for(i = 0, ilen = parsed.length; i < ilen; ++i){
  851. value = parsed[i][scale.axis];
  852. if (isNumberFinite(value)) {
  853. values.push(value);
  854. }
  855. }
  856. return values;
  857. }
  858. getMaxOverflow() {
  859. return false;
  860. }
  861. getLabelAndValue(index) {
  862. const meta = this._cachedMeta;
  863. const iScale = meta.iScale;
  864. const vScale = meta.vScale;
  865. const parsed = this.getParsed(index);
  866. return {
  867. label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
  868. value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
  869. };
  870. }
  871. _update(mode) {
  872. const meta = this._cachedMeta;
  873. this.update(mode || 'default');
  874. meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));
  875. }
  876. update(mode) {}
  877. draw() {
  878. const ctx = this._ctx;
  879. const chart = this.chart;
  880. const meta = this._cachedMeta;
  881. const elements = meta.data || [];
  882. const area = chart.chartArea;
  883. const active = [];
  884. const start = this._drawStart || 0;
  885. const count = this._drawCount || elements.length - start;
  886. const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;
  887. let i;
  888. if (meta.dataset) {
  889. meta.dataset.draw(ctx, area, start, count);
  890. }
  891. for(i = start; i < start + count; ++i){
  892. const element = elements[i];
  893. if (element.hidden) {
  894. continue;
  895. }
  896. if (element.active && drawActiveElementsOnTop) {
  897. active.push(element);
  898. } else {
  899. element.draw(ctx, area);
  900. }
  901. }
  902. for(i = 0; i < active.length; ++i){
  903. active[i].draw(ctx, area);
  904. }
  905. }
  906. getStyle(index, active) {
  907. const mode = active ? 'active' : 'default';
  908. return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode);
  909. }
  910. getContext(index, active, mode) {
  911. const dataset = this.getDataset();
  912. let context;
  913. if (index >= 0 && index < this._cachedMeta.data.length) {
  914. const element = this._cachedMeta.data[index];
  915. context = element.$context || (element.$context = createDataContext(this.getContext(), index, element));
  916. context.parsed = this.getParsed(index);
  917. context.raw = dataset.data[index];
  918. context.index = context.dataIndex = index;
  919. } else {
  920. context = this.$context || (this.$context = createDatasetContext(this.chart.getContext(), this.index));
  921. context.dataset = dataset;
  922. context.index = context.datasetIndex = this.index;
  923. }
  924. context.active = !!active;
  925. context.mode = mode;
  926. return context;
  927. }
  928. resolveDatasetElementOptions(mode) {
  929. return this._resolveElementOptions(this.datasetElementType.id, mode);
  930. }
  931. resolveDataElementOptions(index, mode) {
  932. return this._resolveElementOptions(this.dataElementType.id, mode, index);
  933. }
  934. _resolveElementOptions(elementType, mode = 'default', index) {
  935. const active = mode === 'active';
  936. const cache = this._cachedDataOpts;
  937. const cacheKey = elementType + '-' + mode;
  938. const cached = cache[cacheKey];
  939. const sharing = this.enableOptionSharing && defined(index);
  940. if (cached) {
  941. return cloneIfNotShared(cached, sharing);
  942. }
  943. const config = this.chart.config;
  944. const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);
  945. const prefixes = active ? [
  946. `${elementType}Hover`,
  947. 'hover',
  948. elementType,
  949. ''
  950. ] : [
  951. elementType,
  952. ''
  953. ];
  954. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  955. const names = Object.keys(defaults.elements[elementType]);
  956. const context = ()=>this.getContext(index, active, mode);
  957. const values = config.resolveNamedOptions(scopes, names, context, prefixes);
  958. if (values.$shared) {
  959. values.$shared = sharing;
  960. cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
  961. }
  962. return values;
  963. }
  964. _resolveAnimations(index, transition, active) {
  965. const chart = this.chart;
  966. const cache = this._cachedDataOpts;
  967. const cacheKey = `animation-${transition}`;
  968. const cached = cache[cacheKey];
  969. if (cached) {
  970. return cached;
  971. }
  972. let options;
  973. if (chart.options.animation !== false) {
  974. const config = this.chart.config;
  975. const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);
  976. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  977. options = config.createResolver(scopes, this.getContext(index, active, transition));
  978. }
  979. const animations = new Animations(chart, options && options.animations);
  980. if (options && options._cacheable) {
  981. cache[cacheKey] = Object.freeze(animations);
  982. }
  983. return animations;
  984. }
  985. getSharedOptions(options) {
  986. if (!options.$shared) {
  987. return;
  988. }
  989. return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
  990. }
  991. includeOptions(mode, sharedOptions) {
  992. return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
  993. }
  994. _getSharedOptions(start, mode) {
  995. const firstOpts = this.resolveDataElementOptions(start, mode);
  996. const previouslySharedOptions = this._sharedOptions;
  997. const sharedOptions = this.getSharedOptions(firstOpts);
  998. const includeOptions = this.includeOptions(mode, sharedOptions) || sharedOptions !== previouslySharedOptions;
  999. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  1000. return {
  1001. sharedOptions,
  1002. includeOptions
  1003. };
  1004. }
  1005. updateElement(element, index, properties, mode) {
  1006. if (isDirectUpdateMode(mode)) {
  1007. Object.assign(element, properties);
  1008. } else {
  1009. this._resolveAnimations(index, mode).update(element, properties);
  1010. }
  1011. }
  1012. updateSharedOptions(sharedOptions, mode, newOptions) {
  1013. if (sharedOptions && !isDirectUpdateMode(mode)) {
  1014. this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
  1015. }
  1016. }
  1017. _setStyle(element, index, mode, active) {
  1018. element.active = active;
  1019. const options = this.getStyle(index, active);
  1020. this._resolveAnimations(index, mode, active).update(element, {
  1021. options: !active && this.getSharedOptions(options) || options
  1022. });
  1023. }
  1024. removeHoverStyle(element, datasetIndex, index) {
  1025. this._setStyle(element, index, 'active', false);
  1026. }
  1027. setHoverStyle(element, datasetIndex, index) {
  1028. this._setStyle(element, index, 'active', true);
  1029. }
  1030. _removeDatasetHoverStyle() {
  1031. const element = this._cachedMeta.dataset;
  1032. if (element) {
  1033. this._setStyle(element, undefined, 'active', false);
  1034. }
  1035. }
  1036. _setDatasetHoverStyle() {
  1037. const element = this._cachedMeta.dataset;
  1038. if (element) {
  1039. this._setStyle(element, undefined, 'active', true);
  1040. }
  1041. }
  1042. _resyncElements(resetNewElements) {
  1043. const data = this._data;
  1044. const elements = this._cachedMeta.data;
  1045. for (const [method, arg1, arg2] of this._syncList){
  1046. this[method](arg1, arg2);
  1047. }
  1048. this._syncList = [];
  1049. const numMeta = elements.length;
  1050. const numData = data.length;
  1051. const count = Math.min(numData, numMeta);
  1052. if (count) {
  1053. this.parse(0, count);
  1054. }
  1055. if (numData > numMeta) {
  1056. this._insertElements(numMeta, numData - numMeta, resetNewElements);
  1057. } else if (numData < numMeta) {
  1058. this._removeElements(numData, numMeta - numData);
  1059. }
  1060. }
  1061. _insertElements(start, count, resetNewElements = true) {
  1062. const meta = this._cachedMeta;
  1063. const data = meta.data;
  1064. const end = start + count;
  1065. let i;
  1066. const move = (arr)=>{
  1067. arr.length += count;
  1068. for(i = arr.length - 1; i >= end; i--){
  1069. arr[i] = arr[i - count];
  1070. }
  1071. };
  1072. move(data);
  1073. for(i = start; i < end; ++i){
  1074. data[i] = new this.dataElementType();
  1075. }
  1076. if (this._parsing) {
  1077. move(meta._parsed);
  1078. }
  1079. this.parse(start, count);
  1080. if (resetNewElements) {
  1081. this.updateElements(data, start, count, 'reset');
  1082. }
  1083. }
  1084. updateElements(element, start, count, mode) {}
  1085. _removeElements(start, count) {
  1086. const meta = this._cachedMeta;
  1087. if (this._parsing) {
  1088. const removed = meta._parsed.splice(start, count);
  1089. if (meta._stacked) {
  1090. clearStacks(meta, removed);
  1091. }
  1092. }
  1093. meta.data.splice(start, count);
  1094. }
  1095. _sync(args) {
  1096. if (this._parsing) {
  1097. this._syncList.push(args);
  1098. } else {
  1099. const [method, arg1, arg2] = args;
  1100. this[method](arg1, arg2);
  1101. }
  1102. this.chart._dataChanges.push([
  1103. this.index,
  1104. ...args
  1105. ]);
  1106. }
  1107. _onDataPush() {
  1108. const count = arguments.length;
  1109. this._sync([
  1110. '_insertElements',
  1111. this.getDataset().data.length - count,
  1112. count
  1113. ]);
  1114. }
  1115. _onDataPop() {
  1116. this._sync([
  1117. '_removeElements',
  1118. this._cachedMeta.data.length - 1,
  1119. 1
  1120. ]);
  1121. }
  1122. _onDataShift() {
  1123. this._sync([
  1124. '_removeElements',
  1125. 0,
  1126. 1
  1127. ]);
  1128. }
  1129. _onDataSplice(start, count) {
  1130. if (count) {
  1131. this._sync([
  1132. '_removeElements',
  1133. start,
  1134. count
  1135. ]);
  1136. }
  1137. const newCount = arguments.length - 2;
  1138. if (newCount) {
  1139. this._sync([
  1140. '_insertElements',
  1141. start,
  1142. newCount
  1143. ]);
  1144. }
  1145. }
  1146. _onDataUnshift() {
  1147. this._sync([
  1148. '_insertElements',
  1149. 0,
  1150. arguments.length
  1151. ]);
  1152. }
  1153. }
  1154. function getAllScaleValues(scale, type) {
  1155. if (!scale._cache.$bar) {
  1156. const visibleMetas = scale.getMatchingVisibleMetas(type);
  1157. let values = [];
  1158. for(let i = 0, ilen = visibleMetas.length; i < ilen; i++){
  1159. values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));
  1160. }
  1161. scale._cache.$bar = _arrayUnique(values.sort((a, b)=>a - b));
  1162. }
  1163. return scale._cache.$bar;
  1164. }
  1165. function computeMinSampleSize(meta) {
  1166. const scale = meta.iScale;
  1167. const values = getAllScaleValues(scale, meta.type);
  1168. let min = scale._length;
  1169. let i, ilen, curr, prev;
  1170. const updateMinAndPrev = ()=>{
  1171. if (curr === 32767 || curr === -32768) {
  1172. return;
  1173. }
  1174. if (defined(prev)) {
  1175. min = Math.min(min, Math.abs(curr - prev) || min);
  1176. }
  1177. prev = curr;
  1178. };
  1179. for(i = 0, ilen = values.length; i < ilen; ++i){
  1180. curr = scale.getPixelForValue(values[i]);
  1181. updateMinAndPrev();
  1182. }
  1183. prev = undefined;
  1184. for(i = 0, ilen = scale.ticks.length; i < ilen; ++i){
  1185. curr = scale.getPixelForTick(i);
  1186. updateMinAndPrev();
  1187. }
  1188. return min;
  1189. }
  1190. function computeFitCategoryTraits(index, ruler, options, stackCount) {
  1191. const thickness = options.barThickness;
  1192. let size, ratio;
  1193. if (isNullOrUndef(thickness)) {
  1194. size = ruler.min * options.categoryPercentage;
  1195. ratio = options.barPercentage;
  1196. } else {
  1197. size = thickness * stackCount;
  1198. ratio = 1;
  1199. }
  1200. return {
  1201. chunk: size / stackCount,
  1202. ratio,
  1203. start: ruler.pixels[index] - size / 2
  1204. };
  1205. }
  1206. function computeFlexCategoryTraits(index, ruler, options, stackCount) {
  1207. const pixels = ruler.pixels;
  1208. const curr = pixels[index];
  1209. let prev = index > 0 ? pixels[index - 1] : null;
  1210. let next = index < pixels.length - 1 ? pixels[index + 1] : null;
  1211. const percent = options.categoryPercentage;
  1212. if (prev === null) {
  1213. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  1214. }
  1215. if (next === null) {
  1216. next = curr + curr - prev;
  1217. }
  1218. const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  1219. const size = Math.abs(next - prev) / 2 * percent;
  1220. return {
  1221. chunk: size / stackCount,
  1222. ratio: options.barPercentage,
  1223. start
  1224. };
  1225. }
  1226. function parseFloatBar(entry, item, vScale, i) {
  1227. const startValue = vScale.parse(entry[0], i);
  1228. const endValue = vScale.parse(entry[1], i);
  1229. const min = Math.min(startValue, endValue);
  1230. const max = Math.max(startValue, endValue);
  1231. let barStart = min;
  1232. let barEnd = max;
  1233. if (Math.abs(min) > Math.abs(max)) {
  1234. barStart = max;
  1235. barEnd = min;
  1236. }
  1237. item[vScale.axis] = barEnd;
  1238. item._custom = {
  1239. barStart,
  1240. barEnd,
  1241. start: startValue,
  1242. end: endValue,
  1243. min,
  1244. max
  1245. };
  1246. }
  1247. function parseValue(entry, item, vScale, i) {
  1248. if (isArray(entry)) {
  1249. parseFloatBar(entry, item, vScale, i);
  1250. } else {
  1251. item[vScale.axis] = vScale.parse(entry, i);
  1252. }
  1253. return item;
  1254. }
  1255. function parseArrayOrPrimitive(meta, data, start, count) {
  1256. const iScale = meta.iScale;
  1257. const vScale = meta.vScale;
  1258. const labels = iScale.getLabels();
  1259. const singleScale = iScale === vScale;
  1260. const parsed = [];
  1261. let i, ilen, item, entry;
  1262. for(i = start, ilen = start + count; i < ilen; ++i){
  1263. entry = data[i];
  1264. item = {};
  1265. item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
  1266. parsed.push(parseValue(entry, item, vScale, i));
  1267. }
  1268. return parsed;
  1269. }
  1270. function isFloatBar(custom) {
  1271. return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
  1272. }
  1273. function barSign(size, vScale, actualBase) {
  1274. if (size !== 0) {
  1275. return sign(size);
  1276. }
  1277. return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);
  1278. }
  1279. function borderProps(properties) {
  1280. let reverse, start, end, top, bottom;
  1281. if (properties.horizontal) {
  1282. reverse = properties.base > properties.x;
  1283. start = 'left';
  1284. end = 'right';
  1285. } else {
  1286. reverse = properties.base < properties.y;
  1287. start = 'bottom';
  1288. end = 'top';
  1289. }
  1290. if (reverse) {
  1291. top = 'end';
  1292. bottom = 'start';
  1293. } else {
  1294. top = 'start';
  1295. bottom = 'end';
  1296. }
  1297. return {
  1298. start,
  1299. end,
  1300. reverse,
  1301. top,
  1302. bottom
  1303. };
  1304. }
  1305. function setBorderSkipped(properties, options, stack, index) {
  1306. let edge = options.borderSkipped;
  1307. const res = {};
  1308. if (!edge) {
  1309. properties.borderSkipped = res;
  1310. return;
  1311. }
  1312. if (edge === true) {
  1313. properties.borderSkipped = {
  1314. top: true,
  1315. right: true,
  1316. bottom: true,
  1317. left: true
  1318. };
  1319. return;
  1320. }
  1321. const { start , end , reverse , top , bottom } = borderProps(properties);
  1322. if (edge === 'middle' && stack) {
  1323. properties.enableBorderRadius = true;
  1324. if ((stack._top || 0) === index) {
  1325. edge = top;
  1326. } else if ((stack._bottom || 0) === index) {
  1327. edge = bottom;
  1328. } else {
  1329. res[parseEdge(bottom, start, end, reverse)] = true;
  1330. edge = top;
  1331. }
  1332. }
  1333. res[parseEdge(edge, start, end, reverse)] = true;
  1334. properties.borderSkipped = res;
  1335. }
  1336. function parseEdge(edge, a, b, reverse) {
  1337. if (reverse) {
  1338. edge = swap(edge, a, b);
  1339. edge = startEnd(edge, b, a);
  1340. } else {
  1341. edge = startEnd(edge, a, b);
  1342. }
  1343. return edge;
  1344. }
  1345. function swap(orig, v1, v2) {
  1346. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  1347. }
  1348. function startEnd(v, start, end) {
  1349. return v === 'start' ? start : v === 'end' ? end : v;
  1350. }
  1351. function setInflateAmount(properties, { inflateAmount }, ratio) {
  1352. properties.inflateAmount = inflateAmount === 'auto' ? ratio === 1 ? 0.33 : 0 : inflateAmount;
  1353. }
  1354. class BarController extends DatasetController {
  1355. static id = 'bar';
  1356. static defaults = {
  1357. datasetElementType: false,
  1358. dataElementType: 'bar',
  1359. categoryPercentage: 0.8,
  1360. barPercentage: 0.9,
  1361. grouped: true,
  1362. animations: {
  1363. numbers: {
  1364. type: 'number',
  1365. properties: [
  1366. 'x',
  1367. 'y',
  1368. 'base',
  1369. 'width',
  1370. 'height'
  1371. ]
  1372. }
  1373. }
  1374. };
  1375. static overrides = {
  1376. scales: {
  1377. _index_: {
  1378. type: 'category',
  1379. offset: true,
  1380. grid: {
  1381. offset: true
  1382. }
  1383. },
  1384. _value_: {
  1385. type: 'linear',
  1386. beginAtZero: true
  1387. }
  1388. }
  1389. };
  1390. parsePrimitiveData(meta, data, start, count) {
  1391. return parseArrayOrPrimitive(meta, data, start, count);
  1392. }
  1393. parseArrayData(meta, data, start, count) {
  1394. return parseArrayOrPrimitive(meta, data, start, count);
  1395. }
  1396. parseObjectData(meta, data, start, count) {
  1397. const { iScale , vScale } = meta;
  1398. const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing;
  1399. const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
  1400. const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
  1401. const parsed = [];
  1402. let i, ilen, item, obj;
  1403. for(i = start, ilen = start + count; i < ilen; ++i){
  1404. obj = data[i];
  1405. item = {};
  1406. item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);
  1407. parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));
  1408. }
  1409. return parsed;
  1410. }
  1411. updateRangeFromParsed(range, scale, parsed, stack) {
  1412. super.updateRangeFromParsed(range, scale, parsed, stack);
  1413. const custom = parsed._custom;
  1414. if (custom && scale === this._cachedMeta.vScale) {
  1415. range.min = Math.min(range.min, custom.min);
  1416. range.max = Math.max(range.max, custom.max);
  1417. }
  1418. }
  1419. getMaxOverflow() {
  1420. return 0;
  1421. }
  1422. getLabelAndValue(index) {
  1423. const meta = this._cachedMeta;
  1424. const { iScale , vScale } = meta;
  1425. const parsed = this.getParsed(index);
  1426. const custom = parsed._custom;
  1427. const value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]);
  1428. return {
  1429. label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
  1430. value
  1431. };
  1432. }
  1433. initialize() {
  1434. this.enableOptionSharing = true;
  1435. super.initialize();
  1436. const meta = this._cachedMeta;
  1437. meta.stack = this.getDataset().stack;
  1438. }
  1439. update(mode) {
  1440. const meta = this._cachedMeta;
  1441. this.updateElements(meta.data, 0, meta.data.length, mode);
  1442. }
  1443. updateElements(bars, start, count, mode) {
  1444. const reset = mode === 'reset';
  1445. const { index , _cachedMeta: { vScale } } = this;
  1446. const base = vScale.getBasePixel();
  1447. const horizontal = vScale.isHorizontal();
  1448. const ruler = this._getRuler();
  1449. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1450. for(let i = start; i < start + count; i++){
  1451. const parsed = this.getParsed(i);
  1452. const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {
  1453. base,
  1454. head: base
  1455. } : this._calculateBarValuePixels(i);
  1456. const ipixels = this._calculateBarIndexPixels(i, ruler);
  1457. const stack = (parsed._stacks || {})[vScale.axis];
  1458. const properties = {
  1459. horizontal,
  1460. base: vpixels.base,
  1461. enableBorderRadius: !stack || isFloatBar(parsed._custom) || index === stack._top || index === stack._bottom,
  1462. x: horizontal ? vpixels.head : ipixels.center,
  1463. y: horizontal ? ipixels.center : vpixels.head,
  1464. height: horizontal ? ipixels.size : Math.abs(vpixels.size),
  1465. width: horizontal ? Math.abs(vpixels.size) : ipixels.size
  1466. };
  1467. if (includeOptions) {
  1468. properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);
  1469. }
  1470. const options = properties.options || bars[i].options;
  1471. setBorderSkipped(properties, options, stack, index);
  1472. setInflateAmount(properties, options, ruler.ratio);
  1473. this.updateElement(bars[i], i, properties, mode);
  1474. }
  1475. }
  1476. _getStacks(last, dataIndex) {
  1477. const { iScale } = this._cachedMeta;
  1478. const metasets = iScale.getMatchingVisibleMetas(this._type).filter((meta)=>meta.controller.options.grouped);
  1479. const stacked = iScale.options.stacked;
  1480. const stacks = [];
  1481. const skipNull = (meta)=>{
  1482. const parsed = meta.controller.getParsed(dataIndex);
  1483. const val = parsed && parsed[meta.vScale.axis];
  1484. if (isNullOrUndef(val) || isNaN(val)) {
  1485. return true;
  1486. }
  1487. };
  1488. for (const meta of metasets){
  1489. if (dataIndex !== undefined && skipNull(meta)) {
  1490. continue;
  1491. }
  1492. if (stacked === false || stacks.indexOf(meta.stack) === -1 || stacked === undefined && meta.stack === undefined) {
  1493. stacks.push(meta.stack);
  1494. }
  1495. if (meta.index === last) {
  1496. break;
  1497. }
  1498. }
  1499. if (!stacks.length) {
  1500. stacks.push(undefined);
  1501. }
  1502. return stacks;
  1503. }
  1504. _getStackCount(index) {
  1505. return this._getStacks(undefined, index).length;
  1506. }
  1507. _getStackIndex(datasetIndex, name, dataIndex) {
  1508. const stacks = this._getStacks(datasetIndex, dataIndex);
  1509. const index = name !== undefined ? stacks.indexOf(name) : -1;
  1510. return index === -1 ? stacks.length - 1 : index;
  1511. }
  1512. _getRuler() {
  1513. const opts = this.options;
  1514. const meta = this._cachedMeta;
  1515. const iScale = meta.iScale;
  1516. const pixels = [];
  1517. let i, ilen;
  1518. for(i = 0, ilen = meta.data.length; i < ilen; ++i){
  1519. pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));
  1520. }
  1521. const barThickness = opts.barThickness;
  1522. const min = barThickness || computeMinSampleSize(meta);
  1523. return {
  1524. min,
  1525. pixels,
  1526. start: iScale._startPixel,
  1527. end: iScale._endPixel,
  1528. stackCount: this._getStackCount(),
  1529. scale: iScale,
  1530. grouped: opts.grouped,
  1531. ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
  1532. };
  1533. }
  1534. _calculateBarValuePixels(index) {
  1535. const { _cachedMeta: { vScale , _stacked , index: datasetIndex } , options: { base: baseValue , minBarLength } } = this;
  1536. const actualBase = baseValue || 0;
  1537. const parsed = this.getParsed(index);
  1538. const custom = parsed._custom;
  1539. const floating = isFloatBar(custom);
  1540. let value = parsed[vScale.axis];
  1541. let start = 0;
  1542. let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;
  1543. let head, size;
  1544. if (length !== value) {
  1545. start = length - value;
  1546. length = value;
  1547. }
  1548. if (floating) {
  1549. value = custom.barStart;
  1550. length = custom.barEnd - custom.barStart;
  1551. if (value !== 0 && sign(value) !== sign(custom.barEnd)) {
  1552. start = 0;
  1553. }
  1554. start += value;
  1555. }
  1556. const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;
  1557. let base = vScale.getPixelForValue(startValue);
  1558. if (this.chart.getDataVisibility(index)) {
  1559. head = vScale.getPixelForValue(start + length);
  1560. } else {
  1561. head = base;
  1562. }
  1563. size = head - base;
  1564. if (Math.abs(size) < minBarLength) {
  1565. size = barSign(size, vScale, actualBase) * minBarLength;
  1566. if (value === actualBase) {
  1567. base -= size / 2;
  1568. }
  1569. const startPixel = vScale.getPixelForDecimal(0);
  1570. const endPixel = vScale.getPixelForDecimal(1);
  1571. const min = Math.min(startPixel, endPixel);
  1572. const max = Math.max(startPixel, endPixel);
  1573. base = Math.max(Math.min(base, max), min);
  1574. head = base + size;
  1575. if (_stacked && !floating) {
  1576. parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);
  1577. }
  1578. }
  1579. if (base === vScale.getPixelForValue(actualBase)) {
  1580. const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;
  1581. base += halfGrid;
  1582. size -= halfGrid;
  1583. }
  1584. return {
  1585. size,
  1586. base,
  1587. head,
  1588. center: head + size / 2
  1589. };
  1590. }
  1591. _calculateBarIndexPixels(index, ruler) {
  1592. const scale = ruler.scale;
  1593. const options = this.options;
  1594. const skipNull = options.skipNull;
  1595. const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);
  1596. let center, size;
  1597. if (ruler.grouped) {
  1598. const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;
  1599. const range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount) : computeFitCategoryTraits(index, ruler, options, stackCount);
  1600. const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined);
  1601. center = range.start + range.chunk * stackIndex + range.chunk / 2;
  1602. size = Math.min(maxBarThickness, range.chunk * range.ratio);
  1603. } else {
  1604. center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);
  1605. size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
  1606. }
  1607. return {
  1608. base: center - size / 2,
  1609. head: center + size / 2,
  1610. center,
  1611. size
  1612. };
  1613. }
  1614. draw() {
  1615. const meta = this._cachedMeta;
  1616. const vScale = meta.vScale;
  1617. const rects = meta.data;
  1618. const ilen = rects.length;
  1619. let i = 0;
  1620. for(; i < ilen; ++i){
  1621. if (this.getParsed(i)[vScale.axis] !== null) {
  1622. rects[i].draw(this._ctx);
  1623. }
  1624. }
  1625. }
  1626. }
  1627. class BubbleController extends DatasetController {
  1628. static id = 'bubble';
  1629. static defaults = {
  1630. datasetElementType: false,
  1631. dataElementType: 'point',
  1632. animations: {
  1633. numbers: {
  1634. type: 'number',
  1635. properties: [
  1636. 'x',
  1637. 'y',
  1638. 'borderWidth',
  1639. 'radius'
  1640. ]
  1641. }
  1642. }
  1643. };
  1644. static overrides = {
  1645. scales: {
  1646. x: {
  1647. type: 'linear'
  1648. },
  1649. y: {
  1650. type: 'linear'
  1651. }
  1652. }
  1653. };
  1654. initialize() {
  1655. this.enableOptionSharing = true;
  1656. super.initialize();
  1657. }
  1658. parsePrimitiveData(meta, data, start, count) {
  1659. const parsed = super.parsePrimitiveData(meta, data, start, count);
  1660. for(let i = 0; i < parsed.length; i++){
  1661. parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;
  1662. }
  1663. return parsed;
  1664. }
  1665. parseArrayData(meta, data, start, count) {
  1666. const parsed = super.parseArrayData(meta, data, start, count);
  1667. for(let i = 0; i < parsed.length; i++){
  1668. const item = data[start + i];
  1669. parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);
  1670. }
  1671. return parsed;
  1672. }
  1673. parseObjectData(meta, data, start, count) {
  1674. const parsed = super.parseObjectData(meta, data, start, count);
  1675. for(let i = 0; i < parsed.length; i++){
  1676. const item = data[start + i];
  1677. parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);
  1678. }
  1679. return parsed;
  1680. }
  1681. getMaxOverflow() {
  1682. const data = this._cachedMeta.data;
  1683. let max = 0;
  1684. for(let i = data.length - 1; i >= 0; --i){
  1685. max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
  1686. }
  1687. return max > 0 && max;
  1688. }
  1689. getLabelAndValue(index) {
  1690. const meta = this._cachedMeta;
  1691. const labels = this.chart.data.labels || [];
  1692. const { xScale , yScale } = meta;
  1693. const parsed = this.getParsed(index);
  1694. const x = xScale.getLabelForValue(parsed.x);
  1695. const y = yScale.getLabelForValue(parsed.y);
  1696. const r = parsed._custom;
  1697. return {
  1698. label: labels[index] || '',
  1699. value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
  1700. };
  1701. }
  1702. update(mode) {
  1703. const points = this._cachedMeta.data;
  1704. this.updateElements(points, 0, points.length, mode);
  1705. }
  1706. updateElements(points, start, count, mode) {
  1707. const reset = mode === 'reset';
  1708. const { iScale , vScale } = this._cachedMeta;
  1709. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1710. const iAxis = iScale.axis;
  1711. const vAxis = vScale.axis;
  1712. for(let i = start; i < start + count; i++){
  1713. const point = points[i];
  1714. const parsed = !reset && this.getParsed(i);
  1715. const properties = {};
  1716. const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);
  1717. const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);
  1718. properties.skip = isNaN(iPixel) || isNaN(vPixel);
  1719. if (includeOptions) {
  1720. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  1721. if (reset) {
  1722. properties.options.radius = 0;
  1723. }
  1724. }
  1725. this.updateElement(point, i, properties, mode);
  1726. }
  1727. }
  1728. resolveDataElementOptions(index, mode) {
  1729. const parsed = this.getParsed(index);
  1730. let values = super.resolveDataElementOptions(index, mode);
  1731. if (values.$shared) {
  1732. values = Object.assign({}, values, {
  1733. $shared: false
  1734. });
  1735. }
  1736. const radius = values.radius;
  1737. if (mode !== 'active') {
  1738. values.radius = 0;
  1739. }
  1740. values.radius += valueOrDefault(parsed && parsed._custom, radius);
  1741. return values;
  1742. }
  1743. }
  1744. function getRatioAndOffset(rotation, circumference, cutout) {
  1745. let ratioX = 1;
  1746. let ratioY = 1;
  1747. let offsetX = 0;
  1748. let offsetY = 0;
  1749. if (circumference < TAU) {
  1750. const startAngle = rotation;
  1751. const endAngle = startAngle + circumference;
  1752. const startX = Math.cos(startAngle);
  1753. const startY = Math.sin(startAngle);
  1754. const endX = Math.cos(endAngle);
  1755. const endY = Math.sin(endAngle);
  1756. const calcMax = (angle, a, b)=>_angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);
  1757. const calcMin = (angle, a, b)=>_angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);
  1758. const maxX = calcMax(0, startX, endX);
  1759. const maxY = calcMax(HALF_PI, startY, endY);
  1760. const minX = calcMin(PI, startX, endX);
  1761. const minY = calcMin(PI + HALF_PI, startY, endY);
  1762. ratioX = (maxX - minX) / 2;
  1763. ratioY = (maxY - minY) / 2;
  1764. offsetX = -(maxX + minX) / 2;
  1765. offsetY = -(maxY + minY) / 2;
  1766. }
  1767. return {
  1768. ratioX,
  1769. ratioY,
  1770. offsetX,
  1771. offsetY
  1772. };
  1773. }
  1774. class DoughnutController extends DatasetController {
  1775. static id = 'doughnut';
  1776. static defaults = {
  1777. datasetElementType: false,
  1778. dataElementType: 'arc',
  1779. animation: {
  1780. animateRotate: true,
  1781. animateScale: false
  1782. },
  1783. animations: {
  1784. numbers: {
  1785. type: 'number',
  1786. properties: [
  1787. 'circumference',
  1788. 'endAngle',
  1789. 'innerRadius',
  1790. 'outerRadius',
  1791. 'startAngle',
  1792. 'x',
  1793. 'y',
  1794. 'offset',
  1795. 'borderWidth',
  1796. 'spacing'
  1797. ]
  1798. }
  1799. },
  1800. cutout: '50%',
  1801. rotation: 0,
  1802. circumference: 360,
  1803. radius: '100%',
  1804. spacing: 0,
  1805. indexAxis: 'r'
  1806. };
  1807. static descriptors = {
  1808. _scriptable: (name)=>name !== 'spacing',
  1809. _indexable: (name)=>name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash')
  1810. };
  1811. static overrides = {
  1812. aspectRatio: 1,
  1813. plugins: {
  1814. legend: {
  1815. labels: {
  1816. generateLabels (chart) {
  1817. const data = chart.data;
  1818. if (data.labels.length && data.datasets.length) {
  1819. const { labels: { pointStyle , color } } = chart.legend.options;
  1820. return data.labels.map((label, i)=>{
  1821. const meta = chart.getDatasetMeta(0);
  1822. const style = meta.controller.getStyle(i);
  1823. return {
  1824. text: label,
  1825. fillStyle: style.backgroundColor,
  1826. strokeStyle: style.borderColor,
  1827. fontColor: color,
  1828. lineWidth: style.borderWidth,
  1829. pointStyle: pointStyle,
  1830. hidden: !chart.getDataVisibility(i),
  1831. index: i
  1832. };
  1833. });
  1834. }
  1835. return [];
  1836. }
  1837. },
  1838. onClick (e, legendItem, legend) {
  1839. legend.chart.toggleDataVisibility(legendItem.index);
  1840. legend.chart.update();
  1841. }
  1842. }
  1843. }
  1844. };
  1845. constructor(chart, datasetIndex){
  1846. super(chart, datasetIndex);
  1847. this.enableOptionSharing = true;
  1848. this.innerRadius = undefined;
  1849. this.outerRadius = undefined;
  1850. this.offsetX = undefined;
  1851. this.offsetY = undefined;
  1852. }
  1853. linkScales() {}
  1854. parse(start, count) {
  1855. const data = this.getDataset().data;
  1856. const meta = this._cachedMeta;
  1857. if (this._parsing === false) {
  1858. meta._parsed = data;
  1859. } else {
  1860. let getter = (i)=>+data[i];
  1861. if (isObject(data[start])) {
  1862. const { key ='value' } = this._parsing;
  1863. getter = (i)=>+resolveObjectKey(data[i], key);
  1864. }
  1865. let i, ilen;
  1866. for(i = start, ilen = start + count; i < ilen; ++i){
  1867. meta._parsed[i] = getter(i);
  1868. }
  1869. }
  1870. }
  1871. _getRotation() {
  1872. return toRadians(this.options.rotation - 90);
  1873. }
  1874. _getCircumference() {
  1875. return toRadians(this.options.circumference);
  1876. }
  1877. _getRotationExtents() {
  1878. let min = TAU;
  1879. let max = -TAU;
  1880. for(let i = 0; i < this.chart.data.datasets.length; ++i){
  1881. if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {
  1882. const controller = this.chart.getDatasetMeta(i).controller;
  1883. const rotation = controller._getRotation();
  1884. const circumference = controller._getCircumference();
  1885. min = Math.min(min, rotation);
  1886. max = Math.max(max, rotation + circumference);
  1887. }
  1888. }
  1889. return {
  1890. rotation: min,
  1891. circumference: max - min
  1892. };
  1893. }
  1894. update(mode) {
  1895. const chart = this.chart;
  1896. const { chartArea } = chart;
  1897. const meta = this._cachedMeta;
  1898. const arcs = meta.data;
  1899. const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;
  1900. const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
  1901. const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);
  1902. const chartWeight = this._getRingWeight(this.index);
  1903. const { circumference , rotation } = this._getRotationExtents();
  1904. const { ratioX , ratioY , offsetX , offsetY } = getRatioAndOffset(rotation, circumference, cutout);
  1905. const maxWidth = (chartArea.width - spacing) / ratioX;
  1906. const maxHeight = (chartArea.height - spacing) / ratioY;
  1907. const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  1908. const outerRadius = toDimension(this.options.radius, maxRadius);
  1909. const innerRadius = Math.max(outerRadius * cutout, 0);
  1910. const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();
  1911. this.offsetX = offsetX * outerRadius;
  1912. this.offsetY = offsetY * outerRadius;
  1913. meta.total = this.calculateTotal();
  1914. this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);
  1915. this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);
  1916. this.updateElements(arcs, 0, arcs.length, mode);
  1917. }
  1918. _circumference(i, reset) {
  1919. const opts = this.options;
  1920. const meta = this._cachedMeta;
  1921. const circumference = this._getCircumference();
  1922. if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {
  1923. return 0;
  1924. }
  1925. return this.calculateCircumference(meta._parsed[i] * circumference / TAU);
  1926. }
  1927. updateElements(arcs, start, count, mode) {
  1928. const reset = mode === 'reset';
  1929. const chart = this.chart;
  1930. const chartArea = chart.chartArea;
  1931. const opts = chart.options;
  1932. const animationOpts = opts.animation;
  1933. const centerX = (chartArea.left + chartArea.right) / 2;
  1934. const centerY = (chartArea.top + chartArea.bottom) / 2;
  1935. const animateScale = reset && animationOpts.animateScale;
  1936. const innerRadius = animateScale ? 0 : this.innerRadius;
  1937. const outerRadius = animateScale ? 0 : this.outerRadius;
  1938. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1939. let startAngle = this._getRotation();
  1940. let i;
  1941. for(i = 0; i < start; ++i){
  1942. startAngle += this._circumference(i, reset);
  1943. }
  1944. for(i = start; i < start + count; ++i){
  1945. const circumference = this._circumference(i, reset);
  1946. const arc = arcs[i];
  1947. const properties = {
  1948. x: centerX + this.offsetX,
  1949. y: centerY + this.offsetY,
  1950. startAngle,
  1951. endAngle: startAngle + circumference,
  1952. circumference,
  1953. outerRadius,
  1954. innerRadius
  1955. };
  1956. if (includeOptions) {
  1957. properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);
  1958. }
  1959. startAngle += circumference;
  1960. this.updateElement(arc, i, properties, mode);
  1961. }
  1962. }
  1963. calculateTotal() {
  1964. const meta = this._cachedMeta;
  1965. const metaData = meta.data;
  1966. let total = 0;
  1967. let i;
  1968. for(i = 0; i < metaData.length; i++){
  1969. const value = meta._parsed[i];
  1970. if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {
  1971. total += Math.abs(value);
  1972. }
  1973. }
  1974. return total;
  1975. }
  1976. calculateCircumference(value) {
  1977. const total = this._cachedMeta.total;
  1978. if (total > 0 && !isNaN(value)) {
  1979. return TAU * (Math.abs(value) / total);
  1980. }
  1981. return 0;
  1982. }
  1983. getLabelAndValue(index) {
  1984. const meta = this._cachedMeta;
  1985. const chart = this.chart;
  1986. const labels = chart.data.labels || [];
  1987. const value = formatNumber(meta._parsed[index], chart.options.locale);
  1988. return {
  1989. label: labels[index] || '',
  1990. value
  1991. };
  1992. }
  1993. getMaxBorderWidth(arcs) {
  1994. let max = 0;
  1995. const chart = this.chart;
  1996. let i, ilen, meta, controller, options;
  1997. if (!arcs) {
  1998. for(i = 0, ilen = chart.data.datasets.length; i < ilen; ++i){
  1999. if (chart.isDatasetVisible(i)) {
  2000. meta = chart.getDatasetMeta(i);
  2001. arcs = meta.data;
  2002. controller = meta.controller;
  2003. break;
  2004. }
  2005. }
  2006. }
  2007. if (!arcs) {
  2008. return 0;
  2009. }
  2010. for(i = 0, ilen = arcs.length; i < ilen; ++i){
  2011. options = controller.resolveDataElementOptions(i);
  2012. if (options.borderAlign !== 'inner') {
  2013. max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
  2014. }
  2015. }
  2016. return max;
  2017. }
  2018. getMaxOffset(arcs) {
  2019. let max = 0;
  2020. for(let i = 0, ilen = arcs.length; i < ilen; ++i){
  2021. const options = this.resolveDataElementOptions(i);
  2022. max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
  2023. }
  2024. return max;
  2025. }
  2026. _getRingWeightOffset(datasetIndex) {
  2027. let ringWeightOffset = 0;
  2028. for(let i = 0; i < datasetIndex; ++i){
  2029. if (this.chart.isDatasetVisible(i)) {
  2030. ringWeightOffset += this._getRingWeight(i);
  2031. }
  2032. }
  2033. return ringWeightOffset;
  2034. }
  2035. _getRingWeight(datasetIndex) {
  2036. return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
  2037. }
  2038. _getVisibleDatasetWeightTotal() {
  2039. return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
  2040. }
  2041. }
  2042. class LineController extends DatasetController {
  2043. static id = 'line';
  2044. static defaults = {
  2045. datasetElementType: 'line',
  2046. dataElementType: 'point',
  2047. showLine: true,
  2048. spanGaps: false
  2049. };
  2050. static overrides = {
  2051. scales: {
  2052. _index_: {
  2053. type: 'category'
  2054. },
  2055. _value_: {
  2056. type: 'linear'
  2057. }
  2058. }
  2059. };
  2060. initialize() {
  2061. this.enableOptionSharing = true;
  2062. this.supportsDecimation = true;
  2063. super.initialize();
  2064. }
  2065. update(mode) {
  2066. const meta = this._cachedMeta;
  2067. const { dataset: line , data: points = [] , _dataset } = meta;
  2068. const animationsDisabled = this.chart._animationsDisabled;
  2069. let { start , count } = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  2070. this._drawStart = start;
  2071. this._drawCount = count;
  2072. if (_scaleRangesChanged(meta)) {
  2073. start = 0;
  2074. count = points.length;
  2075. }
  2076. line._chart = this.chart;
  2077. line._datasetIndex = this.index;
  2078. line._decimated = !!_dataset._decimated;
  2079. line.points = points;
  2080. const options = this.resolveDatasetElementOptions(mode);
  2081. if (!this.options.showLine) {
  2082. options.borderWidth = 0;
  2083. }
  2084. options.segment = this.options.segment;
  2085. this.updateElement(line, undefined, {
  2086. animated: !animationsDisabled,
  2087. options
  2088. }, mode);
  2089. this.updateElements(points, start, count, mode);
  2090. }
  2091. updateElements(points, start, count, mode) {
  2092. const reset = mode === 'reset';
  2093. const { iScale , vScale , _stacked , _dataset } = this._cachedMeta;
  2094. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  2095. const iAxis = iScale.axis;
  2096. const vAxis = vScale.axis;
  2097. const { spanGaps , segment } = this.options;
  2098. const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  2099. const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
  2100. const end = start + count;
  2101. const pointsCount = points.length;
  2102. let prevParsed = start > 0 && this.getParsed(start - 1);
  2103. for(let i = 0; i < pointsCount; ++i){
  2104. const point = points[i];
  2105. const properties = directUpdate ? point : {};
  2106. if (i < start || i >= end) {
  2107. properties.skip = true;
  2108. continue;
  2109. }
  2110. const parsed = this.getParsed(i);
  2111. const nullData = isNullOrUndef(parsed[vAxis]);
  2112. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  2113. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  2114. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  2115. properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  2116. if (segment) {
  2117. properties.parsed = parsed;
  2118. properties.raw = _dataset.data[i];
  2119. }
  2120. if (includeOptions) {
  2121. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2122. }
  2123. if (!directUpdate) {
  2124. this.updateElement(point, i, properties, mode);
  2125. }
  2126. prevParsed = parsed;
  2127. }
  2128. }
  2129. getMaxOverflow() {
  2130. const meta = this._cachedMeta;
  2131. const dataset = meta.dataset;
  2132. const border = dataset.options && dataset.options.borderWidth || 0;
  2133. const data = meta.data || [];
  2134. if (!data.length) {
  2135. return border;
  2136. }
  2137. const firstPoint = data[0].size(this.resolveDataElementOptions(0));
  2138. const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
  2139. return Math.max(border, firstPoint, lastPoint) / 2;
  2140. }
  2141. draw() {
  2142. const meta = this._cachedMeta;
  2143. meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);
  2144. super.draw();
  2145. }
  2146. }
  2147. class PolarAreaController extends DatasetController {
  2148. static id = 'polarArea';
  2149. static defaults = {
  2150. dataElementType: 'arc',
  2151. animation: {
  2152. animateRotate: true,
  2153. animateScale: true
  2154. },
  2155. animations: {
  2156. numbers: {
  2157. type: 'number',
  2158. properties: [
  2159. 'x',
  2160. 'y',
  2161. 'startAngle',
  2162. 'endAngle',
  2163. 'innerRadius',
  2164. 'outerRadius'
  2165. ]
  2166. }
  2167. },
  2168. indexAxis: 'r',
  2169. startAngle: 0
  2170. };
  2171. static overrides = {
  2172. aspectRatio: 1,
  2173. plugins: {
  2174. legend: {
  2175. labels: {
  2176. generateLabels (chart) {
  2177. const data = chart.data;
  2178. if (data.labels.length && data.datasets.length) {
  2179. const { labels: { pointStyle , color } } = chart.legend.options;
  2180. return data.labels.map((label, i)=>{
  2181. const meta = chart.getDatasetMeta(0);
  2182. const style = meta.controller.getStyle(i);
  2183. return {
  2184. text: label,
  2185. fillStyle: style.backgroundColor,
  2186. strokeStyle: style.borderColor,
  2187. fontColor: color,
  2188. lineWidth: style.borderWidth,
  2189. pointStyle: pointStyle,
  2190. hidden: !chart.getDataVisibility(i),
  2191. index: i
  2192. };
  2193. });
  2194. }
  2195. return [];
  2196. }
  2197. },
  2198. onClick (e, legendItem, legend) {
  2199. legend.chart.toggleDataVisibility(legendItem.index);
  2200. legend.chart.update();
  2201. }
  2202. }
  2203. },
  2204. scales: {
  2205. r: {
  2206. type: 'radialLinear',
  2207. angleLines: {
  2208. display: false
  2209. },
  2210. beginAtZero: true,
  2211. grid: {
  2212. circular: true
  2213. },
  2214. pointLabels: {
  2215. display: false
  2216. },
  2217. startAngle: 0
  2218. }
  2219. }
  2220. };
  2221. constructor(chart, datasetIndex){
  2222. super(chart, datasetIndex);
  2223. this.innerRadius = undefined;
  2224. this.outerRadius = undefined;
  2225. }
  2226. getLabelAndValue(index) {
  2227. const meta = this._cachedMeta;
  2228. const chart = this.chart;
  2229. const labels = chart.data.labels || [];
  2230. const value = formatNumber(meta._parsed[index].r, chart.options.locale);
  2231. return {
  2232. label: labels[index] || '',
  2233. value
  2234. };
  2235. }
  2236. parseObjectData(meta, data, start, count) {
  2237. return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2238. }
  2239. update(mode) {
  2240. const arcs = this._cachedMeta.data;
  2241. this._updateRadius();
  2242. this.updateElements(arcs, 0, arcs.length, mode);
  2243. }
  2244. getMinMax() {
  2245. const meta = this._cachedMeta;
  2246. const range = {
  2247. min: Number.POSITIVE_INFINITY,
  2248. max: Number.NEGATIVE_INFINITY
  2249. };
  2250. meta.data.forEach((element, index)=>{
  2251. const parsed = this.getParsed(index).r;
  2252. if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {
  2253. if (parsed < range.min) {
  2254. range.min = parsed;
  2255. }
  2256. if (parsed > range.max) {
  2257. range.max = parsed;
  2258. }
  2259. }
  2260. });
  2261. return range;
  2262. }
  2263. _updateRadius() {
  2264. const chart = this.chart;
  2265. const chartArea = chart.chartArea;
  2266. const opts = chart.options;
  2267. const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  2268. const outerRadius = Math.max(minSize / 2, 0);
  2269. const innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0);
  2270. const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
  2271. this.outerRadius = outerRadius - radiusLength * this.index;
  2272. this.innerRadius = this.outerRadius - radiusLength;
  2273. }
  2274. updateElements(arcs, start, count, mode) {
  2275. const reset = mode === 'reset';
  2276. const chart = this.chart;
  2277. const opts = chart.options;
  2278. const animationOpts = opts.animation;
  2279. const scale = this._cachedMeta.rScale;
  2280. const centerX = scale.xCenter;
  2281. const centerY = scale.yCenter;
  2282. const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;
  2283. let angle = datasetStartAngle;
  2284. let i;
  2285. const defaultAngle = 360 / this.countVisibleElements();
  2286. for(i = 0; i < start; ++i){
  2287. angle += this._computeAngle(i, mode, defaultAngle);
  2288. }
  2289. for(i = start; i < start + count; i++){
  2290. const arc = arcs[i];
  2291. let startAngle = angle;
  2292. let endAngle = angle + this._computeAngle(i, mode, defaultAngle);
  2293. let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;
  2294. angle = endAngle;
  2295. if (reset) {
  2296. if (animationOpts.animateScale) {
  2297. outerRadius = 0;
  2298. }
  2299. if (animationOpts.animateRotate) {
  2300. startAngle = endAngle = datasetStartAngle;
  2301. }
  2302. }
  2303. const properties = {
  2304. x: centerX,
  2305. y: centerY,
  2306. innerRadius: 0,
  2307. outerRadius,
  2308. startAngle,
  2309. endAngle,
  2310. options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)
  2311. };
  2312. this.updateElement(arc, i, properties, mode);
  2313. }
  2314. }
  2315. countVisibleElements() {
  2316. const meta = this._cachedMeta;
  2317. let count = 0;
  2318. meta.data.forEach((element, index)=>{
  2319. if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {
  2320. count++;
  2321. }
  2322. });
  2323. return count;
  2324. }
  2325. _computeAngle(index, mode, defaultAngle) {
  2326. return this.chart.getDataVisibility(index) ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0;
  2327. }
  2328. }
  2329. class PieController extends DoughnutController {
  2330. static id = 'pie';
  2331. static defaults = {
  2332. cutout: 0,
  2333. rotation: 0,
  2334. circumference: 360,
  2335. radius: '100%'
  2336. };
  2337. }
  2338. class RadarController extends DatasetController {
  2339. static id = 'radar';
  2340. static defaults = {
  2341. datasetElementType: 'line',
  2342. dataElementType: 'point',
  2343. indexAxis: 'r',
  2344. showLine: true,
  2345. elements: {
  2346. line: {
  2347. fill: 'start'
  2348. }
  2349. }
  2350. };
  2351. static overrides = {
  2352. aspectRatio: 1,
  2353. scales: {
  2354. r: {
  2355. type: 'radialLinear'
  2356. }
  2357. }
  2358. };
  2359. getLabelAndValue(index) {
  2360. const vScale = this._cachedMeta.vScale;
  2361. const parsed = this.getParsed(index);
  2362. return {
  2363. label: vScale.getLabels()[index],
  2364. value: '' + vScale.getLabelForValue(parsed[vScale.axis])
  2365. };
  2366. }
  2367. parseObjectData(meta, data, start, count) {
  2368. return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2369. }
  2370. update(mode) {
  2371. const meta = this._cachedMeta;
  2372. const line = meta.dataset;
  2373. const points = meta.data || [];
  2374. const labels = meta.iScale.getLabels();
  2375. line.points = points;
  2376. if (mode !== 'resize') {
  2377. const options = this.resolveDatasetElementOptions(mode);
  2378. if (!this.options.showLine) {
  2379. options.borderWidth = 0;
  2380. }
  2381. const properties = {
  2382. _loop: true,
  2383. _fullLoop: labels.length === points.length,
  2384. options
  2385. };
  2386. this.updateElement(line, undefined, properties, mode);
  2387. }
  2388. this.updateElements(points, 0, points.length, mode);
  2389. }
  2390. updateElements(points, start, count, mode) {
  2391. const scale = this._cachedMeta.rScale;
  2392. const reset = mode === 'reset';
  2393. for(let i = start; i < start + count; i++){
  2394. const point = points[i];
  2395. const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2396. const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);
  2397. const x = reset ? scale.xCenter : pointPosition.x;
  2398. const y = reset ? scale.yCenter : pointPosition.y;
  2399. const properties = {
  2400. x,
  2401. y,
  2402. angle: pointPosition.angle,
  2403. skip: isNaN(x) || isNaN(y),
  2404. options
  2405. };
  2406. this.updateElement(point, i, properties, mode);
  2407. }
  2408. }
  2409. }
  2410. class ScatterController extends DatasetController {
  2411. static id = 'scatter';
  2412. static defaults = {
  2413. datasetElementType: false,
  2414. dataElementType: 'point',
  2415. showLine: false,
  2416. fill: false
  2417. };
  2418. static overrides = {
  2419. interaction: {
  2420. mode: 'point'
  2421. },
  2422. scales: {
  2423. x: {
  2424. type: 'linear'
  2425. },
  2426. y: {
  2427. type: 'linear'
  2428. }
  2429. }
  2430. };
  2431. getLabelAndValue(index) {
  2432. const meta = this._cachedMeta;
  2433. const labels = this.chart.data.labels || [];
  2434. const { xScale , yScale } = meta;
  2435. const parsed = this.getParsed(index);
  2436. const x = xScale.getLabelForValue(parsed.x);
  2437. const y = yScale.getLabelForValue(parsed.y);
  2438. return {
  2439. label: labels[index] || '',
  2440. value: '(' + x + ', ' + y + ')'
  2441. };
  2442. }
  2443. update(mode) {
  2444. const meta = this._cachedMeta;
  2445. const { data: points = [] } = meta;
  2446. const animationsDisabled = this.chart._animationsDisabled;
  2447. let { start , count } = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  2448. this._drawStart = start;
  2449. this._drawCount = count;
  2450. if (_scaleRangesChanged(meta)) {
  2451. start = 0;
  2452. count = points.length;
  2453. }
  2454. if (this.options.showLine) {
  2455. if (!this.datasetElementType) {
  2456. this.addElements();
  2457. }
  2458. const { dataset: line , _dataset } = meta;
  2459. line._chart = this.chart;
  2460. line._datasetIndex = this.index;
  2461. line._decimated = !!_dataset._decimated;
  2462. line.points = points;
  2463. const options = this.resolveDatasetElementOptions(mode);
  2464. options.segment = this.options.segment;
  2465. this.updateElement(line, undefined, {
  2466. animated: !animationsDisabled,
  2467. options
  2468. }, mode);
  2469. } else if (this.datasetElementType) {
  2470. delete meta.dataset;
  2471. this.datasetElementType = false;
  2472. }
  2473. this.updateElements(points, start, count, mode);
  2474. }
  2475. addElements() {
  2476. const { showLine } = this.options;
  2477. if (!this.datasetElementType && showLine) {
  2478. this.datasetElementType = this.chart.registry.getElement('line');
  2479. }
  2480. super.addElements();
  2481. }
  2482. updateElements(points, start, count, mode) {
  2483. const reset = mode === 'reset';
  2484. const { iScale , vScale , _stacked , _dataset } = this._cachedMeta;
  2485. const firstOpts = this.resolveDataElementOptions(start, mode);
  2486. const sharedOptions = this.getSharedOptions(firstOpts);
  2487. const includeOptions = this.includeOptions(mode, sharedOptions);
  2488. const iAxis = iScale.axis;
  2489. const vAxis = vScale.axis;
  2490. const { spanGaps , segment } = this.options;
  2491. const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  2492. const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
  2493. let prevParsed = start > 0 && this.getParsed(start - 1);
  2494. for(let i = start; i < start + count; ++i){
  2495. const point = points[i];
  2496. const parsed = this.getParsed(i);
  2497. const properties = directUpdate ? point : {};
  2498. const nullData = isNullOrUndef(parsed[vAxis]);
  2499. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  2500. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  2501. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  2502. properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  2503. if (segment) {
  2504. properties.parsed = parsed;
  2505. properties.raw = _dataset.data[i];
  2506. }
  2507. if (includeOptions) {
  2508. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2509. }
  2510. if (!directUpdate) {
  2511. this.updateElement(point, i, properties, mode);
  2512. }
  2513. prevParsed = parsed;
  2514. }
  2515. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  2516. }
  2517. getMaxOverflow() {
  2518. const meta = this._cachedMeta;
  2519. const data = meta.data || [];
  2520. if (!this.options.showLine) {
  2521. let max = 0;
  2522. for(let i = data.length - 1; i >= 0; --i){
  2523. max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
  2524. }
  2525. return max > 0 && max;
  2526. }
  2527. const dataset = meta.dataset;
  2528. const border = dataset.options && dataset.options.borderWidth || 0;
  2529. if (!data.length) {
  2530. return border;
  2531. }
  2532. const firstPoint = data[0].size(this.resolveDataElementOptions(0));
  2533. const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
  2534. return Math.max(border, firstPoint, lastPoint) / 2;
  2535. }
  2536. }
  2537. var controllers = /*#__PURE__*/Object.freeze({
  2538. __proto__: null,
  2539. BarController: BarController,
  2540. BubbleController: BubbleController,
  2541. DoughnutController: DoughnutController,
  2542. LineController: LineController,
  2543. PieController: PieController,
  2544. PolarAreaController: PolarAreaController,
  2545. RadarController: RadarController,
  2546. ScatterController: ScatterController
  2547. });
  2548. /**
  2549. * @namespace Chart._adapters
  2550. * @since 2.8.0
  2551. * @private
  2552. */ function abstract() {
  2553. throw new Error('This method is not implemented: Check that a complete date adapter is provided.');
  2554. }
  2555. /**
  2556. * Date adapter (current used by the time scale)
  2557. * @namespace Chart._adapters._date
  2558. * @memberof Chart._adapters
  2559. * @private
  2560. */ class DateAdapterBase {
  2561. /**
  2562. * Override default date adapter methods.
  2563. * Accepts type parameter to define options type.
  2564. * @example
  2565. * Chart._adapters._date.override<{myAdapterOption: string}>({
  2566. * init() {
  2567. * console.log(this.options.myAdapterOption);
  2568. * }
  2569. * })
  2570. */ static override(members) {
  2571. Object.assign(DateAdapterBase.prototype, members);
  2572. }
  2573. options;
  2574. constructor(options){
  2575. this.options = options || {};
  2576. }
  2577. // eslint-disable-next-line @typescript-eslint/no-empty-function
  2578. init() {}
  2579. formats() {
  2580. return abstract();
  2581. }
  2582. parse() {
  2583. return abstract();
  2584. }
  2585. format() {
  2586. return abstract();
  2587. }
  2588. add() {
  2589. return abstract();
  2590. }
  2591. diff() {
  2592. return abstract();
  2593. }
  2594. startOf() {
  2595. return abstract();
  2596. }
  2597. endOf() {
  2598. return abstract();
  2599. }
  2600. }
  2601. var adapters = {
  2602. _date: DateAdapterBase
  2603. };
  2604. function binarySearch(metaset, axis, value, intersect) {
  2605. const { controller , data , _sorted } = metaset;
  2606. const iScale = controller._cachedMeta.iScale;
  2607. if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {
  2608. const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;
  2609. if (!intersect) {
  2610. return lookupMethod(data, axis, value);
  2611. } else if (controller._sharedOptions) {
  2612. const el = data[0];
  2613. const range = typeof el.getRange === 'function' && el.getRange(axis);
  2614. if (range) {
  2615. const start = lookupMethod(data, axis, value - range);
  2616. const end = lookupMethod(data, axis, value + range);
  2617. return {
  2618. lo: start.lo,
  2619. hi: end.hi
  2620. };
  2621. }
  2622. }
  2623. }
  2624. return {
  2625. lo: 0,
  2626. hi: data.length - 1
  2627. };
  2628. }
  2629. function evaluateInteractionItems(chart, axis, position, handler, intersect) {
  2630. const metasets = chart.getSortedVisibleDatasetMetas();
  2631. const value = position[axis];
  2632. for(let i = 0, ilen = metasets.length; i < ilen; ++i){
  2633. const { index , data } = metasets[i];
  2634. const { lo , hi } = binarySearch(metasets[i], axis, value, intersect);
  2635. for(let j = lo; j <= hi; ++j){
  2636. const element = data[j];
  2637. if (!element.skip) {
  2638. handler(element, index, j);
  2639. }
  2640. }
  2641. }
  2642. }
  2643. function getDistanceMetricForAxis(axis) {
  2644. const useX = axis.indexOf('x') !== -1;
  2645. const useY = axis.indexOf('y') !== -1;
  2646. return function(pt1, pt2) {
  2647. const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  2648. const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  2649. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  2650. };
  2651. }
  2652. function getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {
  2653. const items = [];
  2654. if (!includeInvisible && !chart.isPointInArea(position)) {
  2655. return items;
  2656. }
  2657. const evaluationFunc = function(element, datasetIndex, index) {
  2658. if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) {
  2659. return;
  2660. }
  2661. if (element.inRange(position.x, position.y, useFinalPosition)) {
  2662. items.push({
  2663. element,
  2664. datasetIndex,
  2665. index
  2666. });
  2667. }
  2668. };
  2669. evaluateInteractionItems(chart, axis, position, evaluationFunc, true);
  2670. return items;
  2671. }
  2672. function getNearestRadialItems(chart, position, axis, useFinalPosition) {
  2673. let items = [];
  2674. function evaluationFunc(element, datasetIndex, index) {
  2675. const { startAngle , endAngle } = element.getProps([
  2676. 'startAngle',
  2677. 'endAngle'
  2678. ], useFinalPosition);
  2679. const { angle } = getAngleFromPoint(element, {
  2680. x: position.x,
  2681. y: position.y
  2682. });
  2683. if (_angleBetween(angle, startAngle, endAngle)) {
  2684. items.push({
  2685. element,
  2686. datasetIndex,
  2687. index
  2688. });
  2689. }
  2690. }
  2691. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2692. return items;
  2693. }
  2694. function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
  2695. let items = [];
  2696. const distanceMetric = getDistanceMetricForAxis(axis);
  2697. let minDistance = Number.POSITIVE_INFINITY;
  2698. function evaluationFunc(element, datasetIndex, index) {
  2699. const inRange = element.inRange(position.x, position.y, useFinalPosition);
  2700. if (intersect && !inRange) {
  2701. return;
  2702. }
  2703. const center = element.getCenterPoint(useFinalPosition);
  2704. const pointInArea = !!includeInvisible || chart.isPointInArea(center);
  2705. if (!pointInArea && !inRange) {
  2706. return;
  2707. }
  2708. const distance = distanceMetric(position, center);
  2709. if (distance < minDistance) {
  2710. items = [
  2711. {
  2712. element,
  2713. datasetIndex,
  2714. index
  2715. }
  2716. ];
  2717. minDistance = distance;
  2718. } else if (distance === minDistance) {
  2719. items.push({
  2720. element,
  2721. datasetIndex,
  2722. index
  2723. });
  2724. }
  2725. }
  2726. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2727. return items;
  2728. }
  2729. function getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
  2730. if (!includeInvisible && !chart.isPointInArea(position)) {
  2731. return [];
  2732. }
  2733. return axis === 'r' && !intersect ? getNearestRadialItems(chart, position, axis, useFinalPosition) : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);
  2734. }
  2735. function getAxisItems(chart, position, axis, intersect, useFinalPosition) {
  2736. const items = [];
  2737. const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
  2738. let intersectsItem = false;
  2739. evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index)=>{
  2740. if (element[rangeMethod](position[axis], useFinalPosition)) {
  2741. items.push({
  2742. element,
  2743. datasetIndex,
  2744. index
  2745. });
  2746. intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);
  2747. }
  2748. });
  2749. if (intersect && !intersectsItem) {
  2750. return [];
  2751. }
  2752. return items;
  2753. }
  2754. var Interaction = {
  2755. evaluateInteractionItems,
  2756. modes: {
  2757. index (chart, e, options, useFinalPosition) {
  2758. const position = getRelativePosition(e, chart);
  2759. const axis = options.axis || 'x';
  2760. const includeInvisible = options.includeInvisible || false;
  2761. const items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
  2762. const elements = [];
  2763. if (!items.length) {
  2764. return [];
  2765. }
  2766. chart.getSortedVisibleDatasetMetas().forEach((meta)=>{
  2767. const index = items[0].index;
  2768. const element = meta.data[index];
  2769. if (element && !element.skip) {
  2770. elements.push({
  2771. element,
  2772. datasetIndex: meta.index,
  2773. index
  2774. });
  2775. }
  2776. });
  2777. return elements;
  2778. },
  2779. dataset (chart, e, options, useFinalPosition) {
  2780. const position = getRelativePosition(e, chart);
  2781. const axis = options.axis || 'xy';
  2782. const includeInvisible = options.includeInvisible || false;
  2783. let items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
  2784. if (items.length > 0) {
  2785. const datasetIndex = items[0].datasetIndex;
  2786. const data = chart.getDatasetMeta(datasetIndex).data;
  2787. items = [];
  2788. for(let i = 0; i < data.length; ++i){
  2789. items.push({
  2790. element: data[i],
  2791. datasetIndex,
  2792. index: i
  2793. });
  2794. }
  2795. }
  2796. return items;
  2797. },
  2798. point (chart, e, options, useFinalPosition) {
  2799. const position = getRelativePosition(e, chart);
  2800. const axis = options.axis || 'xy';
  2801. const includeInvisible = options.includeInvisible || false;
  2802. return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);
  2803. },
  2804. nearest (chart, e, options, useFinalPosition) {
  2805. const position = getRelativePosition(e, chart);
  2806. const axis = options.axis || 'xy';
  2807. const includeInvisible = options.includeInvisible || false;
  2808. return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);
  2809. },
  2810. x (chart, e, options, useFinalPosition) {
  2811. const position = getRelativePosition(e, chart);
  2812. return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);
  2813. },
  2814. y (chart, e, options, useFinalPosition) {
  2815. const position = getRelativePosition(e, chart);
  2816. return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);
  2817. }
  2818. }
  2819. };
  2820. const STATIC_POSITIONS = [
  2821. 'left',
  2822. 'top',
  2823. 'right',
  2824. 'bottom'
  2825. ];
  2826. function filterByPosition(array, position) {
  2827. return array.filter((v)=>v.pos === position);
  2828. }
  2829. function filterDynamicPositionByAxis(array, axis) {
  2830. return array.filter((v)=>STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);
  2831. }
  2832. function sortByWeight(array, reverse) {
  2833. return array.sort((a, b)=>{
  2834. const v0 = reverse ? b : a;
  2835. const v1 = reverse ? a : b;
  2836. return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight;
  2837. });
  2838. }
  2839. function wrapBoxes(boxes) {
  2840. const layoutBoxes = [];
  2841. let i, ilen, box, pos, stack, stackWeight;
  2842. for(i = 0, ilen = (boxes || []).length; i < ilen; ++i){
  2843. box = boxes[i];
  2844. ({ position: pos , options: { stack , stackWeight =1 } } = box);
  2845. layoutBoxes.push({
  2846. index: i,
  2847. box,
  2848. pos,
  2849. horizontal: box.isHorizontal(),
  2850. weight: box.weight,
  2851. stack: stack && pos + stack,
  2852. stackWeight
  2853. });
  2854. }
  2855. return layoutBoxes;
  2856. }
  2857. function buildStacks(layouts) {
  2858. const stacks = {};
  2859. for (const wrap of layouts){
  2860. const { stack , pos , stackWeight } = wrap;
  2861. if (!stack || !STATIC_POSITIONS.includes(pos)) {
  2862. continue;
  2863. }
  2864. const _stack = stacks[stack] || (stacks[stack] = {
  2865. count: 0,
  2866. placed: 0,
  2867. weight: 0,
  2868. size: 0
  2869. });
  2870. _stack.count++;
  2871. _stack.weight += stackWeight;
  2872. }
  2873. return stacks;
  2874. }
  2875. function setLayoutDims(layouts, params) {
  2876. const stacks = buildStacks(layouts);
  2877. const { vBoxMaxWidth , hBoxMaxHeight } = params;
  2878. let i, ilen, layout;
  2879. for(i = 0, ilen = layouts.length; i < ilen; ++i){
  2880. layout = layouts[i];
  2881. const { fullSize } = layout.box;
  2882. const stack = stacks[layout.stack];
  2883. const factor = stack && layout.stackWeight / stack.weight;
  2884. if (layout.horizontal) {
  2885. layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;
  2886. layout.height = hBoxMaxHeight;
  2887. } else {
  2888. layout.width = vBoxMaxWidth;
  2889. layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;
  2890. }
  2891. }
  2892. return stacks;
  2893. }
  2894. function buildLayoutBoxes(boxes) {
  2895. const layoutBoxes = wrapBoxes(boxes);
  2896. const fullSize = sortByWeight(layoutBoxes.filter((wrap)=>wrap.box.fullSize), true);
  2897. const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  2898. const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  2899. const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  2900. const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  2901. const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
  2902. const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
  2903. return {
  2904. fullSize,
  2905. leftAndTop: left.concat(top),
  2906. rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
  2907. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  2908. vertical: left.concat(right).concat(centerVertical),
  2909. horizontal: top.concat(bottom).concat(centerHorizontal)
  2910. };
  2911. }
  2912. function getCombinedMax(maxPadding, chartArea, a, b) {
  2913. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  2914. }
  2915. function updateMaxPadding(maxPadding, boxPadding) {
  2916. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  2917. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  2918. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  2919. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  2920. }
  2921. function updateDims(chartArea, params, layout, stacks) {
  2922. const { pos , box } = layout;
  2923. const maxPadding = chartArea.maxPadding;
  2924. if (!isObject(pos)) {
  2925. if (layout.size) {
  2926. chartArea[pos] -= layout.size;
  2927. }
  2928. const stack = stacks[layout.stack] || {
  2929. size: 0,
  2930. count: 1
  2931. };
  2932. stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);
  2933. layout.size = stack.size / stack.count;
  2934. chartArea[pos] += layout.size;
  2935. }
  2936. if (box.getPadding) {
  2937. updateMaxPadding(maxPadding, box.getPadding());
  2938. }
  2939. const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
  2940. const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
  2941. const widthChanged = newWidth !== chartArea.w;
  2942. const heightChanged = newHeight !== chartArea.h;
  2943. chartArea.w = newWidth;
  2944. chartArea.h = newHeight;
  2945. return layout.horizontal ? {
  2946. same: widthChanged,
  2947. other: heightChanged
  2948. } : {
  2949. same: heightChanged,
  2950. other: widthChanged
  2951. };
  2952. }
  2953. function handleMaxPadding(chartArea) {
  2954. const maxPadding = chartArea.maxPadding;
  2955. function updatePos(pos) {
  2956. const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  2957. chartArea[pos] += change;
  2958. return change;
  2959. }
  2960. chartArea.y += updatePos('top');
  2961. chartArea.x += updatePos('left');
  2962. updatePos('right');
  2963. updatePos('bottom');
  2964. }
  2965. function getMargins(horizontal, chartArea) {
  2966. const maxPadding = chartArea.maxPadding;
  2967. function marginForPositions(positions) {
  2968. const margin = {
  2969. left: 0,
  2970. top: 0,
  2971. right: 0,
  2972. bottom: 0
  2973. };
  2974. positions.forEach((pos)=>{
  2975. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  2976. });
  2977. return margin;
  2978. }
  2979. return horizontal ? marginForPositions([
  2980. 'left',
  2981. 'right'
  2982. ]) : marginForPositions([
  2983. 'top',
  2984. 'bottom'
  2985. ]);
  2986. }
  2987. function fitBoxes(boxes, chartArea, params, stacks) {
  2988. const refitBoxes = [];
  2989. let i, ilen, layout, box, refit, changed;
  2990. for(i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i){
  2991. layout = boxes[i];
  2992. box = layout.box;
  2993. box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea));
  2994. const { same , other } = updateDims(chartArea, params, layout, stacks);
  2995. refit |= same && refitBoxes.length;
  2996. changed = changed || other;
  2997. if (!box.fullSize) {
  2998. refitBoxes.push(layout);
  2999. }
  3000. }
  3001. return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;
  3002. }
  3003. function setBoxDims(box, left, top, width, height) {
  3004. box.top = top;
  3005. box.left = left;
  3006. box.right = left + width;
  3007. box.bottom = top + height;
  3008. box.width = width;
  3009. box.height = height;
  3010. }
  3011. function placeBoxes(boxes, chartArea, params, stacks) {
  3012. const userPadding = params.padding;
  3013. let { x , y } = chartArea;
  3014. for (const layout of boxes){
  3015. const box = layout.box;
  3016. const stack = stacks[layout.stack] || {
  3017. count: 1,
  3018. placed: 0,
  3019. weight: 1
  3020. };
  3021. const weight = layout.stackWeight / stack.weight || 1;
  3022. if (layout.horizontal) {
  3023. const width = chartArea.w * weight;
  3024. const height = stack.size || box.height;
  3025. if (defined(stack.start)) {
  3026. y = stack.start;
  3027. }
  3028. if (box.fullSize) {
  3029. setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);
  3030. } else {
  3031. setBoxDims(box, chartArea.left + stack.placed, y, width, height);
  3032. }
  3033. stack.start = y;
  3034. stack.placed += width;
  3035. y = box.bottom;
  3036. } else {
  3037. const height = chartArea.h * weight;
  3038. const width = stack.size || box.width;
  3039. if (defined(stack.start)) {
  3040. x = stack.start;
  3041. }
  3042. if (box.fullSize) {
  3043. setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);
  3044. } else {
  3045. setBoxDims(box, x, chartArea.top + stack.placed, width, height);
  3046. }
  3047. stack.start = x;
  3048. stack.placed += height;
  3049. x = box.right;
  3050. }
  3051. }
  3052. chartArea.x = x;
  3053. chartArea.y = y;
  3054. }
  3055. var layouts = {
  3056. addBox (chart, item) {
  3057. if (!chart.boxes) {
  3058. chart.boxes = [];
  3059. }
  3060. item.fullSize = item.fullSize || false;
  3061. item.position = item.position || 'top';
  3062. item.weight = item.weight || 0;
  3063. item._layers = item._layers || function() {
  3064. return [
  3065. {
  3066. z: 0,
  3067. draw (chartArea) {
  3068. item.draw(chartArea);
  3069. }
  3070. }
  3071. ];
  3072. };
  3073. chart.boxes.push(item);
  3074. },
  3075. removeBox (chart, layoutItem) {
  3076. const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  3077. if (index !== -1) {
  3078. chart.boxes.splice(index, 1);
  3079. }
  3080. },
  3081. configure (chart, item, options) {
  3082. item.fullSize = options.fullSize;
  3083. item.position = options.position;
  3084. item.weight = options.weight;
  3085. },
  3086. update (chart, width, height, minPadding) {
  3087. if (!chart) {
  3088. return;
  3089. }
  3090. const padding = toPadding(chart.options.layout.padding);
  3091. const availableWidth = Math.max(width - padding.width, 0);
  3092. const availableHeight = Math.max(height - padding.height, 0);
  3093. const boxes = buildLayoutBoxes(chart.boxes);
  3094. const verticalBoxes = boxes.vertical;
  3095. const horizontalBoxes = boxes.horizontal;
  3096. each(chart.boxes, (box)=>{
  3097. if (typeof box.beforeLayout === 'function') {
  3098. box.beforeLayout();
  3099. }
  3100. });
  3101. const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap)=>wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
  3102. const params = Object.freeze({
  3103. outerWidth: width,
  3104. outerHeight: height,
  3105. padding,
  3106. availableWidth,
  3107. availableHeight,
  3108. vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
  3109. hBoxMaxHeight: availableHeight / 2
  3110. });
  3111. const maxPadding = Object.assign({}, padding);
  3112. updateMaxPadding(maxPadding, toPadding(minPadding));
  3113. const chartArea = Object.assign({
  3114. maxPadding,
  3115. w: availableWidth,
  3116. h: availableHeight,
  3117. x: padding.left,
  3118. y: padding.top
  3119. }, padding);
  3120. const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  3121. fitBoxes(boxes.fullSize, chartArea, params, stacks);
  3122. fitBoxes(verticalBoxes, chartArea, params, stacks);
  3123. if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {
  3124. fitBoxes(verticalBoxes, chartArea, params, stacks);
  3125. }
  3126. handleMaxPadding(chartArea);
  3127. placeBoxes(boxes.leftAndTop, chartArea, params, stacks);
  3128. chartArea.x += chartArea.w;
  3129. chartArea.y += chartArea.h;
  3130. placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);
  3131. chart.chartArea = {
  3132. left: chartArea.left,
  3133. top: chartArea.top,
  3134. right: chartArea.left + chartArea.w,
  3135. bottom: chartArea.top + chartArea.h,
  3136. height: chartArea.h,
  3137. width: chartArea.w
  3138. };
  3139. each(boxes.chartArea, (layout)=>{
  3140. const box = layout.box;
  3141. Object.assign(box, chart.chartArea);
  3142. box.update(chartArea.w, chartArea.h, {
  3143. left: 0,
  3144. top: 0,
  3145. right: 0,
  3146. bottom: 0
  3147. });
  3148. });
  3149. }
  3150. };
  3151. class BasePlatform {
  3152. acquireContext(canvas, aspectRatio) {}
  3153. releaseContext(context) {
  3154. return false;
  3155. }
  3156. addEventListener(chart, type, listener) {}
  3157. removeEventListener(chart, type, listener) {}
  3158. getDevicePixelRatio() {
  3159. return 1;
  3160. }
  3161. getMaximumSize(element, width, height, aspectRatio) {
  3162. width = Math.max(0, width || element.width);
  3163. height = height || element.height;
  3164. return {
  3165. width,
  3166. height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
  3167. };
  3168. }
  3169. isAttached(canvas) {
  3170. return true;
  3171. }
  3172. updateConfig(config) {
  3173. }
  3174. }
  3175. class BasicPlatform extends BasePlatform {
  3176. acquireContext(item) {
  3177. return item && item.getContext && item.getContext('2d') || null;
  3178. }
  3179. updateConfig(config) {
  3180. config.options.animation = false;
  3181. }
  3182. }
  3183. const EXPANDO_KEY = '$chartjs';
  3184. const EVENT_TYPES = {
  3185. touchstart: 'mousedown',
  3186. touchmove: 'mousemove',
  3187. touchend: 'mouseup',
  3188. pointerenter: 'mouseenter',
  3189. pointerdown: 'mousedown',
  3190. pointermove: 'mousemove',
  3191. pointerup: 'mouseup',
  3192. pointerleave: 'mouseout',
  3193. pointerout: 'mouseout'
  3194. };
  3195. const isNullOrEmpty = (value)=>value === null || value === '';
  3196. function initCanvas(canvas, aspectRatio) {
  3197. const style = canvas.style;
  3198. const renderHeight = canvas.getAttribute('height');
  3199. const renderWidth = canvas.getAttribute('width');
  3200. canvas[EXPANDO_KEY] = {
  3201. initial: {
  3202. height: renderHeight,
  3203. width: renderWidth,
  3204. style: {
  3205. display: style.display,
  3206. height: style.height,
  3207. width: style.width
  3208. }
  3209. }
  3210. };
  3211. style.display = style.display || 'block';
  3212. style.boxSizing = style.boxSizing || 'border-box';
  3213. if (isNullOrEmpty(renderWidth)) {
  3214. const displayWidth = readUsedSize(canvas, 'width');
  3215. if (displayWidth !== undefined) {
  3216. canvas.width = displayWidth;
  3217. }
  3218. }
  3219. if (isNullOrEmpty(renderHeight)) {
  3220. if (canvas.style.height === '') {
  3221. canvas.height = canvas.width / (aspectRatio || 2);
  3222. } else {
  3223. const displayHeight = readUsedSize(canvas, 'height');
  3224. if (displayHeight !== undefined) {
  3225. canvas.height = displayHeight;
  3226. }
  3227. }
  3228. }
  3229. return canvas;
  3230. }
  3231. const eventListenerOptions = supportsEventListenerOptions ? {
  3232. passive: true
  3233. } : false;
  3234. function addListener(node, type, listener) {
  3235. if (node) {
  3236. node.addEventListener(type, listener, eventListenerOptions);
  3237. }
  3238. }
  3239. function removeListener(chart, type, listener) {
  3240. if (chart && chart.canvas) {
  3241. chart.canvas.removeEventListener(type, listener, eventListenerOptions);
  3242. }
  3243. }
  3244. function fromNativeEvent(event, chart) {
  3245. const type = EVENT_TYPES[event.type] || event.type;
  3246. const { x , y } = getRelativePosition(event, chart);
  3247. return {
  3248. type,
  3249. chart,
  3250. native: event,
  3251. x: x !== undefined ? x : null,
  3252. y: y !== undefined ? y : null
  3253. };
  3254. }
  3255. function nodeListContains(nodeList, canvas) {
  3256. for (const node of nodeList){
  3257. if (node === canvas || node.contains(canvas)) {
  3258. return true;
  3259. }
  3260. }
  3261. }
  3262. function createAttachObserver(chart, type, listener) {
  3263. const canvas = chart.canvas;
  3264. const observer = new MutationObserver((entries)=>{
  3265. let trigger = false;
  3266. for (const entry of entries){
  3267. trigger = trigger || nodeListContains(entry.addedNodes, canvas);
  3268. trigger = trigger && !nodeListContains(entry.removedNodes, canvas);
  3269. }
  3270. if (trigger) {
  3271. listener();
  3272. }
  3273. });
  3274. observer.observe(document, {
  3275. childList: true,
  3276. subtree: true
  3277. });
  3278. return observer;
  3279. }
  3280. function createDetachObserver(chart, type, listener) {
  3281. const canvas = chart.canvas;
  3282. const observer = new MutationObserver((entries)=>{
  3283. let trigger = false;
  3284. for (const entry of entries){
  3285. trigger = trigger || nodeListContains(entry.removedNodes, canvas);
  3286. trigger = trigger && !nodeListContains(entry.addedNodes, canvas);
  3287. }
  3288. if (trigger) {
  3289. listener();
  3290. }
  3291. });
  3292. observer.observe(document, {
  3293. childList: true,
  3294. subtree: true
  3295. });
  3296. return observer;
  3297. }
  3298. const drpListeningCharts = new Map();
  3299. let oldDevicePixelRatio = 0;
  3300. function onWindowResize() {
  3301. const dpr = window.devicePixelRatio;
  3302. if (dpr === oldDevicePixelRatio) {
  3303. return;
  3304. }
  3305. oldDevicePixelRatio = dpr;
  3306. drpListeningCharts.forEach((resize, chart)=>{
  3307. if (chart.currentDevicePixelRatio !== dpr) {
  3308. resize();
  3309. }
  3310. });
  3311. }
  3312. function listenDevicePixelRatioChanges(chart, resize) {
  3313. if (!drpListeningCharts.size) {
  3314. window.addEventListener('resize', onWindowResize);
  3315. }
  3316. drpListeningCharts.set(chart, resize);
  3317. }
  3318. function unlistenDevicePixelRatioChanges(chart) {
  3319. drpListeningCharts.delete(chart);
  3320. if (!drpListeningCharts.size) {
  3321. window.removeEventListener('resize', onWindowResize);
  3322. }
  3323. }
  3324. function createResizeObserver(chart, type, listener) {
  3325. const canvas = chart.canvas;
  3326. const container = canvas && _getParentNode(canvas);
  3327. if (!container) {
  3328. return;
  3329. }
  3330. const resize = throttled((width, height)=>{
  3331. const w = container.clientWidth;
  3332. listener(width, height);
  3333. if (w < container.clientWidth) {
  3334. listener();
  3335. }
  3336. }, window);
  3337. const observer = new ResizeObserver((entries)=>{
  3338. const entry = entries[0];
  3339. const width = entry.contentRect.width;
  3340. const height = entry.contentRect.height;
  3341. if (width === 0 && height === 0) {
  3342. return;
  3343. }
  3344. resize(width, height);
  3345. });
  3346. observer.observe(container);
  3347. listenDevicePixelRatioChanges(chart, resize);
  3348. return observer;
  3349. }
  3350. function releaseObserver(chart, type, observer) {
  3351. if (observer) {
  3352. observer.disconnect();
  3353. }
  3354. if (type === 'resize') {
  3355. unlistenDevicePixelRatioChanges(chart);
  3356. }
  3357. }
  3358. function createProxyAndListen(chart, type, listener) {
  3359. const canvas = chart.canvas;
  3360. const proxy = throttled((event)=>{
  3361. if (chart.ctx !== null) {
  3362. listener(fromNativeEvent(event, chart));
  3363. }
  3364. }, chart);
  3365. addListener(canvas, type, proxy);
  3366. return proxy;
  3367. }
  3368. class DomPlatform extends BasePlatform {
  3369. acquireContext(canvas, aspectRatio) {
  3370. const context = canvas && canvas.getContext && canvas.getContext('2d');
  3371. if (context && context.canvas === canvas) {
  3372. initCanvas(canvas, aspectRatio);
  3373. return context;
  3374. }
  3375. return null;
  3376. }
  3377. releaseContext(context) {
  3378. const canvas = context.canvas;
  3379. if (!canvas[EXPANDO_KEY]) {
  3380. return false;
  3381. }
  3382. const initial = canvas[EXPANDO_KEY].initial;
  3383. [
  3384. 'height',
  3385. 'width'
  3386. ].forEach((prop)=>{
  3387. const value = initial[prop];
  3388. if (isNullOrUndef(value)) {
  3389. canvas.removeAttribute(prop);
  3390. } else {
  3391. canvas.setAttribute(prop, value);
  3392. }
  3393. });
  3394. const style = initial.style || {};
  3395. Object.keys(style).forEach((key)=>{
  3396. canvas.style[key] = style[key];
  3397. });
  3398. canvas.width = canvas.width;
  3399. delete canvas[EXPANDO_KEY];
  3400. return true;
  3401. }
  3402. addEventListener(chart, type, listener) {
  3403. this.removeEventListener(chart, type);
  3404. const proxies = chart.$proxies || (chart.$proxies = {});
  3405. const handlers = {
  3406. attach: createAttachObserver,
  3407. detach: createDetachObserver,
  3408. resize: createResizeObserver
  3409. };
  3410. const handler = handlers[type] || createProxyAndListen;
  3411. proxies[type] = handler(chart, type, listener);
  3412. }
  3413. removeEventListener(chart, type) {
  3414. const proxies = chart.$proxies || (chart.$proxies = {});
  3415. const proxy = proxies[type];
  3416. if (!proxy) {
  3417. return;
  3418. }
  3419. const handlers = {
  3420. attach: releaseObserver,
  3421. detach: releaseObserver,
  3422. resize: releaseObserver
  3423. };
  3424. const handler = handlers[type] || removeListener;
  3425. handler(chart, type, proxy);
  3426. proxies[type] = undefined;
  3427. }
  3428. getDevicePixelRatio() {
  3429. return window.devicePixelRatio;
  3430. }
  3431. getMaximumSize(canvas, width, height, aspectRatio) {
  3432. return getMaximumSize(canvas, width, height, aspectRatio);
  3433. }
  3434. isAttached(canvas) {
  3435. const container = _getParentNode(canvas);
  3436. return !!(container && container.isConnected);
  3437. }
  3438. }
  3439. function _detectPlatform(canvas) {
  3440. if (!_isDomSupported() || typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
  3441. return BasicPlatform;
  3442. }
  3443. return DomPlatform;
  3444. }
  3445. class Element {
  3446. static defaults = {};
  3447. static defaultRoutes = undefined;
  3448. x;
  3449. y;
  3450. active = false;
  3451. options;
  3452. $animations;
  3453. tooltipPosition(useFinalPosition) {
  3454. const { x , y } = this.getProps([
  3455. 'x',
  3456. 'y'
  3457. ], useFinalPosition);
  3458. return {
  3459. x,
  3460. y
  3461. };
  3462. }
  3463. hasValue() {
  3464. return isNumber(this.x) && isNumber(this.y);
  3465. }
  3466. getProps(props, final) {
  3467. const anims = this.$animations;
  3468. if (!final || !anims) {
  3469. // let's not create an object, if not needed
  3470. return this;
  3471. }
  3472. const ret = {};
  3473. props.forEach((prop)=>{
  3474. ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop];
  3475. });
  3476. return ret;
  3477. }
  3478. }
  3479. function autoSkip(scale, ticks) {
  3480. const tickOpts = scale.options.ticks;
  3481. const determinedMaxTicks = determineMaxTicks(scale);
  3482. const ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks);
  3483. const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  3484. const numMajorIndices = majorIndices.length;
  3485. const first = majorIndices[0];
  3486. const last = majorIndices[numMajorIndices - 1];
  3487. const newTicks = [];
  3488. if (numMajorIndices > ticksLimit) {
  3489. skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
  3490. return newTicks;
  3491. }
  3492. const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
  3493. if (numMajorIndices > 0) {
  3494. let i, ilen;
  3495. const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
  3496. skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  3497. for(i = 0, ilen = numMajorIndices - 1; i < ilen; i++){
  3498. skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
  3499. }
  3500. skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  3501. return newTicks;
  3502. }
  3503. skip(ticks, newTicks, spacing);
  3504. return newTicks;
  3505. }
  3506. function determineMaxTicks(scale) {
  3507. const offset = scale.options.offset;
  3508. const tickLength = scale._tickSize();
  3509. const maxScale = scale._length / tickLength + (offset ? 0 : 1);
  3510. const maxChart = scale._maxLength / tickLength;
  3511. return Math.floor(Math.min(maxScale, maxChart));
  3512. }
  3513. function calculateSpacing(majorIndices, ticks, ticksLimit) {
  3514. const evenMajorSpacing = getEvenSpacing(majorIndices);
  3515. const spacing = ticks.length / ticksLimit;
  3516. if (!evenMajorSpacing) {
  3517. return Math.max(spacing, 1);
  3518. }
  3519. const factors = _factorize(evenMajorSpacing);
  3520. for(let i = 0, ilen = factors.length - 1; i < ilen; i++){
  3521. const factor = factors[i];
  3522. if (factor > spacing) {
  3523. return factor;
  3524. }
  3525. }
  3526. return Math.max(spacing, 1);
  3527. }
  3528. function getMajorIndices(ticks) {
  3529. const result = [];
  3530. let i, ilen;
  3531. for(i = 0, ilen = ticks.length; i < ilen; i++){
  3532. if (ticks[i].major) {
  3533. result.push(i);
  3534. }
  3535. }
  3536. return result;
  3537. }
  3538. function skipMajors(ticks, newTicks, majorIndices, spacing) {
  3539. let count = 0;
  3540. let next = majorIndices[0];
  3541. let i;
  3542. spacing = Math.ceil(spacing);
  3543. for(i = 0; i < ticks.length; i++){
  3544. if (i === next) {
  3545. newTicks.push(ticks[i]);
  3546. count++;
  3547. next = majorIndices[count * spacing];
  3548. }
  3549. }
  3550. }
  3551. function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
  3552. const start = valueOrDefault(majorStart, 0);
  3553. const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
  3554. let count = 0;
  3555. let length, i, next;
  3556. spacing = Math.ceil(spacing);
  3557. if (majorEnd) {
  3558. length = majorEnd - majorStart;
  3559. spacing = length / Math.floor(length / spacing);
  3560. }
  3561. next = start;
  3562. while(next < 0){
  3563. count++;
  3564. next = Math.round(start + count * spacing);
  3565. }
  3566. for(i = Math.max(start, 0); i < end; i++){
  3567. if (i === next) {
  3568. newTicks.push(ticks[i]);
  3569. count++;
  3570. next = Math.round(start + count * spacing);
  3571. }
  3572. }
  3573. }
  3574. function getEvenSpacing(arr) {
  3575. const len = arr.length;
  3576. let i, diff;
  3577. if (len < 2) {
  3578. return false;
  3579. }
  3580. for(diff = arr[0], i = 1; i < len; ++i){
  3581. if (arr[i] - arr[i - 1] !== diff) {
  3582. return false;
  3583. }
  3584. }
  3585. return diff;
  3586. }
  3587. const reverseAlign = (align)=>align === 'left' ? 'right' : align === 'right' ? 'left' : align;
  3588. const offsetFromEdge = (scale, edge, offset)=>edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
  3589. const getTicksLimit = (ticksLength, maxTicksLimit)=>Math.min(maxTicksLimit || ticksLength, ticksLength);
  3590. function sample(arr, numItems) {
  3591. const result = [];
  3592. const increment = arr.length / numItems;
  3593. const len = arr.length;
  3594. let i = 0;
  3595. for(; i < len; i += increment){
  3596. result.push(arr[Math.floor(i)]);
  3597. }
  3598. return result;
  3599. }
  3600. function getPixelForGridLine(scale, index, offsetGridLines) {
  3601. const length = scale.ticks.length;
  3602. const validIndex = Math.min(index, length - 1);
  3603. const start = scale._startPixel;
  3604. const end = scale._endPixel;
  3605. const epsilon = 1e-6;
  3606. let lineValue = scale.getPixelForTick(validIndex);
  3607. let offset;
  3608. if (offsetGridLines) {
  3609. if (length === 1) {
  3610. offset = Math.max(lineValue - start, end - lineValue);
  3611. } else if (index === 0) {
  3612. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  3613. } else {
  3614. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  3615. }
  3616. lineValue += validIndex < index ? offset : -offset;
  3617. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  3618. return;
  3619. }
  3620. }
  3621. return lineValue;
  3622. }
  3623. function garbageCollect(caches, length) {
  3624. each(caches, (cache)=>{
  3625. const gc = cache.gc;
  3626. const gcLen = gc.length / 2;
  3627. let i;
  3628. if (gcLen > length) {
  3629. for(i = 0; i < gcLen; ++i){
  3630. delete cache.data[gc[i]];
  3631. }
  3632. gc.splice(0, gcLen);
  3633. }
  3634. });
  3635. }
  3636. function getTickMarkLength(options) {
  3637. return options.drawTicks ? options.tickLength : 0;
  3638. }
  3639. function getTitleHeight(options, fallback) {
  3640. if (!options.display) {
  3641. return 0;
  3642. }
  3643. const font = toFont(options.font, fallback);
  3644. const padding = toPadding(options.padding);
  3645. const lines = isArray(options.text) ? options.text.length : 1;
  3646. return lines * font.lineHeight + padding.height;
  3647. }
  3648. function createScaleContext(parent, scale) {
  3649. return createContext(parent, {
  3650. scale,
  3651. type: 'scale'
  3652. });
  3653. }
  3654. function createTickContext(parent, index, tick) {
  3655. return createContext(parent, {
  3656. tick,
  3657. index,
  3658. type: 'tick'
  3659. });
  3660. }
  3661. function titleAlign(align, position, reverse) {
  3662. let ret = _toLeftRightCenter(align);
  3663. if (reverse && position !== 'right' || !reverse && position === 'right') {
  3664. ret = reverseAlign(ret);
  3665. }
  3666. return ret;
  3667. }
  3668. function titleArgs(scale, offset, position, align) {
  3669. const { top , left , bottom , right , chart } = scale;
  3670. const { chartArea , scales } = chart;
  3671. let rotation = 0;
  3672. let maxWidth, titleX, titleY;
  3673. const height = bottom - top;
  3674. const width = right - left;
  3675. if (scale.isHorizontal()) {
  3676. titleX = _alignStartEnd(align, left, right);
  3677. if (isObject(position)) {
  3678. const positionAxisID = Object.keys(position)[0];
  3679. const value = position[positionAxisID];
  3680. titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;
  3681. } else if (position === 'center') {
  3682. titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;
  3683. } else {
  3684. titleY = offsetFromEdge(scale, position, offset);
  3685. }
  3686. maxWidth = right - left;
  3687. } else {
  3688. if (isObject(position)) {
  3689. const positionAxisID = Object.keys(position)[0];
  3690. const value = position[positionAxisID];
  3691. titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;
  3692. } else if (position === 'center') {
  3693. titleX = (chartArea.left + chartArea.right) / 2 - width + offset;
  3694. } else {
  3695. titleX = offsetFromEdge(scale, position, offset);
  3696. }
  3697. titleY = _alignStartEnd(align, bottom, top);
  3698. rotation = position === 'left' ? -HALF_PI : HALF_PI;
  3699. }
  3700. return {
  3701. titleX,
  3702. titleY,
  3703. maxWidth,
  3704. rotation
  3705. };
  3706. }
  3707. class Scale extends Element {
  3708. constructor(cfg){
  3709. super();
  3710. this.id = cfg.id;
  3711. this.type = cfg.type;
  3712. this.options = undefined;
  3713. this.ctx = cfg.ctx;
  3714. this.chart = cfg.chart;
  3715. this.top = undefined;
  3716. this.bottom = undefined;
  3717. this.left = undefined;
  3718. this.right = undefined;
  3719. this.width = undefined;
  3720. this.height = undefined;
  3721. this._margins = {
  3722. left: 0,
  3723. right: 0,
  3724. top: 0,
  3725. bottom: 0
  3726. };
  3727. this.maxWidth = undefined;
  3728. this.maxHeight = undefined;
  3729. this.paddingTop = undefined;
  3730. this.paddingBottom = undefined;
  3731. this.paddingLeft = undefined;
  3732. this.paddingRight = undefined;
  3733. this.axis = undefined;
  3734. this.labelRotation = undefined;
  3735. this.min = undefined;
  3736. this.max = undefined;
  3737. this._range = undefined;
  3738. this.ticks = [];
  3739. this._gridLineItems = null;
  3740. this._labelItems = null;
  3741. this._labelSizes = null;
  3742. this._length = 0;
  3743. this._maxLength = 0;
  3744. this._longestTextCache = {};
  3745. this._startPixel = undefined;
  3746. this._endPixel = undefined;
  3747. this._reversePixels = false;
  3748. this._userMax = undefined;
  3749. this._userMin = undefined;
  3750. this._suggestedMax = undefined;
  3751. this._suggestedMin = undefined;
  3752. this._ticksLength = 0;
  3753. this._borderValue = 0;
  3754. this._cache = {};
  3755. this._dataLimitsCached = false;
  3756. this.$context = undefined;
  3757. }
  3758. init(options) {
  3759. this.options = options.setContext(this.getContext());
  3760. this.axis = options.axis;
  3761. this._userMin = this.parse(options.min);
  3762. this._userMax = this.parse(options.max);
  3763. this._suggestedMin = this.parse(options.suggestedMin);
  3764. this._suggestedMax = this.parse(options.suggestedMax);
  3765. }
  3766. parse(raw, index) {
  3767. return raw;
  3768. }
  3769. getUserBounds() {
  3770. let { _userMin , _userMax , _suggestedMin , _suggestedMax } = this;
  3771. _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
  3772. _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
  3773. _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
  3774. _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
  3775. return {
  3776. min: finiteOrDefault(_userMin, _suggestedMin),
  3777. max: finiteOrDefault(_userMax, _suggestedMax),
  3778. minDefined: isNumberFinite(_userMin),
  3779. maxDefined: isNumberFinite(_userMax)
  3780. };
  3781. }
  3782. getMinMax(canStack) {
  3783. let { min , max , minDefined , maxDefined } = this.getUserBounds();
  3784. let range;
  3785. if (minDefined && maxDefined) {
  3786. return {
  3787. min,
  3788. max
  3789. };
  3790. }
  3791. const metas = this.getMatchingVisibleMetas();
  3792. for(let i = 0, ilen = metas.length; i < ilen; ++i){
  3793. range = metas[i].controller.getMinMax(this, canStack);
  3794. if (!minDefined) {
  3795. min = Math.min(min, range.min);
  3796. }
  3797. if (!maxDefined) {
  3798. max = Math.max(max, range.max);
  3799. }
  3800. }
  3801. min = maxDefined && min > max ? max : min;
  3802. max = minDefined && min > max ? min : max;
  3803. return {
  3804. min: finiteOrDefault(min, finiteOrDefault(max, min)),
  3805. max: finiteOrDefault(max, finiteOrDefault(min, max))
  3806. };
  3807. }
  3808. getPadding() {
  3809. return {
  3810. left: this.paddingLeft || 0,
  3811. top: this.paddingTop || 0,
  3812. right: this.paddingRight || 0,
  3813. bottom: this.paddingBottom || 0
  3814. };
  3815. }
  3816. getTicks() {
  3817. return this.ticks;
  3818. }
  3819. getLabels() {
  3820. const data = this.chart.data;
  3821. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  3822. }
  3823. getLabelItems(chartArea = this.chart.chartArea) {
  3824. const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));
  3825. return items;
  3826. }
  3827. beforeLayout() {
  3828. this._cache = {};
  3829. this._dataLimitsCached = false;
  3830. }
  3831. beforeUpdate() {
  3832. callback(this.options.beforeUpdate, [
  3833. this
  3834. ]);
  3835. }
  3836. update(maxWidth, maxHeight, margins) {
  3837. const { beginAtZero , grace , ticks: tickOpts } = this.options;
  3838. const sampleSize = tickOpts.sampleSize;
  3839. this.beforeUpdate();
  3840. this.maxWidth = maxWidth;
  3841. this.maxHeight = maxHeight;
  3842. this._margins = margins = Object.assign({
  3843. left: 0,
  3844. right: 0,
  3845. top: 0,
  3846. bottom: 0
  3847. }, margins);
  3848. this.ticks = null;
  3849. this._labelSizes = null;
  3850. this._gridLineItems = null;
  3851. this._labelItems = null;
  3852. this.beforeSetDimensions();
  3853. this.setDimensions();
  3854. this.afterSetDimensions();
  3855. this._maxLength = this.isHorizontal() ? this.width + margins.left + margins.right : this.height + margins.top + margins.bottom;
  3856. if (!this._dataLimitsCached) {
  3857. this.beforeDataLimits();
  3858. this.determineDataLimits();
  3859. this.afterDataLimits();
  3860. this._range = _addGrace(this, grace, beginAtZero);
  3861. this._dataLimitsCached = true;
  3862. }
  3863. this.beforeBuildTicks();
  3864. this.ticks = this.buildTicks() || [];
  3865. this.afterBuildTicks();
  3866. const samplingEnabled = sampleSize < this.ticks.length;
  3867. this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);
  3868. this.configure();
  3869. this.beforeCalculateLabelRotation();
  3870. this.calculateLabelRotation();
  3871. this.afterCalculateLabelRotation();
  3872. if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
  3873. this.ticks = autoSkip(this, this.ticks);
  3874. this._labelSizes = null;
  3875. this.afterAutoSkip();
  3876. }
  3877. if (samplingEnabled) {
  3878. this._convertTicksToLabels(this.ticks);
  3879. }
  3880. this.beforeFit();
  3881. this.fit();
  3882. this.afterFit();
  3883. this.afterUpdate();
  3884. }
  3885. configure() {
  3886. let reversePixels = this.options.reverse;
  3887. let startPixel, endPixel;
  3888. if (this.isHorizontal()) {
  3889. startPixel = this.left;
  3890. endPixel = this.right;
  3891. } else {
  3892. startPixel = this.top;
  3893. endPixel = this.bottom;
  3894. reversePixels = !reversePixels;
  3895. }
  3896. this._startPixel = startPixel;
  3897. this._endPixel = endPixel;
  3898. this._reversePixels = reversePixels;
  3899. this._length = endPixel - startPixel;
  3900. this._alignToPixels = this.options.alignToPixels;
  3901. }
  3902. afterUpdate() {
  3903. callback(this.options.afterUpdate, [
  3904. this
  3905. ]);
  3906. }
  3907. beforeSetDimensions() {
  3908. callback(this.options.beforeSetDimensions, [
  3909. this
  3910. ]);
  3911. }
  3912. setDimensions() {
  3913. if (this.isHorizontal()) {
  3914. this.width = this.maxWidth;
  3915. this.left = 0;
  3916. this.right = this.width;
  3917. } else {
  3918. this.height = this.maxHeight;
  3919. this.top = 0;
  3920. this.bottom = this.height;
  3921. }
  3922. this.paddingLeft = 0;
  3923. this.paddingTop = 0;
  3924. this.paddingRight = 0;
  3925. this.paddingBottom = 0;
  3926. }
  3927. afterSetDimensions() {
  3928. callback(this.options.afterSetDimensions, [
  3929. this
  3930. ]);
  3931. }
  3932. _callHooks(name) {
  3933. this.chart.notifyPlugins(name, this.getContext());
  3934. callback(this.options[name], [
  3935. this
  3936. ]);
  3937. }
  3938. beforeDataLimits() {
  3939. this._callHooks('beforeDataLimits');
  3940. }
  3941. determineDataLimits() {}
  3942. afterDataLimits() {
  3943. this._callHooks('afterDataLimits');
  3944. }
  3945. beforeBuildTicks() {
  3946. this._callHooks('beforeBuildTicks');
  3947. }
  3948. buildTicks() {
  3949. return [];
  3950. }
  3951. afterBuildTicks() {
  3952. this._callHooks('afterBuildTicks');
  3953. }
  3954. beforeTickToLabelConversion() {
  3955. callback(this.options.beforeTickToLabelConversion, [
  3956. this
  3957. ]);
  3958. }
  3959. generateTickLabels(ticks) {
  3960. const tickOpts = this.options.ticks;
  3961. let i, ilen, tick;
  3962. for(i = 0, ilen = ticks.length; i < ilen; i++){
  3963. tick = ticks[i];
  3964. tick.label = callback(tickOpts.callback, [
  3965. tick.value,
  3966. i,
  3967. ticks
  3968. ], this);
  3969. }
  3970. }
  3971. afterTickToLabelConversion() {
  3972. callback(this.options.afterTickToLabelConversion, [
  3973. this
  3974. ]);
  3975. }
  3976. beforeCalculateLabelRotation() {
  3977. callback(this.options.beforeCalculateLabelRotation, [
  3978. this
  3979. ]);
  3980. }
  3981. calculateLabelRotation() {
  3982. const options = this.options;
  3983. const tickOpts = options.ticks;
  3984. const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit);
  3985. const minRotation = tickOpts.minRotation || 0;
  3986. const maxRotation = tickOpts.maxRotation;
  3987. let labelRotation = minRotation;
  3988. let tickWidth, maxHeight, maxLabelDiagonal;
  3989. if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {
  3990. this.labelRotation = minRotation;
  3991. return;
  3992. }
  3993. const labelSizes = this._getLabelSizes();
  3994. const maxLabelWidth = labelSizes.widest.width;
  3995. const maxLabelHeight = labelSizes.highest.height;
  3996. const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);
  3997. tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);
  3998. if (maxLabelWidth + 6 > tickWidth) {
  3999. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  4000. maxHeight = this.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);
  4001. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  4002. labelRotation = toDegrees(Math.min(Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))));
  4003. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  4004. }
  4005. this.labelRotation = labelRotation;
  4006. }
  4007. afterCalculateLabelRotation() {
  4008. callback(this.options.afterCalculateLabelRotation, [
  4009. this
  4010. ]);
  4011. }
  4012. afterAutoSkip() {}
  4013. beforeFit() {
  4014. callback(this.options.beforeFit, [
  4015. this
  4016. ]);
  4017. }
  4018. fit() {
  4019. const minSize = {
  4020. width: 0,
  4021. height: 0
  4022. };
  4023. const { chart , options: { ticks: tickOpts , title: titleOpts , grid: gridOpts } } = this;
  4024. const display = this._isVisible();
  4025. const isHorizontal = this.isHorizontal();
  4026. if (display) {
  4027. const titleHeight = getTitleHeight(titleOpts, chart.options.font);
  4028. if (isHorizontal) {
  4029. minSize.width = this.maxWidth;
  4030. minSize.height = getTickMarkLength(gridOpts) + titleHeight;
  4031. } else {
  4032. minSize.height = this.maxHeight;
  4033. minSize.width = getTickMarkLength(gridOpts) + titleHeight;
  4034. }
  4035. if (tickOpts.display && this.ticks.length) {
  4036. const { first , last , widest , highest } = this._getLabelSizes();
  4037. const tickPadding = tickOpts.padding * 2;
  4038. const angleRadians = toRadians(this.labelRotation);
  4039. const cos = Math.cos(angleRadians);
  4040. const sin = Math.sin(angleRadians);
  4041. if (isHorizontal) {
  4042. const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
  4043. minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);
  4044. } else {
  4045. const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
  4046. minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);
  4047. }
  4048. this._calculatePadding(first, last, sin, cos);
  4049. }
  4050. }
  4051. this._handleMargins();
  4052. if (isHorizontal) {
  4053. this.width = this._length = chart.width - this._margins.left - this._margins.right;
  4054. this.height = minSize.height;
  4055. } else {
  4056. this.width = minSize.width;
  4057. this.height = this._length = chart.height - this._margins.top - this._margins.bottom;
  4058. }
  4059. }
  4060. _calculatePadding(first, last, sin, cos) {
  4061. const { ticks: { align , padding } , position } = this.options;
  4062. const isRotated = this.labelRotation !== 0;
  4063. const labelsBelowTicks = position !== 'top' && this.axis === 'x';
  4064. if (this.isHorizontal()) {
  4065. const offsetLeft = this.getPixelForTick(0) - this.left;
  4066. const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);
  4067. let paddingLeft = 0;
  4068. let paddingRight = 0;
  4069. if (isRotated) {
  4070. if (labelsBelowTicks) {
  4071. paddingLeft = cos * first.width;
  4072. paddingRight = sin * last.height;
  4073. } else {
  4074. paddingLeft = sin * first.height;
  4075. paddingRight = cos * last.width;
  4076. }
  4077. } else if (align === 'start') {
  4078. paddingRight = last.width;
  4079. } else if (align === 'end') {
  4080. paddingLeft = first.width;
  4081. } else if (align !== 'inner') {
  4082. paddingLeft = first.width / 2;
  4083. paddingRight = last.width / 2;
  4084. }
  4085. this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);
  4086. this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);
  4087. } else {
  4088. let paddingTop = last.height / 2;
  4089. let paddingBottom = first.height / 2;
  4090. if (align === 'start') {
  4091. paddingTop = 0;
  4092. paddingBottom = first.height;
  4093. } else if (align === 'end') {
  4094. paddingTop = last.height;
  4095. paddingBottom = 0;
  4096. }
  4097. this.paddingTop = paddingTop + padding;
  4098. this.paddingBottom = paddingBottom + padding;
  4099. }
  4100. }
  4101. _handleMargins() {
  4102. if (this._margins) {
  4103. this._margins.left = Math.max(this.paddingLeft, this._margins.left);
  4104. this._margins.top = Math.max(this.paddingTop, this._margins.top);
  4105. this._margins.right = Math.max(this.paddingRight, this._margins.right);
  4106. this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);
  4107. }
  4108. }
  4109. afterFit() {
  4110. callback(this.options.afterFit, [
  4111. this
  4112. ]);
  4113. }
  4114. isHorizontal() {
  4115. const { axis , position } = this.options;
  4116. return position === 'top' || position === 'bottom' || axis === 'x';
  4117. }
  4118. isFullSize() {
  4119. return this.options.fullSize;
  4120. }
  4121. _convertTicksToLabels(ticks) {
  4122. this.beforeTickToLabelConversion();
  4123. this.generateTickLabels(ticks);
  4124. let i, ilen;
  4125. for(i = 0, ilen = ticks.length; i < ilen; i++){
  4126. if (isNullOrUndef(ticks[i].label)) {
  4127. ticks.splice(i, 1);
  4128. ilen--;
  4129. i--;
  4130. }
  4131. }
  4132. this.afterTickToLabelConversion();
  4133. }
  4134. _getLabelSizes() {
  4135. let labelSizes = this._labelSizes;
  4136. if (!labelSizes) {
  4137. const sampleSize = this.options.ticks.sampleSize;
  4138. let ticks = this.ticks;
  4139. if (sampleSize < ticks.length) {
  4140. ticks = sample(ticks, sampleSize);
  4141. }
  4142. this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit);
  4143. }
  4144. return labelSizes;
  4145. }
  4146. _computeLabelSizes(ticks, length, maxTicksLimit) {
  4147. const { ctx , _longestTextCache: caches } = this;
  4148. const widths = [];
  4149. const heights = [];
  4150. const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit));
  4151. let widestLabelSize = 0;
  4152. let highestLabelSize = 0;
  4153. let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
  4154. for(i = 0; i < length; i += increment){
  4155. label = ticks[i].label;
  4156. tickFont = this._resolveTickFontOptions(i);
  4157. ctx.font = fontString = tickFont.string;
  4158. cache = caches[fontString] = caches[fontString] || {
  4159. data: {},
  4160. gc: []
  4161. };
  4162. lineHeight = tickFont.lineHeight;
  4163. width = height = 0;
  4164. if (!isNullOrUndef(label) && !isArray(label)) {
  4165. width = _measureText(ctx, cache.data, cache.gc, width, label);
  4166. height = lineHeight;
  4167. } else if (isArray(label)) {
  4168. for(j = 0, jlen = label.length; j < jlen; ++j){
  4169. nestedLabel = label[j];
  4170. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  4171. width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  4172. height += lineHeight;
  4173. }
  4174. }
  4175. }
  4176. widths.push(width);
  4177. heights.push(height);
  4178. widestLabelSize = Math.max(width, widestLabelSize);
  4179. highestLabelSize = Math.max(height, highestLabelSize);
  4180. }
  4181. garbageCollect(caches, length);
  4182. const widest = widths.indexOf(widestLabelSize);
  4183. const highest = heights.indexOf(highestLabelSize);
  4184. const valueAt = (idx)=>({
  4185. width: widths[idx] || 0,
  4186. height: heights[idx] || 0
  4187. });
  4188. return {
  4189. first: valueAt(0),
  4190. last: valueAt(length - 1),
  4191. widest: valueAt(widest),
  4192. highest: valueAt(highest),
  4193. widths,
  4194. heights
  4195. };
  4196. }
  4197. getLabelForValue(value) {
  4198. return value;
  4199. }
  4200. getPixelForValue(value, index) {
  4201. return NaN;
  4202. }
  4203. getValueForPixel(pixel) {}
  4204. getPixelForTick(index) {
  4205. const ticks = this.ticks;
  4206. if (index < 0 || index > ticks.length - 1) {
  4207. return null;
  4208. }
  4209. return this.getPixelForValue(ticks[index].value);
  4210. }
  4211. getPixelForDecimal(decimal) {
  4212. if (this._reversePixels) {
  4213. decimal = 1 - decimal;
  4214. }
  4215. const pixel = this._startPixel + decimal * this._length;
  4216. return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel);
  4217. }
  4218. getDecimalForPixel(pixel) {
  4219. const decimal = (pixel - this._startPixel) / this._length;
  4220. return this._reversePixels ? 1 - decimal : decimal;
  4221. }
  4222. getBasePixel() {
  4223. return this.getPixelForValue(this.getBaseValue());
  4224. }
  4225. getBaseValue() {
  4226. const { min , max } = this;
  4227. return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0;
  4228. }
  4229. getContext(index) {
  4230. const ticks = this.ticks || [];
  4231. if (index >= 0 && index < ticks.length) {
  4232. const tick = ticks[index];
  4233. return tick.$context || (tick.$context = createTickContext(this.getContext(), index, tick));
  4234. }
  4235. return this.$context || (this.$context = createScaleContext(this.chart.getContext(), this));
  4236. }
  4237. _tickSize() {
  4238. const optionTicks = this.options.ticks;
  4239. const rot = toRadians(this.labelRotation);
  4240. const cos = Math.abs(Math.cos(rot));
  4241. const sin = Math.abs(Math.sin(rot));
  4242. const labelSizes = this._getLabelSizes();
  4243. const padding = optionTicks.autoSkipPadding || 0;
  4244. const w = labelSizes ? labelSizes.widest.width + padding : 0;
  4245. const h = labelSizes ? labelSizes.highest.height + padding : 0;
  4246. return this.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin;
  4247. }
  4248. _isVisible() {
  4249. const display = this.options.display;
  4250. if (display !== 'auto') {
  4251. return !!display;
  4252. }
  4253. return this.getMatchingVisibleMetas().length > 0;
  4254. }
  4255. _computeGridLineItems(chartArea) {
  4256. const axis = this.axis;
  4257. const chart = this.chart;
  4258. const options = this.options;
  4259. const { grid , position , border } = options;
  4260. const offset = grid.offset;
  4261. const isHorizontal = this.isHorizontal();
  4262. const ticks = this.ticks;
  4263. const ticksLength = ticks.length + (offset ? 1 : 0);
  4264. const tl = getTickMarkLength(grid);
  4265. const items = [];
  4266. const borderOpts = border.setContext(this.getContext());
  4267. const axisWidth = borderOpts.display ? borderOpts.width : 0;
  4268. const axisHalfWidth = axisWidth / 2;
  4269. const alignBorderValue = function(pixel) {
  4270. return _alignPixel(chart, pixel, axisWidth);
  4271. };
  4272. let borderValue, i, lineValue, alignedLineValue;
  4273. let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
  4274. if (position === 'top') {
  4275. borderValue = alignBorderValue(this.bottom);
  4276. ty1 = this.bottom - tl;
  4277. ty2 = borderValue - axisHalfWidth;
  4278. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  4279. y2 = chartArea.bottom;
  4280. } else if (position === 'bottom') {
  4281. borderValue = alignBorderValue(this.top);
  4282. y1 = chartArea.top;
  4283. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  4284. ty1 = borderValue + axisHalfWidth;
  4285. ty2 = this.top + tl;
  4286. } else if (position === 'left') {
  4287. borderValue = alignBorderValue(this.right);
  4288. tx1 = this.right - tl;
  4289. tx2 = borderValue - axisHalfWidth;
  4290. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  4291. x2 = chartArea.right;
  4292. } else if (position === 'right') {
  4293. borderValue = alignBorderValue(this.left);
  4294. x1 = chartArea.left;
  4295. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  4296. tx1 = borderValue + axisHalfWidth;
  4297. tx2 = this.left + tl;
  4298. } else if (axis === 'x') {
  4299. if (position === 'center') {
  4300. borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
  4301. } else if (isObject(position)) {
  4302. const positionAxisID = Object.keys(position)[0];
  4303. const value = position[positionAxisID];
  4304. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4305. }
  4306. y1 = chartArea.top;
  4307. y2 = chartArea.bottom;
  4308. ty1 = borderValue + axisHalfWidth;
  4309. ty2 = ty1 + tl;
  4310. } else if (axis === 'y') {
  4311. if (position === 'center') {
  4312. borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
  4313. } else if (isObject(position)) {
  4314. const positionAxisID = Object.keys(position)[0];
  4315. const value = position[positionAxisID];
  4316. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4317. }
  4318. tx1 = borderValue - axisHalfWidth;
  4319. tx2 = tx1 - tl;
  4320. x1 = chartArea.left;
  4321. x2 = chartArea.right;
  4322. }
  4323. const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);
  4324. const step = Math.max(1, Math.ceil(ticksLength / limit));
  4325. for(i = 0; i < ticksLength; i += step){
  4326. const context = this.getContext(i);
  4327. const optsAtIndex = grid.setContext(context);
  4328. const optsAtIndexBorder = border.setContext(context);
  4329. const lineWidth = optsAtIndex.lineWidth;
  4330. const lineColor = optsAtIndex.color;
  4331. const borderDash = optsAtIndexBorder.dash || [];
  4332. const borderDashOffset = optsAtIndexBorder.dashOffset;
  4333. const tickWidth = optsAtIndex.tickWidth;
  4334. const tickColor = optsAtIndex.tickColor;
  4335. const tickBorderDash = optsAtIndex.tickBorderDash || [];
  4336. const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
  4337. lineValue = getPixelForGridLine(this, i, offset);
  4338. if (lineValue === undefined) {
  4339. continue;
  4340. }
  4341. alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
  4342. if (isHorizontal) {
  4343. tx1 = tx2 = x1 = x2 = alignedLineValue;
  4344. } else {
  4345. ty1 = ty2 = y1 = y2 = alignedLineValue;
  4346. }
  4347. items.push({
  4348. tx1,
  4349. ty1,
  4350. tx2,
  4351. ty2,
  4352. x1,
  4353. y1,
  4354. x2,
  4355. y2,
  4356. width: lineWidth,
  4357. color: lineColor,
  4358. borderDash,
  4359. borderDashOffset,
  4360. tickWidth,
  4361. tickColor,
  4362. tickBorderDash,
  4363. tickBorderDashOffset
  4364. });
  4365. }
  4366. this._ticksLength = ticksLength;
  4367. this._borderValue = borderValue;
  4368. return items;
  4369. }
  4370. _computeLabelItems(chartArea) {
  4371. const axis = this.axis;
  4372. const options = this.options;
  4373. const { position , ticks: optionTicks } = options;
  4374. const isHorizontal = this.isHorizontal();
  4375. const ticks = this.ticks;
  4376. const { align , crossAlign , padding , mirror } = optionTicks;
  4377. const tl = getTickMarkLength(options.grid);
  4378. const tickAndPadding = tl + padding;
  4379. const hTickAndPadding = mirror ? -padding : tickAndPadding;
  4380. const rotation = -toRadians(this.labelRotation);
  4381. const items = [];
  4382. let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  4383. let textBaseline = 'middle';
  4384. if (position === 'top') {
  4385. y = this.bottom - hTickAndPadding;
  4386. textAlign = this._getXAxisLabelAlignment();
  4387. } else if (position === 'bottom') {
  4388. y = this.top + hTickAndPadding;
  4389. textAlign = this._getXAxisLabelAlignment();
  4390. } else if (position === 'left') {
  4391. const ret = this._getYAxisLabelAlignment(tl);
  4392. textAlign = ret.textAlign;
  4393. x = ret.x;
  4394. } else if (position === 'right') {
  4395. const ret = this._getYAxisLabelAlignment(tl);
  4396. textAlign = ret.textAlign;
  4397. x = ret.x;
  4398. } else if (axis === 'x') {
  4399. if (position === 'center') {
  4400. y = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding;
  4401. } else if (isObject(position)) {
  4402. const positionAxisID = Object.keys(position)[0];
  4403. const value = position[positionAxisID];
  4404. y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
  4405. }
  4406. textAlign = this._getXAxisLabelAlignment();
  4407. } else if (axis === 'y') {
  4408. if (position === 'center') {
  4409. x = (chartArea.left + chartArea.right) / 2 - tickAndPadding;
  4410. } else if (isObject(position)) {
  4411. const positionAxisID = Object.keys(position)[0];
  4412. const value = position[positionAxisID];
  4413. x = this.chart.scales[positionAxisID].getPixelForValue(value);
  4414. }
  4415. textAlign = this._getYAxisLabelAlignment(tl).textAlign;
  4416. }
  4417. if (axis === 'y') {
  4418. if (align === 'start') {
  4419. textBaseline = 'top';
  4420. } else if (align === 'end') {
  4421. textBaseline = 'bottom';
  4422. }
  4423. }
  4424. const labelSizes = this._getLabelSizes();
  4425. for(i = 0, ilen = ticks.length; i < ilen; ++i){
  4426. tick = ticks[i];
  4427. label = tick.label;
  4428. const optsAtIndex = optionTicks.setContext(this.getContext(i));
  4429. pixel = this.getPixelForTick(i) + optionTicks.labelOffset;
  4430. font = this._resolveTickFontOptions(i);
  4431. lineHeight = font.lineHeight;
  4432. lineCount = isArray(label) ? label.length : 1;
  4433. const halfCount = lineCount / 2;
  4434. const color = optsAtIndex.color;
  4435. const strokeColor = optsAtIndex.textStrokeColor;
  4436. const strokeWidth = optsAtIndex.textStrokeWidth;
  4437. let tickTextAlign = textAlign;
  4438. if (isHorizontal) {
  4439. x = pixel;
  4440. if (textAlign === 'inner') {
  4441. if (i === ilen - 1) {
  4442. tickTextAlign = !this.options.reverse ? 'right' : 'left';
  4443. } else if (i === 0) {
  4444. tickTextAlign = !this.options.reverse ? 'left' : 'right';
  4445. } else {
  4446. tickTextAlign = 'center';
  4447. }
  4448. }
  4449. if (position === 'top') {
  4450. if (crossAlign === 'near' || rotation !== 0) {
  4451. textOffset = -lineCount * lineHeight + lineHeight / 2;
  4452. } else if (crossAlign === 'center') {
  4453. textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
  4454. } else {
  4455. textOffset = -labelSizes.highest.height + lineHeight / 2;
  4456. }
  4457. } else {
  4458. if (crossAlign === 'near' || rotation !== 0) {
  4459. textOffset = lineHeight / 2;
  4460. } else if (crossAlign === 'center') {
  4461. textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
  4462. } else {
  4463. textOffset = labelSizes.highest.height - lineCount * lineHeight;
  4464. }
  4465. }
  4466. if (mirror) {
  4467. textOffset *= -1;
  4468. }
  4469. if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) {
  4470. x += lineHeight / 2 * Math.sin(rotation);
  4471. }
  4472. } else {
  4473. y = pixel;
  4474. textOffset = (1 - lineCount) * lineHeight / 2;
  4475. }
  4476. let backdrop;
  4477. if (optsAtIndex.showLabelBackdrop) {
  4478. const labelPadding = toPadding(optsAtIndex.backdropPadding);
  4479. const height = labelSizes.heights[i];
  4480. const width = labelSizes.widths[i];
  4481. let top = textOffset - labelPadding.top;
  4482. let left = 0 - labelPadding.left;
  4483. switch(textBaseline){
  4484. case 'middle':
  4485. top -= height / 2;
  4486. break;
  4487. case 'bottom':
  4488. top -= height;
  4489. break;
  4490. }
  4491. switch(textAlign){
  4492. case 'center':
  4493. left -= width / 2;
  4494. break;
  4495. case 'right':
  4496. left -= width;
  4497. break;
  4498. case 'inner':
  4499. if (i === ilen - 1) {
  4500. left -= width;
  4501. } else if (i > 0) {
  4502. left -= width / 2;
  4503. }
  4504. break;
  4505. }
  4506. backdrop = {
  4507. left,
  4508. top,
  4509. width: width + labelPadding.width,
  4510. height: height + labelPadding.height,
  4511. color: optsAtIndex.backdropColor
  4512. };
  4513. }
  4514. items.push({
  4515. label,
  4516. font,
  4517. textOffset,
  4518. options: {
  4519. rotation,
  4520. color,
  4521. strokeColor,
  4522. strokeWidth,
  4523. textAlign: tickTextAlign,
  4524. textBaseline,
  4525. translation: [
  4526. x,
  4527. y
  4528. ],
  4529. backdrop
  4530. }
  4531. });
  4532. }
  4533. return items;
  4534. }
  4535. _getXAxisLabelAlignment() {
  4536. const { position , ticks } = this.options;
  4537. const rotation = -toRadians(this.labelRotation);
  4538. if (rotation) {
  4539. return position === 'top' ? 'left' : 'right';
  4540. }
  4541. let align = 'center';
  4542. if (ticks.align === 'start') {
  4543. align = 'left';
  4544. } else if (ticks.align === 'end') {
  4545. align = 'right';
  4546. } else if (ticks.align === 'inner') {
  4547. align = 'inner';
  4548. }
  4549. return align;
  4550. }
  4551. _getYAxisLabelAlignment(tl) {
  4552. const { position , ticks: { crossAlign , mirror , padding } } = this.options;
  4553. const labelSizes = this._getLabelSizes();
  4554. const tickAndPadding = tl + padding;
  4555. const widest = labelSizes.widest.width;
  4556. let textAlign;
  4557. let x;
  4558. if (position === 'left') {
  4559. if (mirror) {
  4560. x = this.right + padding;
  4561. if (crossAlign === 'near') {
  4562. textAlign = 'left';
  4563. } else if (crossAlign === 'center') {
  4564. textAlign = 'center';
  4565. x += widest / 2;
  4566. } else {
  4567. textAlign = 'right';
  4568. x += widest;
  4569. }
  4570. } else {
  4571. x = this.right - tickAndPadding;
  4572. if (crossAlign === 'near') {
  4573. textAlign = 'right';
  4574. } else if (crossAlign === 'center') {
  4575. textAlign = 'center';
  4576. x -= widest / 2;
  4577. } else {
  4578. textAlign = 'left';
  4579. x = this.left;
  4580. }
  4581. }
  4582. } else if (position === 'right') {
  4583. if (mirror) {
  4584. x = this.left + padding;
  4585. if (crossAlign === 'near') {
  4586. textAlign = 'right';
  4587. } else if (crossAlign === 'center') {
  4588. textAlign = 'center';
  4589. x -= widest / 2;
  4590. } else {
  4591. textAlign = 'left';
  4592. x -= widest;
  4593. }
  4594. } else {
  4595. x = this.left + tickAndPadding;
  4596. if (crossAlign === 'near') {
  4597. textAlign = 'left';
  4598. } else if (crossAlign === 'center') {
  4599. textAlign = 'center';
  4600. x += widest / 2;
  4601. } else {
  4602. textAlign = 'right';
  4603. x = this.right;
  4604. }
  4605. }
  4606. } else {
  4607. textAlign = 'right';
  4608. }
  4609. return {
  4610. textAlign,
  4611. x
  4612. };
  4613. }
  4614. _computeLabelArea() {
  4615. if (this.options.ticks.mirror) {
  4616. return;
  4617. }
  4618. const chart = this.chart;
  4619. const position = this.options.position;
  4620. if (position === 'left' || position === 'right') {
  4621. return {
  4622. top: 0,
  4623. left: this.left,
  4624. bottom: chart.height,
  4625. right: this.right
  4626. };
  4627. }
  4628. if (position === 'top' || position === 'bottom') {
  4629. return {
  4630. top: this.top,
  4631. left: 0,
  4632. bottom: this.bottom,
  4633. right: chart.width
  4634. };
  4635. }
  4636. }
  4637. drawBackground() {
  4638. const { ctx , options: { backgroundColor } , left , top , width , height } = this;
  4639. if (backgroundColor) {
  4640. ctx.save();
  4641. ctx.fillStyle = backgroundColor;
  4642. ctx.fillRect(left, top, width, height);
  4643. ctx.restore();
  4644. }
  4645. }
  4646. getLineWidthForValue(value) {
  4647. const grid = this.options.grid;
  4648. if (!this._isVisible() || !grid.display) {
  4649. return 0;
  4650. }
  4651. const ticks = this.ticks;
  4652. const index = ticks.findIndex((t)=>t.value === value);
  4653. if (index >= 0) {
  4654. const opts = grid.setContext(this.getContext(index));
  4655. return opts.lineWidth;
  4656. }
  4657. return 0;
  4658. }
  4659. drawGrid(chartArea) {
  4660. const grid = this.options.grid;
  4661. const ctx = this.ctx;
  4662. const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea));
  4663. let i, ilen;
  4664. const drawLine = (p1, p2, style)=>{
  4665. if (!style.width || !style.color) {
  4666. return;
  4667. }
  4668. ctx.save();
  4669. ctx.lineWidth = style.width;
  4670. ctx.strokeStyle = style.color;
  4671. ctx.setLineDash(style.borderDash || []);
  4672. ctx.lineDashOffset = style.borderDashOffset;
  4673. ctx.beginPath();
  4674. ctx.moveTo(p1.x, p1.y);
  4675. ctx.lineTo(p2.x, p2.y);
  4676. ctx.stroke();
  4677. ctx.restore();
  4678. };
  4679. if (grid.display) {
  4680. for(i = 0, ilen = items.length; i < ilen; ++i){
  4681. const item = items[i];
  4682. if (grid.drawOnChartArea) {
  4683. drawLine({
  4684. x: item.x1,
  4685. y: item.y1
  4686. }, {
  4687. x: item.x2,
  4688. y: item.y2
  4689. }, item);
  4690. }
  4691. if (grid.drawTicks) {
  4692. drawLine({
  4693. x: item.tx1,
  4694. y: item.ty1
  4695. }, {
  4696. x: item.tx2,
  4697. y: item.ty2
  4698. }, {
  4699. color: item.tickColor,
  4700. width: item.tickWidth,
  4701. borderDash: item.tickBorderDash,
  4702. borderDashOffset: item.tickBorderDashOffset
  4703. });
  4704. }
  4705. }
  4706. }
  4707. }
  4708. drawBorder() {
  4709. const { chart , ctx , options: { border , grid } } = this;
  4710. const borderOpts = border.setContext(this.getContext());
  4711. const axisWidth = border.display ? borderOpts.width : 0;
  4712. if (!axisWidth) {
  4713. return;
  4714. }
  4715. const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth;
  4716. const borderValue = this._borderValue;
  4717. let x1, x2, y1, y2;
  4718. if (this.isHorizontal()) {
  4719. x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2;
  4720. x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2;
  4721. y1 = y2 = borderValue;
  4722. } else {
  4723. y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2;
  4724. y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2;
  4725. x1 = x2 = borderValue;
  4726. }
  4727. ctx.save();
  4728. ctx.lineWidth = borderOpts.width;
  4729. ctx.strokeStyle = borderOpts.color;
  4730. ctx.beginPath();
  4731. ctx.moveTo(x1, y1);
  4732. ctx.lineTo(x2, y2);
  4733. ctx.stroke();
  4734. ctx.restore();
  4735. }
  4736. drawLabels(chartArea) {
  4737. const optionTicks = this.options.ticks;
  4738. if (!optionTicks.display) {
  4739. return;
  4740. }
  4741. const ctx = this.ctx;
  4742. const area = this._computeLabelArea();
  4743. if (area) {
  4744. clipArea(ctx, area);
  4745. }
  4746. const items = this.getLabelItems(chartArea);
  4747. for (const item of items){
  4748. const renderTextOptions = item.options;
  4749. const tickFont = item.font;
  4750. const label = item.label;
  4751. const y = item.textOffset;
  4752. renderText(ctx, label, 0, y, tickFont, renderTextOptions);
  4753. }
  4754. if (area) {
  4755. unclipArea(ctx);
  4756. }
  4757. }
  4758. drawTitle() {
  4759. const { ctx , options: { position , title , reverse } } = this;
  4760. if (!title.display) {
  4761. return;
  4762. }
  4763. const font = toFont(title.font);
  4764. const padding = toPadding(title.padding);
  4765. const align = title.align;
  4766. let offset = font.lineHeight / 2;
  4767. if (position === 'bottom' || position === 'center' || isObject(position)) {
  4768. offset += padding.bottom;
  4769. if (isArray(title.text)) {
  4770. offset += font.lineHeight * (title.text.length - 1);
  4771. }
  4772. } else {
  4773. offset += padding.top;
  4774. }
  4775. const { titleX , titleY , maxWidth , rotation } = titleArgs(this, offset, position, align);
  4776. renderText(ctx, title.text, 0, 0, font, {
  4777. color: title.color,
  4778. maxWidth,
  4779. rotation,
  4780. textAlign: titleAlign(align, position, reverse),
  4781. textBaseline: 'middle',
  4782. translation: [
  4783. titleX,
  4784. titleY
  4785. ]
  4786. });
  4787. }
  4788. draw(chartArea) {
  4789. if (!this._isVisible()) {
  4790. return;
  4791. }
  4792. this.drawBackground();
  4793. this.drawGrid(chartArea);
  4794. this.drawBorder();
  4795. this.drawTitle();
  4796. this.drawLabels(chartArea);
  4797. }
  4798. _layers() {
  4799. const opts = this.options;
  4800. const tz = opts.ticks && opts.ticks.z || 0;
  4801. const gz = valueOrDefault(opts.grid && opts.grid.z, -1);
  4802. const bz = valueOrDefault(opts.border && opts.border.z, 0);
  4803. if (!this._isVisible() || this.draw !== Scale.prototype.draw) {
  4804. return [
  4805. {
  4806. z: tz,
  4807. draw: (chartArea)=>{
  4808. this.draw(chartArea);
  4809. }
  4810. }
  4811. ];
  4812. }
  4813. return [
  4814. {
  4815. z: gz,
  4816. draw: (chartArea)=>{
  4817. this.drawBackground();
  4818. this.drawGrid(chartArea);
  4819. this.drawTitle();
  4820. }
  4821. },
  4822. {
  4823. z: bz,
  4824. draw: ()=>{
  4825. this.drawBorder();
  4826. }
  4827. },
  4828. {
  4829. z: tz,
  4830. draw: (chartArea)=>{
  4831. this.drawLabels(chartArea);
  4832. }
  4833. }
  4834. ];
  4835. }
  4836. getMatchingVisibleMetas(type) {
  4837. const metas = this.chart.getSortedVisibleDatasetMetas();
  4838. const axisID = this.axis + 'AxisID';
  4839. const result = [];
  4840. let i, ilen;
  4841. for(i = 0, ilen = metas.length; i < ilen; ++i){
  4842. const meta = metas[i];
  4843. if (meta[axisID] === this.id && (!type || meta.type === type)) {
  4844. result.push(meta);
  4845. }
  4846. }
  4847. return result;
  4848. }
  4849. _resolveTickFontOptions(index) {
  4850. const opts = this.options.ticks.setContext(this.getContext(index));
  4851. return toFont(opts.font);
  4852. }
  4853. _maxDigits() {
  4854. const fontSize = this._resolveTickFontOptions(0).lineHeight;
  4855. return (this.isHorizontal() ? this.width : this.height) / fontSize;
  4856. }
  4857. }
  4858. class TypedRegistry {
  4859. constructor(type, scope, override){
  4860. this.type = type;
  4861. this.scope = scope;
  4862. this.override = override;
  4863. this.items = Object.create(null);
  4864. }
  4865. isForType(type) {
  4866. return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
  4867. }
  4868. register(item) {
  4869. const proto = Object.getPrototypeOf(item);
  4870. let parentScope;
  4871. if (isIChartComponent(proto)) {
  4872. parentScope = this.register(proto);
  4873. }
  4874. const items = this.items;
  4875. const id = item.id;
  4876. const scope = this.scope + '.' + id;
  4877. if (!id) {
  4878. throw new Error('class does not have id: ' + item);
  4879. }
  4880. if (id in items) {
  4881. return scope;
  4882. }
  4883. items[id] = item;
  4884. registerDefaults(item, scope, parentScope);
  4885. if (this.override) {
  4886. defaults.override(item.id, item.overrides);
  4887. }
  4888. return scope;
  4889. }
  4890. get(id) {
  4891. return this.items[id];
  4892. }
  4893. unregister(item) {
  4894. const items = this.items;
  4895. const id = item.id;
  4896. const scope = this.scope;
  4897. if (id in items) {
  4898. delete items[id];
  4899. }
  4900. if (scope && id in defaults[scope]) {
  4901. delete defaults[scope][id];
  4902. if (this.override) {
  4903. delete overrides[id];
  4904. }
  4905. }
  4906. }
  4907. }
  4908. function registerDefaults(item, scope, parentScope) {
  4909. const itemDefaults = merge(Object.create(null), [
  4910. parentScope ? defaults.get(parentScope) : {},
  4911. defaults.get(scope),
  4912. item.defaults
  4913. ]);
  4914. defaults.set(scope, itemDefaults);
  4915. if (item.defaultRoutes) {
  4916. routeDefaults(scope, item.defaultRoutes);
  4917. }
  4918. if (item.descriptors) {
  4919. defaults.describe(scope, item.descriptors);
  4920. }
  4921. }
  4922. function routeDefaults(scope, routes) {
  4923. Object.keys(routes).forEach((property)=>{
  4924. const propertyParts = property.split('.');
  4925. const sourceName = propertyParts.pop();
  4926. const sourceScope = [
  4927. scope
  4928. ].concat(propertyParts).join('.');
  4929. const parts = routes[property].split('.');
  4930. const targetName = parts.pop();
  4931. const targetScope = parts.join('.');
  4932. defaults.route(sourceScope, sourceName, targetScope, targetName);
  4933. });
  4934. }
  4935. function isIChartComponent(proto) {
  4936. return 'id' in proto && 'defaults' in proto;
  4937. }
  4938. class Registry {
  4939. constructor(){
  4940. this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
  4941. this.elements = new TypedRegistry(Element, 'elements');
  4942. this.plugins = new TypedRegistry(Object, 'plugins');
  4943. this.scales = new TypedRegistry(Scale, 'scales');
  4944. this._typedRegistries = [
  4945. this.controllers,
  4946. this.scales,
  4947. this.elements
  4948. ];
  4949. }
  4950. add(...args) {
  4951. this._each('register', args);
  4952. }
  4953. remove(...args) {
  4954. this._each('unregister', args);
  4955. }
  4956. addControllers(...args) {
  4957. this._each('register', args, this.controllers);
  4958. }
  4959. addElements(...args) {
  4960. this._each('register', args, this.elements);
  4961. }
  4962. addPlugins(...args) {
  4963. this._each('register', args, this.plugins);
  4964. }
  4965. addScales(...args) {
  4966. this._each('register', args, this.scales);
  4967. }
  4968. getController(id) {
  4969. return this._get(id, this.controllers, 'controller');
  4970. }
  4971. getElement(id) {
  4972. return this._get(id, this.elements, 'element');
  4973. }
  4974. getPlugin(id) {
  4975. return this._get(id, this.plugins, 'plugin');
  4976. }
  4977. getScale(id) {
  4978. return this._get(id, this.scales, 'scale');
  4979. }
  4980. removeControllers(...args) {
  4981. this._each('unregister', args, this.controllers);
  4982. }
  4983. removeElements(...args) {
  4984. this._each('unregister', args, this.elements);
  4985. }
  4986. removePlugins(...args) {
  4987. this._each('unregister', args, this.plugins);
  4988. }
  4989. removeScales(...args) {
  4990. this._each('unregister', args, this.scales);
  4991. }
  4992. _each(method, args, typedRegistry) {
  4993. [
  4994. ...args
  4995. ].forEach((arg)=>{
  4996. const reg = typedRegistry || this._getRegistryForType(arg);
  4997. if (typedRegistry || reg.isForType(arg) || reg === this.plugins && arg.id) {
  4998. this._exec(method, reg, arg);
  4999. } else {
  5000. each(arg, (item)=>{
  5001. const itemReg = typedRegistry || this._getRegistryForType(item);
  5002. this._exec(method, itemReg, item);
  5003. });
  5004. }
  5005. });
  5006. }
  5007. _exec(method, registry, component) {
  5008. const camelMethod = _capitalize(method);
  5009. callback(component['before' + camelMethod], [], component);
  5010. registry[method](component);
  5011. callback(component['after' + camelMethod], [], component);
  5012. }
  5013. _getRegistryForType(type) {
  5014. for(let i = 0; i < this._typedRegistries.length; i++){
  5015. const reg = this._typedRegistries[i];
  5016. if (reg.isForType(type)) {
  5017. return reg;
  5018. }
  5019. }
  5020. return this.plugins;
  5021. }
  5022. _get(id, typedRegistry, type) {
  5023. const item = typedRegistry.get(id);
  5024. if (item === undefined) {
  5025. throw new Error('"' + id + '" is not a registered ' + type + '.');
  5026. }
  5027. return item;
  5028. }
  5029. }
  5030. var registry = /* #__PURE__ */ new Registry();
  5031. class PluginService {
  5032. constructor(){
  5033. this._init = [];
  5034. }
  5035. notify(chart, hook, args, filter) {
  5036. if (hook === 'beforeInit') {
  5037. this._init = this._createDescriptors(chart, true);
  5038. this._notify(this._init, chart, 'install');
  5039. }
  5040. const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart);
  5041. const result = this._notify(descriptors, chart, hook, args);
  5042. if (hook === 'afterDestroy') {
  5043. this._notify(descriptors, chart, 'stop');
  5044. this._notify(this._init, chart, 'uninstall');
  5045. }
  5046. return result;
  5047. }
  5048. _notify(descriptors, chart, hook, args) {
  5049. args = args || {};
  5050. for (const descriptor of descriptors){
  5051. const plugin = descriptor.plugin;
  5052. const method = plugin[hook];
  5053. const params = [
  5054. chart,
  5055. args,
  5056. descriptor.options
  5057. ];
  5058. if (callback(method, params, plugin) === false && args.cancelable) {
  5059. return false;
  5060. }
  5061. }
  5062. return true;
  5063. }
  5064. invalidate() {
  5065. if (!isNullOrUndef(this._cache)) {
  5066. this._oldCache = this._cache;
  5067. this._cache = undefined;
  5068. }
  5069. }
  5070. _descriptors(chart) {
  5071. if (this._cache) {
  5072. return this._cache;
  5073. }
  5074. const descriptors = this._cache = this._createDescriptors(chart);
  5075. this._notifyStateChanges(chart);
  5076. return descriptors;
  5077. }
  5078. _createDescriptors(chart, all) {
  5079. const config = chart && chart.config;
  5080. const options = valueOrDefault(config.options && config.options.plugins, {});
  5081. const plugins = allPlugins(config);
  5082. return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
  5083. }
  5084. _notifyStateChanges(chart) {
  5085. const previousDescriptors = this._oldCache || [];
  5086. const descriptors = this._cache;
  5087. const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.plugin.id === y.plugin.id));
  5088. this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
  5089. this._notify(diff(descriptors, previousDescriptors), chart, 'start');
  5090. }
  5091. }
  5092. function allPlugins(config) {
  5093. const localIds = {};
  5094. const plugins = [];
  5095. const keys = Object.keys(registry.plugins.items);
  5096. for(let i = 0; i < keys.length; i++){
  5097. plugins.push(registry.getPlugin(keys[i]));
  5098. }
  5099. const local = config.plugins || [];
  5100. for(let i = 0; i < local.length; i++){
  5101. const plugin = local[i];
  5102. if (plugins.indexOf(plugin) === -1) {
  5103. plugins.push(plugin);
  5104. localIds[plugin.id] = true;
  5105. }
  5106. }
  5107. return {
  5108. plugins,
  5109. localIds
  5110. };
  5111. }
  5112. function getOpts(options, all) {
  5113. if (!all && options === false) {
  5114. return null;
  5115. }
  5116. if (options === true) {
  5117. return {};
  5118. }
  5119. return options;
  5120. }
  5121. function createDescriptors(chart, { plugins , localIds }, options, all) {
  5122. const result = [];
  5123. const context = chart.getContext();
  5124. for (const plugin of plugins){
  5125. const id = plugin.id;
  5126. const opts = getOpts(options[id], all);
  5127. if (opts === null) {
  5128. continue;
  5129. }
  5130. result.push({
  5131. plugin,
  5132. options: pluginOpts(chart.config, {
  5133. plugin,
  5134. local: localIds[id]
  5135. }, opts, context)
  5136. });
  5137. }
  5138. return result;
  5139. }
  5140. function pluginOpts(config, { plugin , local }, opts, context) {
  5141. const keys = config.pluginScopeKeys(plugin);
  5142. const scopes = config.getOptionScopes(opts, keys);
  5143. if (local && plugin.defaults) {
  5144. scopes.push(plugin.defaults);
  5145. }
  5146. return config.createResolver(scopes, context, [
  5147. ''
  5148. ], {
  5149. scriptable: false,
  5150. indexable: false,
  5151. allKeys: true
  5152. });
  5153. }
  5154. function getIndexAxis(type, options) {
  5155. const datasetDefaults = defaults.datasets[type] || {};
  5156. const datasetOptions = (options.datasets || {})[type] || {};
  5157. return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
  5158. }
  5159. function getAxisFromDefaultScaleID(id, indexAxis) {
  5160. let axis = id;
  5161. if (id === '_index_') {
  5162. axis = indexAxis;
  5163. } else if (id === '_value_') {
  5164. axis = indexAxis === 'x' ? 'y' : 'x';
  5165. }
  5166. return axis;
  5167. }
  5168. function getDefaultScaleIDFromAxis(axis, indexAxis) {
  5169. return axis === indexAxis ? '_index_' : '_value_';
  5170. }
  5171. function idMatchesAxis(id) {
  5172. if (id === 'x' || id === 'y' || id === 'r') {
  5173. return id;
  5174. }
  5175. }
  5176. function axisFromPosition(position) {
  5177. if (position === 'top' || position === 'bottom') {
  5178. return 'x';
  5179. }
  5180. if (position === 'left' || position === 'right') {
  5181. return 'y';
  5182. }
  5183. }
  5184. function determineAxis(id, ...scaleOptions) {
  5185. if (idMatchesAxis(id)) {
  5186. return id;
  5187. }
  5188. for (const opts of scaleOptions){
  5189. const axis = opts.axis || axisFromPosition(opts.position) || id.length > 1 && idMatchesAxis(id[0].toLowerCase());
  5190. if (axis) {
  5191. return axis;
  5192. }
  5193. }
  5194. throw new Error(`Cannot determine type of '${id}' axis. Please provide 'axis' or 'position' option.`);
  5195. }
  5196. function getAxisFromDataset(id, axis, dataset) {
  5197. if (dataset[axis + 'AxisID'] === id) {
  5198. return {
  5199. axis
  5200. };
  5201. }
  5202. }
  5203. function retrieveAxisFromDatasets(id, config) {
  5204. if (config.data && config.data.datasets) {
  5205. const boundDs = config.data.datasets.filter((d)=>d.xAxisID === id || d.yAxisID === id);
  5206. if (boundDs.length) {
  5207. return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]);
  5208. }
  5209. }
  5210. return {};
  5211. }
  5212. function mergeScaleConfig(config, options) {
  5213. const chartDefaults = overrides[config.type] || {
  5214. scales: {}
  5215. };
  5216. const configScales = options.scales || {};
  5217. const chartIndexAxis = getIndexAxis(config.type, options);
  5218. const scales = Object.create(null);
  5219. Object.keys(configScales).forEach((id)=>{
  5220. const scaleConf = configScales[id];
  5221. if (!isObject(scaleConf)) {
  5222. return console.error(`Invalid scale configuration for scale: ${id}`);
  5223. }
  5224. if (scaleConf._proxy) {
  5225. return console.warn(`Ignoring resolver passed as options for scale: ${id}`);
  5226. }
  5227. const axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), defaults.scales[scaleConf.type]);
  5228. const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
  5229. const defaultScaleOptions = chartDefaults.scales || {};
  5230. scales[id] = mergeIf(Object.create(null), [
  5231. {
  5232. axis
  5233. },
  5234. scaleConf,
  5235. defaultScaleOptions[axis],
  5236. defaultScaleOptions[defaultId]
  5237. ]);
  5238. });
  5239. config.data.datasets.forEach((dataset)=>{
  5240. const type = dataset.type || config.type;
  5241. const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
  5242. const datasetDefaults = overrides[type] || {};
  5243. const defaultScaleOptions = datasetDefaults.scales || {};
  5244. Object.keys(defaultScaleOptions).forEach((defaultID)=>{
  5245. const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
  5246. const id = dataset[axis + 'AxisID'] || axis;
  5247. scales[id] = scales[id] || Object.create(null);
  5248. mergeIf(scales[id], [
  5249. {
  5250. axis
  5251. },
  5252. configScales[id],
  5253. defaultScaleOptions[defaultID]
  5254. ]);
  5255. });
  5256. });
  5257. Object.keys(scales).forEach((key)=>{
  5258. const scale = scales[key];
  5259. mergeIf(scale, [
  5260. defaults.scales[scale.type],
  5261. defaults.scale
  5262. ]);
  5263. });
  5264. return scales;
  5265. }
  5266. function initOptions(config) {
  5267. const options = config.options || (config.options = {});
  5268. options.plugins = valueOrDefault(options.plugins, {});
  5269. options.scales = mergeScaleConfig(config, options);
  5270. }
  5271. function initData(data) {
  5272. data = data || {};
  5273. data.datasets = data.datasets || [];
  5274. data.labels = data.labels || [];
  5275. return data;
  5276. }
  5277. function initConfig(config) {
  5278. config = config || {};
  5279. config.data = initData(config.data);
  5280. initOptions(config);
  5281. return config;
  5282. }
  5283. const keyCache = new Map();
  5284. const keysCached = new Set();
  5285. function cachedKeys(cacheKey, generate) {
  5286. let keys = keyCache.get(cacheKey);
  5287. if (!keys) {
  5288. keys = generate();
  5289. keyCache.set(cacheKey, keys);
  5290. keysCached.add(keys);
  5291. }
  5292. return keys;
  5293. }
  5294. const addIfFound = (set, obj, key)=>{
  5295. const opts = resolveObjectKey(obj, key);
  5296. if (opts !== undefined) {
  5297. set.add(opts);
  5298. }
  5299. };
  5300. class Config {
  5301. constructor(config){
  5302. this._config = initConfig(config);
  5303. this._scopeCache = new Map();
  5304. this._resolverCache = new Map();
  5305. }
  5306. get platform() {
  5307. return this._config.platform;
  5308. }
  5309. get type() {
  5310. return this._config.type;
  5311. }
  5312. set type(type) {
  5313. this._config.type = type;
  5314. }
  5315. get data() {
  5316. return this._config.data;
  5317. }
  5318. set data(data) {
  5319. this._config.data = initData(data);
  5320. }
  5321. get options() {
  5322. return this._config.options;
  5323. }
  5324. set options(options) {
  5325. this._config.options = options;
  5326. }
  5327. get plugins() {
  5328. return this._config.plugins;
  5329. }
  5330. update() {
  5331. const config = this._config;
  5332. this.clearCache();
  5333. initOptions(config);
  5334. }
  5335. clearCache() {
  5336. this._scopeCache.clear();
  5337. this._resolverCache.clear();
  5338. }
  5339. datasetScopeKeys(datasetType) {
  5340. return cachedKeys(datasetType, ()=>[
  5341. [
  5342. `datasets.${datasetType}`,
  5343. ''
  5344. ]
  5345. ]);
  5346. }
  5347. datasetAnimationScopeKeys(datasetType, transition) {
  5348. return cachedKeys(`${datasetType}.transition.${transition}`, ()=>[
  5349. [
  5350. `datasets.${datasetType}.transitions.${transition}`,
  5351. `transitions.${transition}`
  5352. ],
  5353. [
  5354. `datasets.${datasetType}`,
  5355. ''
  5356. ]
  5357. ]);
  5358. }
  5359. datasetElementScopeKeys(datasetType, elementType) {
  5360. return cachedKeys(`${datasetType}-${elementType}`, ()=>[
  5361. [
  5362. `datasets.${datasetType}.elements.${elementType}`,
  5363. `datasets.${datasetType}`,
  5364. `elements.${elementType}`,
  5365. ''
  5366. ]
  5367. ]);
  5368. }
  5369. pluginScopeKeys(plugin) {
  5370. const id = plugin.id;
  5371. const type = this.type;
  5372. return cachedKeys(`${type}-plugin-${id}`, ()=>[
  5373. [
  5374. `plugins.${id}`,
  5375. ...plugin.additionalOptionScopes || []
  5376. ]
  5377. ]);
  5378. }
  5379. _cachedScopes(mainScope, resetCache) {
  5380. const _scopeCache = this._scopeCache;
  5381. let cache = _scopeCache.get(mainScope);
  5382. if (!cache || resetCache) {
  5383. cache = new Map();
  5384. _scopeCache.set(mainScope, cache);
  5385. }
  5386. return cache;
  5387. }
  5388. getOptionScopes(mainScope, keyLists, resetCache) {
  5389. const { options , type } = this;
  5390. const cache = this._cachedScopes(mainScope, resetCache);
  5391. const cached = cache.get(keyLists);
  5392. if (cached) {
  5393. return cached;
  5394. }
  5395. const scopes = new Set();
  5396. keyLists.forEach((keys)=>{
  5397. if (mainScope) {
  5398. scopes.add(mainScope);
  5399. keys.forEach((key)=>addIfFound(scopes, mainScope, key));
  5400. }
  5401. keys.forEach((key)=>addIfFound(scopes, options, key));
  5402. keys.forEach((key)=>addIfFound(scopes, overrides[type] || {}, key));
  5403. keys.forEach((key)=>addIfFound(scopes, defaults, key));
  5404. keys.forEach((key)=>addIfFound(scopes, descriptors, key));
  5405. });
  5406. const array = Array.from(scopes);
  5407. if (array.length === 0) {
  5408. array.push(Object.create(null));
  5409. }
  5410. if (keysCached.has(keyLists)) {
  5411. cache.set(keyLists, array);
  5412. }
  5413. return array;
  5414. }
  5415. chartOptionScopes() {
  5416. const { options , type } = this;
  5417. return [
  5418. options,
  5419. overrides[type] || {},
  5420. defaults.datasets[type] || {},
  5421. {
  5422. type
  5423. },
  5424. defaults,
  5425. descriptors
  5426. ];
  5427. }
  5428. resolveNamedOptions(scopes, names, context, prefixes = [
  5429. ''
  5430. ]) {
  5431. const result = {
  5432. $shared: true
  5433. };
  5434. const { resolver , subPrefixes } = getResolver(this._resolverCache, scopes, prefixes);
  5435. let options = resolver;
  5436. if (needContext(resolver, names)) {
  5437. result.$shared = false;
  5438. context = isFunction(context) ? context() : context;
  5439. const subResolver = this.createResolver(scopes, context, subPrefixes);
  5440. options = _attachContext(resolver, context, subResolver);
  5441. }
  5442. for (const prop of names){
  5443. result[prop] = options[prop];
  5444. }
  5445. return result;
  5446. }
  5447. createResolver(scopes, context, prefixes = [
  5448. ''
  5449. ], descriptorDefaults) {
  5450. const { resolver } = getResolver(this._resolverCache, scopes, prefixes);
  5451. return isObject(context) ? _attachContext(resolver, context, undefined, descriptorDefaults) : resolver;
  5452. }
  5453. }
  5454. function getResolver(resolverCache, scopes, prefixes) {
  5455. let cache = resolverCache.get(scopes);
  5456. if (!cache) {
  5457. cache = new Map();
  5458. resolverCache.set(scopes, cache);
  5459. }
  5460. const cacheKey = prefixes.join();
  5461. let cached = cache.get(cacheKey);
  5462. if (!cached) {
  5463. const resolver = _createResolver(scopes, prefixes);
  5464. cached = {
  5465. resolver,
  5466. subPrefixes: prefixes.filter((p)=>!p.toLowerCase().includes('hover'))
  5467. };
  5468. cache.set(cacheKey, cached);
  5469. }
  5470. return cached;
  5471. }
  5472. const hasFunction = (value)=>isObject(value) && Object.getOwnPropertyNames(value).some((key)=>isFunction(value[key]));
  5473. function needContext(proxy, names) {
  5474. const { isScriptable , isIndexable } = _descriptors(proxy);
  5475. for (const prop of names){
  5476. const scriptable = isScriptable(prop);
  5477. const indexable = isIndexable(prop);
  5478. const value = (indexable || scriptable) && proxy[prop];
  5479. if (scriptable && (isFunction(value) || hasFunction(value)) || indexable && isArray(value)) {
  5480. return true;
  5481. }
  5482. }
  5483. return false;
  5484. }
  5485. var version = "4.4.2";
  5486. const KNOWN_POSITIONS = [
  5487. 'top',
  5488. 'bottom',
  5489. 'left',
  5490. 'right',
  5491. 'chartArea'
  5492. ];
  5493. function positionIsHorizontal(position, axis) {
  5494. return position === 'top' || position === 'bottom' || KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x';
  5495. }
  5496. function compare2Level(l1, l2) {
  5497. return function(a, b) {
  5498. return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1];
  5499. };
  5500. }
  5501. function onAnimationsComplete(context) {
  5502. const chart = context.chart;
  5503. const animationOptions = chart.options.animation;
  5504. chart.notifyPlugins('afterRender');
  5505. callback(animationOptions && animationOptions.onComplete, [
  5506. context
  5507. ], chart);
  5508. }
  5509. function onAnimationProgress(context) {
  5510. const chart = context.chart;
  5511. const animationOptions = chart.options.animation;
  5512. callback(animationOptions && animationOptions.onProgress, [
  5513. context
  5514. ], chart);
  5515. }
  5516. function getCanvas(item) {
  5517. if (_isDomSupported() && typeof item === 'string') {
  5518. item = document.getElementById(item);
  5519. } else if (item && item.length) {
  5520. item = item[0];
  5521. }
  5522. if (item && item.canvas) {
  5523. item = item.canvas;
  5524. }
  5525. return item;
  5526. }
  5527. const instances = {};
  5528. const getChart = (key)=>{
  5529. const canvas = getCanvas(key);
  5530. return Object.values(instances).filter((c)=>c.canvas === canvas).pop();
  5531. };
  5532. function moveNumericKeys(obj, start, move) {
  5533. const keys = Object.keys(obj);
  5534. for (const key of keys){
  5535. const intKey = +key;
  5536. if (intKey >= start) {
  5537. const value = obj[key];
  5538. delete obj[key];
  5539. if (move > 0 || intKey > start) {
  5540. obj[intKey + move] = value;
  5541. }
  5542. }
  5543. }
  5544. }
  5545. function determineLastEvent(e, lastEvent, inChartArea, isClick) {
  5546. if (!inChartArea || e.type === 'mouseout') {
  5547. return null;
  5548. }
  5549. if (isClick) {
  5550. return lastEvent;
  5551. }
  5552. return e;
  5553. }
  5554. function getSizeForArea(scale, chartArea, field) {
  5555. return scale.options.clip ? scale[field] : chartArea[field];
  5556. }
  5557. function getDatasetArea(meta, chartArea) {
  5558. const { xScale , yScale } = meta;
  5559. if (xScale && yScale) {
  5560. return {
  5561. left: getSizeForArea(xScale, chartArea, 'left'),
  5562. right: getSizeForArea(xScale, chartArea, 'right'),
  5563. top: getSizeForArea(yScale, chartArea, 'top'),
  5564. bottom: getSizeForArea(yScale, chartArea, 'bottom')
  5565. };
  5566. }
  5567. return chartArea;
  5568. }
  5569. class Chart {
  5570. static defaults = defaults;
  5571. static instances = instances;
  5572. static overrides = overrides;
  5573. static registry = registry;
  5574. static version = version;
  5575. static getChart = getChart;
  5576. static register(...items) {
  5577. registry.add(...items);
  5578. invalidatePlugins();
  5579. }
  5580. static unregister(...items) {
  5581. registry.remove(...items);
  5582. invalidatePlugins();
  5583. }
  5584. constructor(item, userConfig){
  5585. const config = this.config = new Config(userConfig);
  5586. const initialCanvas = getCanvas(item);
  5587. const existingChart = getChart(initialCanvas);
  5588. if (existingChart) {
  5589. throw new Error('Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + ' must be destroyed before the canvas with ID \'' + existingChart.canvas.id + '\' can be reused.');
  5590. }
  5591. const options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5592. this.platform = new (config.platform || _detectPlatform(initialCanvas))();
  5593. this.platform.updateConfig(config);
  5594. const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);
  5595. const canvas = context && context.canvas;
  5596. const height = canvas && canvas.height;
  5597. const width = canvas && canvas.width;
  5598. this.id = uid();
  5599. this.ctx = context;
  5600. this.canvas = canvas;
  5601. this.width = width;
  5602. this.height = height;
  5603. this._options = options;
  5604. this._aspectRatio = this.aspectRatio;
  5605. this._layers = [];
  5606. this._metasets = [];
  5607. this._stacks = undefined;
  5608. this.boxes = [];
  5609. this.currentDevicePixelRatio = undefined;
  5610. this.chartArea = undefined;
  5611. this._active = [];
  5612. this._lastEvent = undefined;
  5613. this._listeners = {};
  5614. this._responsiveListeners = undefined;
  5615. this._sortedMetasets = [];
  5616. this.scales = {};
  5617. this._plugins = new PluginService();
  5618. this.$proxies = {};
  5619. this._hiddenIndices = {};
  5620. this.attached = false;
  5621. this._animationsDisabled = undefined;
  5622. this.$context = undefined;
  5623. this._doResize = debounce((mode)=>this.update(mode), options.resizeDelay || 0);
  5624. this._dataChanges = [];
  5625. instances[this.id] = this;
  5626. if (!context || !canvas) {
  5627. console.error("Failed to create chart: can't acquire context from the given item");
  5628. return;
  5629. }
  5630. animator.listen(this, 'complete', onAnimationsComplete);
  5631. animator.listen(this, 'progress', onAnimationProgress);
  5632. this._initialize();
  5633. if (this.attached) {
  5634. this.update();
  5635. }
  5636. }
  5637. get aspectRatio() {
  5638. const { options: { aspectRatio , maintainAspectRatio } , width , height , _aspectRatio } = this;
  5639. if (!isNullOrUndef(aspectRatio)) {
  5640. return aspectRatio;
  5641. }
  5642. if (maintainAspectRatio && _aspectRatio) {
  5643. return _aspectRatio;
  5644. }
  5645. return height ? width / height : null;
  5646. }
  5647. get data() {
  5648. return this.config.data;
  5649. }
  5650. set data(data) {
  5651. this.config.data = data;
  5652. }
  5653. get options() {
  5654. return this._options;
  5655. }
  5656. set options(options) {
  5657. this.config.options = options;
  5658. }
  5659. get registry() {
  5660. return registry;
  5661. }
  5662. _initialize() {
  5663. this.notifyPlugins('beforeInit');
  5664. if (this.options.responsive) {
  5665. this.resize();
  5666. } else {
  5667. retinaScale(this, this.options.devicePixelRatio);
  5668. }
  5669. this.bindEvents();
  5670. this.notifyPlugins('afterInit');
  5671. return this;
  5672. }
  5673. clear() {
  5674. clearCanvas(this.canvas, this.ctx);
  5675. return this;
  5676. }
  5677. stop() {
  5678. animator.stop(this);
  5679. return this;
  5680. }
  5681. resize(width, height) {
  5682. if (!animator.running(this)) {
  5683. this._resize(width, height);
  5684. } else {
  5685. this._resizeBeforeDraw = {
  5686. width,
  5687. height
  5688. };
  5689. }
  5690. }
  5691. _resize(width, height) {
  5692. const options = this.options;
  5693. const canvas = this.canvas;
  5694. const aspectRatio = options.maintainAspectRatio && this.aspectRatio;
  5695. const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);
  5696. const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();
  5697. const mode = this.width ? 'resize' : 'attach';
  5698. this.width = newSize.width;
  5699. this.height = newSize.height;
  5700. this._aspectRatio = this.aspectRatio;
  5701. if (!retinaScale(this, newRatio, true)) {
  5702. return;
  5703. }
  5704. this.notifyPlugins('resize', {
  5705. size: newSize
  5706. });
  5707. callback(options.onResize, [
  5708. this,
  5709. newSize
  5710. ], this);
  5711. if (this.attached) {
  5712. if (this._doResize(mode)) {
  5713. this.render();
  5714. }
  5715. }
  5716. }
  5717. ensureScalesHaveIDs() {
  5718. const options = this.options;
  5719. const scalesOptions = options.scales || {};
  5720. each(scalesOptions, (axisOptions, axisID)=>{
  5721. axisOptions.id = axisID;
  5722. });
  5723. }
  5724. buildOrUpdateScales() {
  5725. const options = this.options;
  5726. const scaleOpts = options.scales;
  5727. const scales = this.scales;
  5728. const updated = Object.keys(scales).reduce((obj, id)=>{
  5729. obj[id] = false;
  5730. return obj;
  5731. }, {});
  5732. let items = [];
  5733. if (scaleOpts) {
  5734. items = items.concat(Object.keys(scaleOpts).map((id)=>{
  5735. const scaleOptions = scaleOpts[id];
  5736. const axis = determineAxis(id, scaleOptions);
  5737. const isRadial = axis === 'r';
  5738. const isHorizontal = axis === 'x';
  5739. return {
  5740. options: scaleOptions,
  5741. dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
  5742. dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
  5743. };
  5744. }));
  5745. }
  5746. each(items, (item)=>{
  5747. const scaleOptions = item.options;
  5748. const id = scaleOptions.id;
  5749. const axis = determineAxis(id, scaleOptions);
  5750. const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
  5751. if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
  5752. scaleOptions.position = item.dposition;
  5753. }
  5754. updated[id] = true;
  5755. let scale = null;
  5756. if (id in scales && scales[id].type === scaleType) {
  5757. scale = scales[id];
  5758. } else {
  5759. const scaleClass = registry.getScale(scaleType);
  5760. scale = new scaleClass({
  5761. id,
  5762. type: scaleType,
  5763. ctx: this.ctx,
  5764. chart: this
  5765. });
  5766. scales[scale.id] = scale;
  5767. }
  5768. scale.init(scaleOptions, options);
  5769. });
  5770. each(updated, (hasUpdated, id)=>{
  5771. if (!hasUpdated) {
  5772. delete scales[id];
  5773. }
  5774. });
  5775. each(scales, (scale)=>{
  5776. layouts.configure(this, scale, scale.options);
  5777. layouts.addBox(this, scale);
  5778. });
  5779. }
  5780. _updateMetasets() {
  5781. const metasets = this._metasets;
  5782. const numData = this.data.datasets.length;
  5783. const numMeta = metasets.length;
  5784. metasets.sort((a, b)=>a.index - b.index);
  5785. if (numMeta > numData) {
  5786. for(let i = numData; i < numMeta; ++i){
  5787. this._destroyDatasetMeta(i);
  5788. }
  5789. metasets.splice(numData, numMeta - numData);
  5790. }
  5791. this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
  5792. }
  5793. _removeUnreferencedMetasets() {
  5794. const { _metasets: metasets , data: { datasets } } = this;
  5795. if (metasets.length > datasets.length) {
  5796. delete this._stacks;
  5797. }
  5798. metasets.forEach((meta, index)=>{
  5799. if (datasets.filter((x)=>x === meta._dataset).length === 0) {
  5800. this._destroyDatasetMeta(index);
  5801. }
  5802. });
  5803. }
  5804. buildOrUpdateControllers() {
  5805. const newControllers = [];
  5806. const datasets = this.data.datasets;
  5807. let i, ilen;
  5808. this._removeUnreferencedMetasets();
  5809. for(i = 0, ilen = datasets.length; i < ilen; i++){
  5810. const dataset = datasets[i];
  5811. let meta = this.getDatasetMeta(i);
  5812. const type = dataset.type || this.config.type;
  5813. if (meta.type && meta.type !== type) {
  5814. this._destroyDatasetMeta(i);
  5815. meta = this.getDatasetMeta(i);
  5816. }
  5817. meta.type = type;
  5818. meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);
  5819. meta.order = dataset.order || 0;
  5820. meta.index = i;
  5821. meta.label = '' + dataset.label;
  5822. meta.visible = this.isDatasetVisible(i);
  5823. if (meta.controller) {
  5824. meta.controller.updateIndex(i);
  5825. meta.controller.linkScales();
  5826. } else {
  5827. const ControllerClass = registry.getController(type);
  5828. const { datasetElementType , dataElementType } = defaults.datasets[type];
  5829. Object.assign(ControllerClass, {
  5830. dataElementType: registry.getElement(dataElementType),
  5831. datasetElementType: datasetElementType && registry.getElement(datasetElementType)
  5832. });
  5833. meta.controller = new ControllerClass(this, i);
  5834. newControllers.push(meta.controller);
  5835. }
  5836. }
  5837. this._updateMetasets();
  5838. return newControllers;
  5839. }
  5840. _resetElements() {
  5841. each(this.data.datasets, (dataset, datasetIndex)=>{
  5842. this.getDatasetMeta(datasetIndex).controller.reset();
  5843. }, this);
  5844. }
  5845. reset() {
  5846. this._resetElements();
  5847. this.notifyPlugins('reset');
  5848. }
  5849. update(mode) {
  5850. const config = this.config;
  5851. config.update();
  5852. const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5853. const animsDisabled = this._animationsDisabled = !options.animation;
  5854. this._updateScales();
  5855. this._checkEventBindings();
  5856. this._updateHiddenIndices();
  5857. this._plugins.invalidate();
  5858. if (this.notifyPlugins('beforeUpdate', {
  5859. mode,
  5860. cancelable: true
  5861. }) === false) {
  5862. return;
  5863. }
  5864. const newControllers = this.buildOrUpdateControllers();
  5865. this.notifyPlugins('beforeElementsUpdate');
  5866. let minPadding = 0;
  5867. for(let i = 0, ilen = this.data.datasets.length; i < ilen; i++){
  5868. const { controller } = this.getDatasetMeta(i);
  5869. const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
  5870. controller.buildOrUpdateElements(reset);
  5871. minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
  5872. }
  5873. minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;
  5874. this._updateLayout(minPadding);
  5875. if (!animsDisabled) {
  5876. each(newControllers, (controller)=>{
  5877. controller.reset();
  5878. });
  5879. }
  5880. this._updateDatasets(mode);
  5881. this.notifyPlugins('afterUpdate', {
  5882. mode
  5883. });
  5884. this._layers.sort(compare2Level('z', '_idx'));
  5885. const { _active , _lastEvent } = this;
  5886. if (_lastEvent) {
  5887. this._eventHandler(_lastEvent, true);
  5888. } else if (_active.length) {
  5889. this._updateHoverStyles(_active, _active, true);
  5890. }
  5891. this.render();
  5892. }
  5893. _updateScales() {
  5894. each(this.scales, (scale)=>{
  5895. layouts.removeBox(this, scale);
  5896. });
  5897. this.ensureScalesHaveIDs();
  5898. this.buildOrUpdateScales();
  5899. }
  5900. _checkEventBindings() {
  5901. const options = this.options;
  5902. const existingEvents = new Set(Object.keys(this._listeners));
  5903. const newEvents = new Set(options.events);
  5904. if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {
  5905. this.unbindEvents();
  5906. this.bindEvents();
  5907. }
  5908. }
  5909. _updateHiddenIndices() {
  5910. const { _hiddenIndices } = this;
  5911. const changes = this._getUniformDataChanges() || [];
  5912. for (const { method , start , count } of changes){
  5913. const move = method === '_removeElements' ? -count : count;
  5914. moveNumericKeys(_hiddenIndices, start, move);
  5915. }
  5916. }
  5917. _getUniformDataChanges() {
  5918. const _dataChanges = this._dataChanges;
  5919. if (!_dataChanges || !_dataChanges.length) {
  5920. return;
  5921. }
  5922. this._dataChanges = [];
  5923. const datasetCount = this.data.datasets.length;
  5924. const makeSet = (idx)=>new Set(_dataChanges.filter((c)=>c[0] === idx).map((c, i)=>i + ',' + c.splice(1).join(',')));
  5925. const changeSet = makeSet(0);
  5926. for(let i = 1; i < datasetCount; i++){
  5927. if (!setsEqual(changeSet, makeSet(i))) {
  5928. return;
  5929. }
  5930. }
  5931. return Array.from(changeSet).map((c)=>c.split(',')).map((a)=>({
  5932. method: a[1],
  5933. start: +a[2],
  5934. count: +a[3]
  5935. }));
  5936. }
  5937. _updateLayout(minPadding) {
  5938. if (this.notifyPlugins('beforeLayout', {
  5939. cancelable: true
  5940. }) === false) {
  5941. return;
  5942. }
  5943. layouts.update(this, this.width, this.height, minPadding);
  5944. const area = this.chartArea;
  5945. const noArea = area.width <= 0 || area.height <= 0;
  5946. this._layers = [];
  5947. each(this.boxes, (box)=>{
  5948. if (noArea && box.position === 'chartArea') {
  5949. return;
  5950. }
  5951. if (box.configure) {
  5952. box.configure();
  5953. }
  5954. this._layers.push(...box._layers());
  5955. }, this);
  5956. this._layers.forEach((item, index)=>{
  5957. item._idx = index;
  5958. });
  5959. this.notifyPlugins('afterLayout');
  5960. }
  5961. _updateDatasets(mode) {
  5962. if (this.notifyPlugins('beforeDatasetsUpdate', {
  5963. mode,
  5964. cancelable: true
  5965. }) === false) {
  5966. return;
  5967. }
  5968. for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  5969. this.getDatasetMeta(i).controller.configure();
  5970. }
  5971. for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  5972. this._updateDataset(i, isFunction(mode) ? mode({
  5973. datasetIndex: i
  5974. }) : mode);
  5975. }
  5976. this.notifyPlugins('afterDatasetsUpdate', {
  5977. mode
  5978. });
  5979. }
  5980. _updateDataset(index, mode) {
  5981. const meta = this.getDatasetMeta(index);
  5982. const args = {
  5983. meta,
  5984. index,
  5985. mode,
  5986. cancelable: true
  5987. };
  5988. if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {
  5989. return;
  5990. }
  5991. meta.controller._update(mode);
  5992. args.cancelable = false;
  5993. this.notifyPlugins('afterDatasetUpdate', args);
  5994. }
  5995. render() {
  5996. if (this.notifyPlugins('beforeRender', {
  5997. cancelable: true
  5998. }) === false) {
  5999. return;
  6000. }
  6001. if (animator.has(this)) {
  6002. if (this.attached && !animator.running(this)) {
  6003. animator.start(this);
  6004. }
  6005. } else {
  6006. this.draw();
  6007. onAnimationsComplete({
  6008. chart: this
  6009. });
  6010. }
  6011. }
  6012. draw() {
  6013. let i;
  6014. if (this._resizeBeforeDraw) {
  6015. const { width , height } = this._resizeBeforeDraw;
  6016. this._resize(width, height);
  6017. this._resizeBeforeDraw = null;
  6018. }
  6019. this.clear();
  6020. if (this.width <= 0 || this.height <= 0) {
  6021. return;
  6022. }
  6023. if (this.notifyPlugins('beforeDraw', {
  6024. cancelable: true
  6025. }) === false) {
  6026. return;
  6027. }
  6028. const layers = this._layers;
  6029. for(i = 0; i < layers.length && layers[i].z <= 0; ++i){
  6030. layers[i].draw(this.chartArea);
  6031. }
  6032. this._drawDatasets();
  6033. for(; i < layers.length; ++i){
  6034. layers[i].draw(this.chartArea);
  6035. }
  6036. this.notifyPlugins('afterDraw');
  6037. }
  6038. _getSortedDatasetMetas(filterVisible) {
  6039. const metasets = this._sortedMetasets;
  6040. const result = [];
  6041. let i, ilen;
  6042. for(i = 0, ilen = metasets.length; i < ilen; ++i){
  6043. const meta = metasets[i];
  6044. if (!filterVisible || meta.visible) {
  6045. result.push(meta);
  6046. }
  6047. }
  6048. return result;
  6049. }
  6050. getSortedVisibleDatasetMetas() {
  6051. return this._getSortedDatasetMetas(true);
  6052. }
  6053. _drawDatasets() {
  6054. if (this.notifyPlugins('beforeDatasetsDraw', {
  6055. cancelable: true
  6056. }) === false) {
  6057. return;
  6058. }
  6059. const metasets = this.getSortedVisibleDatasetMetas();
  6060. for(let i = metasets.length - 1; i >= 0; --i){
  6061. this._drawDataset(metasets[i]);
  6062. }
  6063. this.notifyPlugins('afterDatasetsDraw');
  6064. }
  6065. _drawDataset(meta) {
  6066. const ctx = this.ctx;
  6067. const clip = meta._clip;
  6068. const useClip = !clip.disabled;
  6069. const area = getDatasetArea(meta, this.chartArea);
  6070. const args = {
  6071. meta,
  6072. index: meta.index,
  6073. cancelable: true
  6074. };
  6075. if (this.notifyPlugins('beforeDatasetDraw', args) === false) {
  6076. return;
  6077. }
  6078. if (useClip) {
  6079. clipArea(ctx, {
  6080. left: clip.left === false ? 0 : area.left - clip.left,
  6081. right: clip.right === false ? this.width : area.right + clip.right,
  6082. top: clip.top === false ? 0 : area.top - clip.top,
  6083. bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom
  6084. });
  6085. }
  6086. meta.controller.draw();
  6087. if (useClip) {
  6088. unclipArea(ctx);
  6089. }
  6090. args.cancelable = false;
  6091. this.notifyPlugins('afterDatasetDraw', args);
  6092. }
  6093. isPointInArea(point) {
  6094. return _isPointInArea(point, this.chartArea, this._minPadding);
  6095. }
  6096. getElementsAtEventForMode(e, mode, options, useFinalPosition) {
  6097. const method = Interaction.modes[mode];
  6098. if (typeof method === 'function') {
  6099. return method(this, e, options, useFinalPosition);
  6100. }
  6101. return [];
  6102. }
  6103. getDatasetMeta(datasetIndex) {
  6104. const dataset = this.data.datasets[datasetIndex];
  6105. const metasets = this._metasets;
  6106. let meta = metasets.filter((x)=>x && x._dataset === dataset).pop();
  6107. if (!meta) {
  6108. meta = {
  6109. type: null,
  6110. data: [],
  6111. dataset: null,
  6112. controller: null,
  6113. hidden: null,
  6114. xAxisID: null,
  6115. yAxisID: null,
  6116. order: dataset && dataset.order || 0,
  6117. index: datasetIndex,
  6118. _dataset: dataset,
  6119. _parsed: [],
  6120. _sorted: false
  6121. };
  6122. metasets.push(meta);
  6123. }
  6124. return meta;
  6125. }
  6126. getContext() {
  6127. return this.$context || (this.$context = createContext(null, {
  6128. chart: this,
  6129. type: 'chart'
  6130. }));
  6131. }
  6132. getVisibleDatasetCount() {
  6133. return this.getSortedVisibleDatasetMetas().length;
  6134. }
  6135. isDatasetVisible(datasetIndex) {
  6136. const dataset = this.data.datasets[datasetIndex];
  6137. if (!dataset) {
  6138. return false;
  6139. }
  6140. const meta = this.getDatasetMeta(datasetIndex);
  6141. return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
  6142. }
  6143. setDatasetVisibility(datasetIndex, visible) {
  6144. const meta = this.getDatasetMeta(datasetIndex);
  6145. meta.hidden = !visible;
  6146. }
  6147. toggleDataVisibility(index) {
  6148. this._hiddenIndices[index] = !this._hiddenIndices[index];
  6149. }
  6150. getDataVisibility(index) {
  6151. return !this._hiddenIndices[index];
  6152. }
  6153. _updateVisibility(datasetIndex, dataIndex, visible) {
  6154. const mode = visible ? 'show' : 'hide';
  6155. const meta = this.getDatasetMeta(datasetIndex);
  6156. const anims = meta.controller._resolveAnimations(undefined, mode);
  6157. if (defined(dataIndex)) {
  6158. meta.data[dataIndex].hidden = !visible;
  6159. this.update();
  6160. } else {
  6161. this.setDatasetVisibility(datasetIndex, visible);
  6162. anims.update(meta, {
  6163. visible
  6164. });
  6165. this.update((ctx)=>ctx.datasetIndex === datasetIndex ? mode : undefined);
  6166. }
  6167. }
  6168. hide(datasetIndex, dataIndex) {
  6169. this._updateVisibility(datasetIndex, dataIndex, false);
  6170. }
  6171. show(datasetIndex, dataIndex) {
  6172. this._updateVisibility(datasetIndex, dataIndex, true);
  6173. }
  6174. _destroyDatasetMeta(datasetIndex) {
  6175. const meta = this._metasets[datasetIndex];
  6176. if (meta && meta.controller) {
  6177. meta.controller._destroy();
  6178. }
  6179. delete this._metasets[datasetIndex];
  6180. }
  6181. _stop() {
  6182. let i, ilen;
  6183. this.stop();
  6184. animator.remove(this);
  6185. for(i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  6186. this._destroyDatasetMeta(i);
  6187. }
  6188. }
  6189. destroy() {
  6190. this.notifyPlugins('beforeDestroy');
  6191. const { canvas , ctx } = this;
  6192. this._stop();
  6193. this.config.clearCache();
  6194. if (canvas) {
  6195. this.unbindEvents();
  6196. clearCanvas(canvas, ctx);
  6197. this.platform.releaseContext(ctx);
  6198. this.canvas = null;
  6199. this.ctx = null;
  6200. }
  6201. delete instances[this.id];
  6202. this.notifyPlugins('afterDestroy');
  6203. }
  6204. toBase64Image(...args) {
  6205. return this.canvas.toDataURL(...args);
  6206. }
  6207. bindEvents() {
  6208. this.bindUserEvents();
  6209. if (this.options.responsive) {
  6210. this.bindResponsiveEvents();
  6211. } else {
  6212. this.attached = true;
  6213. }
  6214. }
  6215. bindUserEvents() {
  6216. const listeners = this._listeners;
  6217. const platform = this.platform;
  6218. const _add = (type, listener)=>{
  6219. platform.addEventListener(this, type, listener);
  6220. listeners[type] = listener;
  6221. };
  6222. const listener = (e, x, y)=>{
  6223. e.offsetX = x;
  6224. e.offsetY = y;
  6225. this._eventHandler(e);
  6226. };
  6227. each(this.options.events, (type)=>_add(type, listener));
  6228. }
  6229. bindResponsiveEvents() {
  6230. if (!this._responsiveListeners) {
  6231. this._responsiveListeners = {};
  6232. }
  6233. const listeners = this._responsiveListeners;
  6234. const platform = this.platform;
  6235. const _add = (type, listener)=>{
  6236. platform.addEventListener(this, type, listener);
  6237. listeners[type] = listener;
  6238. };
  6239. const _remove = (type, listener)=>{
  6240. if (listeners[type]) {
  6241. platform.removeEventListener(this, type, listener);
  6242. delete listeners[type];
  6243. }
  6244. };
  6245. const listener = (width, height)=>{
  6246. if (this.canvas) {
  6247. this.resize(width, height);
  6248. }
  6249. };
  6250. let detached;
  6251. const attached = ()=>{
  6252. _remove('attach', attached);
  6253. this.attached = true;
  6254. this.resize();
  6255. _add('resize', listener);
  6256. _add('detach', detached);
  6257. };
  6258. detached = ()=>{
  6259. this.attached = false;
  6260. _remove('resize', listener);
  6261. this._stop();
  6262. this._resize(0, 0);
  6263. _add('attach', attached);
  6264. };
  6265. if (platform.isAttached(this.canvas)) {
  6266. attached();
  6267. } else {
  6268. detached();
  6269. }
  6270. }
  6271. unbindEvents() {
  6272. each(this._listeners, (listener, type)=>{
  6273. this.platform.removeEventListener(this, type, listener);
  6274. });
  6275. this._listeners = {};
  6276. each(this._responsiveListeners, (listener, type)=>{
  6277. this.platform.removeEventListener(this, type, listener);
  6278. });
  6279. this._responsiveListeners = undefined;
  6280. }
  6281. updateHoverStyle(items, mode, enabled) {
  6282. const prefix = enabled ? 'set' : 'remove';
  6283. let meta, item, i, ilen;
  6284. if (mode === 'dataset') {
  6285. meta = this.getDatasetMeta(items[0].datasetIndex);
  6286. meta.controller['_' + prefix + 'DatasetHoverStyle']();
  6287. }
  6288. for(i = 0, ilen = items.length; i < ilen; ++i){
  6289. item = items[i];
  6290. const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
  6291. if (controller) {
  6292. controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
  6293. }
  6294. }
  6295. }
  6296. getActiveElements() {
  6297. return this._active || [];
  6298. }
  6299. setActiveElements(activeElements) {
  6300. const lastActive = this._active || [];
  6301. const active = activeElements.map(({ datasetIndex , index })=>{
  6302. const meta = this.getDatasetMeta(datasetIndex);
  6303. if (!meta) {
  6304. throw new Error('No dataset found at index ' + datasetIndex);
  6305. }
  6306. return {
  6307. datasetIndex,
  6308. element: meta.data[index],
  6309. index
  6310. };
  6311. });
  6312. const changed = !_elementsEqual(active, lastActive);
  6313. if (changed) {
  6314. this._active = active;
  6315. this._lastEvent = null;
  6316. this._updateHoverStyles(active, lastActive);
  6317. }
  6318. }
  6319. notifyPlugins(hook, args, filter) {
  6320. return this._plugins.notify(this, hook, args, filter);
  6321. }
  6322. isPluginEnabled(pluginId) {
  6323. return this._plugins._cache.filter((p)=>p.plugin.id === pluginId).length === 1;
  6324. }
  6325. _updateHoverStyles(active, lastActive, replay) {
  6326. const hoverOptions = this.options.hover;
  6327. const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.datasetIndex === y.datasetIndex && x.index === y.index));
  6328. const deactivated = diff(lastActive, active);
  6329. const activated = replay ? active : diff(active, lastActive);
  6330. if (deactivated.length) {
  6331. this.updateHoverStyle(deactivated, hoverOptions.mode, false);
  6332. }
  6333. if (activated.length && hoverOptions.mode) {
  6334. this.updateHoverStyle(activated, hoverOptions.mode, true);
  6335. }
  6336. }
  6337. _eventHandler(e, replay) {
  6338. const args = {
  6339. event: e,
  6340. replay,
  6341. cancelable: true,
  6342. inChartArea: this.isPointInArea(e)
  6343. };
  6344. const eventFilter = (plugin)=>(plugin.options.events || this.options.events).includes(e.native.type);
  6345. if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {
  6346. return;
  6347. }
  6348. const changed = this._handleEvent(e, replay, args.inChartArea);
  6349. args.cancelable = false;
  6350. this.notifyPlugins('afterEvent', args, eventFilter);
  6351. if (changed || args.changed) {
  6352. this.render();
  6353. }
  6354. return this;
  6355. }
  6356. _handleEvent(e, replay, inChartArea) {
  6357. const { _active: lastActive = [] , options } = this;
  6358. const useFinalPosition = replay;
  6359. const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);
  6360. const isClick = _isClickEvent(e);
  6361. const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);
  6362. if (inChartArea) {
  6363. this._lastEvent = null;
  6364. callback(options.onHover, [
  6365. e,
  6366. active,
  6367. this
  6368. ], this);
  6369. if (isClick) {
  6370. callback(options.onClick, [
  6371. e,
  6372. active,
  6373. this
  6374. ], this);
  6375. }
  6376. }
  6377. const changed = !_elementsEqual(active, lastActive);
  6378. if (changed || replay) {
  6379. this._active = active;
  6380. this._updateHoverStyles(active, lastActive, replay);
  6381. }
  6382. this._lastEvent = lastEvent;
  6383. return changed;
  6384. }
  6385. _getActiveElements(e, lastActive, inChartArea, useFinalPosition) {
  6386. if (e.type === 'mouseout') {
  6387. return [];
  6388. }
  6389. if (!inChartArea) {
  6390. return lastActive;
  6391. }
  6392. const hoverOptions = this.options.hover;
  6393. return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
  6394. }
  6395. }
  6396. function invalidatePlugins() {
  6397. return each(Chart.instances, (chart)=>chart._plugins.invalidate());
  6398. }
  6399. function clipArc(ctx, element, endAngle) {
  6400. const { startAngle , pixelMargin , x , y , outerRadius , innerRadius } = element;
  6401. let angleMargin = pixelMargin / outerRadius;
  6402. // Draw an inner border by clipping the arc and drawing a double-width border
  6403. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  6404. ctx.beginPath();
  6405. ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  6406. if (innerRadius > pixelMargin) {
  6407. angleMargin = pixelMargin / innerRadius;
  6408. ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
  6409. } else {
  6410. ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);
  6411. }
  6412. ctx.closePath();
  6413. ctx.clip();
  6414. }
  6415. function toRadiusCorners(value) {
  6416. return _readValueToProps(value, [
  6417. 'outerStart',
  6418. 'outerEnd',
  6419. 'innerStart',
  6420. 'innerEnd'
  6421. ]);
  6422. }
  6423. /**
  6424. * Parse border radius from the provided options
  6425. */ function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
  6426. const o = toRadiusCorners(arc.options.borderRadius);
  6427. const halfThickness = (outerRadius - innerRadius) / 2;
  6428. const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
  6429. // Outer limits are complicated. We want to compute the available angular distance at
  6430. // a radius of outerRadius - borderRadius because for small angular distances, this term limits.
  6431. // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners.
  6432. //
  6433. // If the borderRadius is large, that value can become negative.
  6434. // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius
  6435. // we know that the thickness term will dominate and compute the limits at that point
  6436. const computeOuterLimit = (val)=>{
  6437. const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
  6438. return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
  6439. };
  6440. return {
  6441. outerStart: computeOuterLimit(o.outerStart),
  6442. outerEnd: computeOuterLimit(o.outerEnd),
  6443. innerStart: _limitValue(o.innerStart, 0, innerLimit),
  6444. innerEnd: _limitValue(o.innerEnd, 0, innerLimit)
  6445. };
  6446. }
  6447. /**
  6448. * Convert (r, 𝜃) to (x, y)
  6449. */ function rThetaToXY(r, theta, x, y) {
  6450. return {
  6451. x: x + r * Math.cos(theta),
  6452. y: y + r * Math.sin(theta)
  6453. };
  6454. }
  6455. /**
  6456. * Path the arc, respecting border radius by separating into left and right halves.
  6457. *
  6458. * Start End
  6459. *
  6460. * 1--->a--->2 Outer
  6461. * / \
  6462. * 8 3
  6463. * | |
  6464. * | |
  6465. * 7 4
  6466. * \ /
  6467. * 6<---b<---5 Inner
  6468. */ function pathArc(ctx, element, offset, spacing, end, circular) {
  6469. const { x , y , startAngle: start , pixelMargin , innerRadius: innerR } = element;
  6470. const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);
  6471. const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;
  6472. let spacingOffset = 0;
  6473. const alpha = end - start;
  6474. if (spacing) {
  6475. // When spacing is present, it is the same for all items
  6476. // So we adjust the start and end angle of the arc such that
  6477. // the distance is the same as it would be without the spacing
  6478. const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;
  6479. const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;
  6480. const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;
  6481. const adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha;
  6482. spacingOffset = (alpha - adjustedAngle) / 2;
  6483. }
  6484. const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;
  6485. const angleOffset = (alpha - beta) / 2;
  6486. const startAngle = start + angleOffset + spacingOffset;
  6487. const endAngle = end - angleOffset - spacingOffset;
  6488. const { outerStart , outerEnd , innerStart , innerEnd } = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
  6489. const outerStartAdjustedRadius = outerRadius - outerStart;
  6490. const outerEndAdjustedRadius = outerRadius - outerEnd;
  6491. const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
  6492. const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
  6493. const innerStartAdjustedRadius = innerRadius + innerStart;
  6494. const innerEndAdjustedRadius = innerRadius + innerEnd;
  6495. const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
  6496. const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
  6497. ctx.beginPath();
  6498. if (circular) {
  6499. // The first arc segments from point 1 to point a to point 2
  6500. const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2;
  6501. ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle);
  6502. ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle);
  6503. // The corner segment from point 2 to point 3
  6504. if (outerEnd > 0) {
  6505. const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
  6506. ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);
  6507. }
  6508. // The line from point 3 to point 4
  6509. const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
  6510. ctx.lineTo(p4.x, p4.y);
  6511. // The corner segment from point 4 to point 5
  6512. if (innerEnd > 0) {
  6513. const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
  6514. ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);
  6515. }
  6516. // The inner arc from point 5 to point b to point 6
  6517. const innerMidAdjustedAngle = (endAngle - innerEnd / innerRadius + (startAngle + innerStart / innerRadius)) / 2;
  6518. ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, innerMidAdjustedAngle, true);
  6519. ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + innerStart / innerRadius, true);
  6520. // The corner segment from point 6 to point 7
  6521. if (innerStart > 0) {
  6522. const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
  6523. ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);
  6524. }
  6525. // The line from point 7 to point 8
  6526. const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
  6527. ctx.lineTo(p8.x, p8.y);
  6528. // The corner segment from point 8 to point 1
  6529. if (outerStart > 0) {
  6530. const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
  6531. ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);
  6532. }
  6533. } else {
  6534. ctx.moveTo(x, y);
  6535. const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x;
  6536. const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y;
  6537. ctx.lineTo(outerStartX, outerStartY);
  6538. const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x;
  6539. const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y;
  6540. ctx.lineTo(outerEndX, outerEndY);
  6541. }
  6542. ctx.closePath();
  6543. }
  6544. function drawArc(ctx, element, offset, spacing, circular) {
  6545. const { fullCircles , startAngle , circumference } = element;
  6546. let endAngle = element.endAngle;
  6547. if (fullCircles) {
  6548. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6549. for(let i = 0; i < fullCircles; ++i){
  6550. ctx.fill();
  6551. }
  6552. if (!isNaN(circumference)) {
  6553. endAngle = startAngle + (circumference % TAU || TAU);
  6554. }
  6555. }
  6556. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6557. ctx.fill();
  6558. return endAngle;
  6559. }
  6560. function drawBorder(ctx, element, offset, spacing, circular) {
  6561. const { fullCircles , startAngle , circumference , options } = element;
  6562. const { borderWidth , borderJoinStyle , borderDash , borderDashOffset } = options;
  6563. const inner = options.borderAlign === 'inner';
  6564. if (!borderWidth) {
  6565. return;
  6566. }
  6567. ctx.setLineDash(borderDash || []);
  6568. ctx.lineDashOffset = borderDashOffset;
  6569. if (inner) {
  6570. ctx.lineWidth = borderWidth * 2;
  6571. ctx.lineJoin = borderJoinStyle || 'round';
  6572. } else {
  6573. ctx.lineWidth = borderWidth;
  6574. ctx.lineJoin = borderJoinStyle || 'bevel';
  6575. }
  6576. let endAngle = element.endAngle;
  6577. if (fullCircles) {
  6578. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6579. for(let i = 0; i < fullCircles; ++i){
  6580. ctx.stroke();
  6581. }
  6582. if (!isNaN(circumference)) {
  6583. endAngle = startAngle + (circumference % TAU || TAU);
  6584. }
  6585. }
  6586. if (inner) {
  6587. clipArc(ctx, element, endAngle);
  6588. }
  6589. if (!fullCircles) {
  6590. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6591. ctx.stroke();
  6592. }
  6593. }
  6594. class ArcElement extends Element {
  6595. static id = 'arc';
  6596. static defaults = {
  6597. borderAlign: 'center',
  6598. borderColor: '#fff',
  6599. borderDash: [],
  6600. borderDashOffset: 0,
  6601. borderJoinStyle: undefined,
  6602. borderRadius: 0,
  6603. borderWidth: 2,
  6604. offset: 0,
  6605. spacing: 0,
  6606. angle: undefined,
  6607. circular: true
  6608. };
  6609. static defaultRoutes = {
  6610. backgroundColor: 'backgroundColor'
  6611. };
  6612. static descriptors = {
  6613. _scriptable: true,
  6614. _indexable: (name)=>name !== 'borderDash'
  6615. };
  6616. circumference;
  6617. endAngle;
  6618. fullCircles;
  6619. innerRadius;
  6620. outerRadius;
  6621. pixelMargin;
  6622. startAngle;
  6623. constructor(cfg){
  6624. super();
  6625. this.options = undefined;
  6626. this.circumference = undefined;
  6627. this.startAngle = undefined;
  6628. this.endAngle = undefined;
  6629. this.innerRadius = undefined;
  6630. this.outerRadius = undefined;
  6631. this.pixelMargin = 0;
  6632. this.fullCircles = 0;
  6633. if (cfg) {
  6634. Object.assign(this, cfg);
  6635. }
  6636. }
  6637. inRange(chartX, chartY, useFinalPosition) {
  6638. const point = this.getProps([
  6639. 'x',
  6640. 'y'
  6641. ], useFinalPosition);
  6642. const { angle , distance } = getAngleFromPoint(point, {
  6643. x: chartX,
  6644. y: chartY
  6645. });
  6646. const { startAngle , endAngle , innerRadius , outerRadius , circumference } = this.getProps([
  6647. 'startAngle',
  6648. 'endAngle',
  6649. 'innerRadius',
  6650. 'outerRadius',
  6651. 'circumference'
  6652. ], useFinalPosition);
  6653. const rAdjust = (this.options.spacing + this.options.borderWidth) / 2;
  6654. const _circumference = valueOrDefault(circumference, endAngle - startAngle);
  6655. const betweenAngles = _circumference >= TAU || _angleBetween(angle, startAngle, endAngle);
  6656. const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust);
  6657. return betweenAngles && withinRadius;
  6658. }
  6659. getCenterPoint(useFinalPosition) {
  6660. const { x , y , startAngle , endAngle , innerRadius , outerRadius } = this.getProps([
  6661. 'x',
  6662. 'y',
  6663. 'startAngle',
  6664. 'endAngle',
  6665. 'innerRadius',
  6666. 'outerRadius'
  6667. ], useFinalPosition);
  6668. const { offset , spacing } = this.options;
  6669. const halfAngle = (startAngle + endAngle) / 2;
  6670. const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;
  6671. return {
  6672. x: x + Math.cos(halfAngle) * halfRadius,
  6673. y: y + Math.sin(halfAngle) * halfRadius
  6674. };
  6675. }
  6676. tooltipPosition(useFinalPosition) {
  6677. return this.getCenterPoint(useFinalPosition);
  6678. }
  6679. draw(ctx) {
  6680. const { options , circumference } = this;
  6681. const offset = (options.offset || 0) / 4;
  6682. const spacing = (options.spacing || 0) / 2;
  6683. const circular = options.circular;
  6684. this.pixelMargin = options.borderAlign === 'inner' ? 0.33 : 0;
  6685. this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;
  6686. if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) {
  6687. return;
  6688. }
  6689. ctx.save();
  6690. const halfAngle = (this.startAngle + this.endAngle) / 2;
  6691. ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset);
  6692. const fix = 1 - Math.sin(Math.min(PI, circumference || 0));
  6693. const radiusOffset = offset * fix;
  6694. ctx.fillStyle = options.backgroundColor;
  6695. ctx.strokeStyle = options.borderColor;
  6696. drawArc(ctx, this, radiusOffset, spacing, circular);
  6697. drawBorder(ctx, this, radiusOffset, spacing, circular);
  6698. ctx.restore();
  6699. }
  6700. }
  6701. function setStyle(ctx, options, style = options) {
  6702. ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);
  6703. ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));
  6704. ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);
  6705. ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
  6706. ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);
  6707. ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);
  6708. }
  6709. function lineTo(ctx, previous, target) {
  6710. ctx.lineTo(target.x, target.y);
  6711. }
  6712. function getLineMethod(options) {
  6713. if (options.stepped) {
  6714. return _steppedLineTo;
  6715. }
  6716. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6717. return _bezierCurveTo;
  6718. }
  6719. return lineTo;
  6720. }
  6721. function pathVars(points, segment, params = {}) {
  6722. const count = points.length;
  6723. const { start: paramsStart = 0 , end: paramsEnd = count - 1 } = params;
  6724. const { start: segmentStart , end: segmentEnd } = segment;
  6725. const start = Math.max(paramsStart, segmentStart);
  6726. const end = Math.min(paramsEnd, segmentEnd);
  6727. const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
  6728. return {
  6729. count,
  6730. start,
  6731. loop: segment.loop,
  6732. ilen: end < start && !outside ? count + end - start : end - start
  6733. };
  6734. }
  6735. function pathSegment(ctx, line, segment, params) {
  6736. const { points , options } = line;
  6737. const { count , start , loop , ilen } = pathVars(points, segment, params);
  6738. const lineMethod = getLineMethod(options);
  6739. let { move =true , reverse } = params || {};
  6740. let i, point, prev;
  6741. for(i = 0; i <= ilen; ++i){
  6742. point = points[(start + (reverse ? ilen - i : i)) % count];
  6743. if (point.skip) {
  6744. continue;
  6745. } else if (move) {
  6746. ctx.moveTo(point.x, point.y);
  6747. move = false;
  6748. } else {
  6749. lineMethod(ctx, prev, point, reverse, options.stepped);
  6750. }
  6751. prev = point;
  6752. }
  6753. if (loop) {
  6754. point = points[(start + (reverse ? ilen : 0)) % count];
  6755. lineMethod(ctx, prev, point, reverse, options.stepped);
  6756. }
  6757. return !!loop;
  6758. }
  6759. function fastPathSegment(ctx, line, segment, params) {
  6760. const points = line.points;
  6761. const { count , start , ilen } = pathVars(points, segment, params);
  6762. const { move =true , reverse } = params || {};
  6763. let avgX = 0;
  6764. let countX = 0;
  6765. let i, point, prevX, minY, maxY, lastY;
  6766. const pointIndex = (index)=>(start + (reverse ? ilen - index : index)) % count;
  6767. const drawX = ()=>{
  6768. if (minY !== maxY) {
  6769. ctx.lineTo(avgX, maxY);
  6770. ctx.lineTo(avgX, minY);
  6771. ctx.lineTo(avgX, lastY);
  6772. }
  6773. };
  6774. if (move) {
  6775. point = points[pointIndex(0)];
  6776. ctx.moveTo(point.x, point.y);
  6777. }
  6778. for(i = 0; i <= ilen; ++i){
  6779. point = points[pointIndex(i)];
  6780. if (point.skip) {
  6781. continue;
  6782. }
  6783. const x = point.x;
  6784. const y = point.y;
  6785. const truncX = x | 0;
  6786. if (truncX === prevX) {
  6787. if (y < minY) {
  6788. minY = y;
  6789. } else if (y > maxY) {
  6790. maxY = y;
  6791. }
  6792. avgX = (countX * avgX + x) / ++countX;
  6793. } else {
  6794. drawX();
  6795. ctx.lineTo(x, y);
  6796. prevX = truncX;
  6797. countX = 0;
  6798. minY = maxY = y;
  6799. }
  6800. lastY = y;
  6801. }
  6802. drawX();
  6803. }
  6804. function _getSegmentMethod(line) {
  6805. const opts = line.options;
  6806. const borderDash = opts.borderDash && opts.borderDash.length;
  6807. const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
  6808. return useFastPath ? fastPathSegment : pathSegment;
  6809. }
  6810. function _getInterpolationMethod(options) {
  6811. if (options.stepped) {
  6812. return _steppedInterpolation;
  6813. }
  6814. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6815. return _bezierInterpolation;
  6816. }
  6817. return _pointInLine;
  6818. }
  6819. function strokePathWithCache(ctx, line, start, count) {
  6820. let path = line._path;
  6821. if (!path) {
  6822. path = line._path = new Path2D();
  6823. if (line.path(path, start, count)) {
  6824. path.closePath();
  6825. }
  6826. }
  6827. setStyle(ctx, line.options);
  6828. ctx.stroke(path);
  6829. }
  6830. function strokePathDirect(ctx, line, start, count) {
  6831. const { segments , options } = line;
  6832. const segmentMethod = _getSegmentMethod(line);
  6833. for (const segment of segments){
  6834. setStyle(ctx, options, segment.style);
  6835. ctx.beginPath();
  6836. if (segmentMethod(ctx, line, segment, {
  6837. start,
  6838. end: start + count - 1
  6839. })) {
  6840. ctx.closePath();
  6841. }
  6842. ctx.stroke();
  6843. }
  6844. }
  6845. const usePath2D = typeof Path2D === 'function';
  6846. function draw(ctx, line, start, count) {
  6847. if (usePath2D && !line.options.segment) {
  6848. strokePathWithCache(ctx, line, start, count);
  6849. } else {
  6850. strokePathDirect(ctx, line, start, count);
  6851. }
  6852. }
  6853. class LineElement extends Element {
  6854. static id = 'line';
  6855. static defaults = {
  6856. borderCapStyle: 'butt',
  6857. borderDash: [],
  6858. borderDashOffset: 0,
  6859. borderJoinStyle: 'miter',
  6860. borderWidth: 3,
  6861. capBezierPoints: true,
  6862. cubicInterpolationMode: 'default',
  6863. fill: false,
  6864. spanGaps: false,
  6865. stepped: false,
  6866. tension: 0
  6867. };
  6868. static defaultRoutes = {
  6869. backgroundColor: 'backgroundColor',
  6870. borderColor: 'borderColor'
  6871. };
  6872. static descriptors = {
  6873. _scriptable: true,
  6874. _indexable: (name)=>name !== 'borderDash' && name !== 'fill'
  6875. };
  6876. constructor(cfg){
  6877. super();
  6878. this.animated = true;
  6879. this.options = undefined;
  6880. this._chart = undefined;
  6881. this._loop = undefined;
  6882. this._fullLoop = undefined;
  6883. this._path = undefined;
  6884. this._points = undefined;
  6885. this._segments = undefined;
  6886. this._decimated = false;
  6887. this._pointsUpdated = false;
  6888. this._datasetIndex = undefined;
  6889. if (cfg) {
  6890. Object.assign(this, cfg);
  6891. }
  6892. }
  6893. updateControlPoints(chartArea, indexAxis) {
  6894. const options = this.options;
  6895. if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) {
  6896. const loop = options.spanGaps ? this._loop : this._fullLoop;
  6897. _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis);
  6898. this._pointsUpdated = true;
  6899. }
  6900. }
  6901. set points(points) {
  6902. this._points = points;
  6903. delete this._segments;
  6904. delete this._path;
  6905. this._pointsUpdated = false;
  6906. }
  6907. get points() {
  6908. return this._points;
  6909. }
  6910. get segments() {
  6911. return this._segments || (this._segments = _computeSegments(this, this.options.segment));
  6912. }
  6913. first() {
  6914. const segments = this.segments;
  6915. const points = this.points;
  6916. return segments.length && points[segments[0].start];
  6917. }
  6918. last() {
  6919. const segments = this.segments;
  6920. const points = this.points;
  6921. const count = segments.length;
  6922. return count && points[segments[count - 1].end];
  6923. }
  6924. interpolate(point, property) {
  6925. const options = this.options;
  6926. const value = point[property];
  6927. const points = this.points;
  6928. const segments = _boundSegments(this, {
  6929. property,
  6930. start: value,
  6931. end: value
  6932. });
  6933. if (!segments.length) {
  6934. return;
  6935. }
  6936. const result = [];
  6937. const _interpolate = _getInterpolationMethod(options);
  6938. let i, ilen;
  6939. for(i = 0, ilen = segments.length; i < ilen; ++i){
  6940. const { start , end } = segments[i];
  6941. const p1 = points[start];
  6942. const p2 = points[end];
  6943. if (p1 === p2) {
  6944. result.push(p1);
  6945. continue;
  6946. }
  6947. const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
  6948. const interpolated = _interpolate(p1, p2, t, options.stepped);
  6949. interpolated[property] = point[property];
  6950. result.push(interpolated);
  6951. }
  6952. return result.length === 1 ? result[0] : result;
  6953. }
  6954. pathSegment(ctx, segment, params) {
  6955. const segmentMethod = _getSegmentMethod(this);
  6956. return segmentMethod(ctx, this, segment, params);
  6957. }
  6958. path(ctx, start, count) {
  6959. const segments = this.segments;
  6960. const segmentMethod = _getSegmentMethod(this);
  6961. let loop = this._loop;
  6962. start = start || 0;
  6963. count = count || this.points.length - start;
  6964. for (const segment of segments){
  6965. loop &= segmentMethod(ctx, this, segment, {
  6966. start,
  6967. end: start + count - 1
  6968. });
  6969. }
  6970. return !!loop;
  6971. }
  6972. draw(ctx, chartArea, start, count) {
  6973. const options = this.options || {};
  6974. const points = this.points || [];
  6975. if (points.length && options.borderWidth) {
  6976. ctx.save();
  6977. draw(ctx, this, start, count);
  6978. ctx.restore();
  6979. }
  6980. if (this.animated) {
  6981. this._pointsUpdated = false;
  6982. this._path = undefined;
  6983. }
  6984. }
  6985. }
  6986. function inRange$1(el, pos, axis, useFinalPosition) {
  6987. const options = el.options;
  6988. const { [axis]: value } = el.getProps([
  6989. axis
  6990. ], useFinalPosition);
  6991. return Math.abs(pos - value) < options.radius + options.hitRadius;
  6992. }
  6993. class PointElement extends Element {
  6994. static id = 'point';
  6995. parsed;
  6996. skip;
  6997. stop;
  6998. /**
  6999. * @type {any}
  7000. */ static defaults = {
  7001. borderWidth: 1,
  7002. hitRadius: 1,
  7003. hoverBorderWidth: 1,
  7004. hoverRadius: 4,
  7005. pointStyle: 'circle',
  7006. radius: 3,
  7007. rotation: 0
  7008. };
  7009. /**
  7010. * @type {any}
  7011. */ static defaultRoutes = {
  7012. backgroundColor: 'backgroundColor',
  7013. borderColor: 'borderColor'
  7014. };
  7015. constructor(cfg){
  7016. super();
  7017. this.options = undefined;
  7018. this.parsed = undefined;
  7019. this.skip = undefined;
  7020. this.stop = undefined;
  7021. if (cfg) {
  7022. Object.assign(this, cfg);
  7023. }
  7024. }
  7025. inRange(mouseX, mouseY, useFinalPosition) {
  7026. const options = this.options;
  7027. const { x , y } = this.getProps([
  7028. 'x',
  7029. 'y'
  7030. ], useFinalPosition);
  7031. return Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2) < Math.pow(options.hitRadius + options.radius, 2);
  7032. }
  7033. inXRange(mouseX, useFinalPosition) {
  7034. return inRange$1(this, mouseX, 'x', useFinalPosition);
  7035. }
  7036. inYRange(mouseY, useFinalPosition) {
  7037. return inRange$1(this, mouseY, 'y', useFinalPosition);
  7038. }
  7039. getCenterPoint(useFinalPosition) {
  7040. const { x , y } = this.getProps([
  7041. 'x',
  7042. 'y'
  7043. ], useFinalPosition);
  7044. return {
  7045. x,
  7046. y
  7047. };
  7048. }
  7049. size(options) {
  7050. options = options || this.options || {};
  7051. let radius = options.radius || 0;
  7052. radius = Math.max(radius, radius && options.hoverRadius || 0);
  7053. const borderWidth = radius && options.borderWidth || 0;
  7054. return (radius + borderWidth) * 2;
  7055. }
  7056. draw(ctx, area) {
  7057. const options = this.options;
  7058. if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) {
  7059. return;
  7060. }
  7061. ctx.strokeStyle = options.borderColor;
  7062. ctx.lineWidth = options.borderWidth;
  7063. ctx.fillStyle = options.backgroundColor;
  7064. drawPoint(ctx, options, this.x, this.y);
  7065. }
  7066. getRange() {
  7067. const options = this.options || {};
  7068. // @ts-expect-error Fallbacks should never be hit in practice
  7069. return options.radius + options.hitRadius;
  7070. }
  7071. }
  7072. function getBarBounds(bar, useFinalPosition) {
  7073. const { x , y , base , width , height } = bar.getProps([
  7074. 'x',
  7075. 'y',
  7076. 'base',
  7077. 'width',
  7078. 'height'
  7079. ], useFinalPosition);
  7080. let left, right, top, bottom, half;
  7081. if (bar.horizontal) {
  7082. half = height / 2;
  7083. left = Math.min(x, base);
  7084. right = Math.max(x, base);
  7085. top = y - half;
  7086. bottom = y + half;
  7087. } else {
  7088. half = width / 2;
  7089. left = x - half;
  7090. right = x + half;
  7091. top = Math.min(y, base);
  7092. bottom = Math.max(y, base);
  7093. }
  7094. return {
  7095. left,
  7096. top,
  7097. right,
  7098. bottom
  7099. };
  7100. }
  7101. function skipOrLimit(skip, value, min, max) {
  7102. return skip ? 0 : _limitValue(value, min, max);
  7103. }
  7104. function parseBorderWidth(bar, maxW, maxH) {
  7105. const value = bar.options.borderWidth;
  7106. const skip = bar.borderSkipped;
  7107. const o = toTRBL(value);
  7108. return {
  7109. t: skipOrLimit(skip.top, o.top, 0, maxH),
  7110. r: skipOrLimit(skip.right, o.right, 0, maxW),
  7111. b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
  7112. l: skipOrLimit(skip.left, o.left, 0, maxW)
  7113. };
  7114. }
  7115. function parseBorderRadius(bar, maxW, maxH) {
  7116. const { enableBorderRadius } = bar.getProps([
  7117. 'enableBorderRadius'
  7118. ]);
  7119. const value = bar.options.borderRadius;
  7120. const o = toTRBLCorners(value);
  7121. const maxR = Math.min(maxW, maxH);
  7122. const skip = bar.borderSkipped;
  7123. const enableBorder = enableBorderRadius || isObject(value);
  7124. return {
  7125. topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
  7126. topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
  7127. bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
  7128. bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
  7129. };
  7130. }
  7131. function boundingRects(bar) {
  7132. const bounds = getBarBounds(bar);
  7133. const width = bounds.right - bounds.left;
  7134. const height = bounds.bottom - bounds.top;
  7135. const border = parseBorderWidth(bar, width / 2, height / 2);
  7136. const radius = parseBorderRadius(bar, width / 2, height / 2);
  7137. return {
  7138. outer: {
  7139. x: bounds.left,
  7140. y: bounds.top,
  7141. w: width,
  7142. h: height,
  7143. radius
  7144. },
  7145. inner: {
  7146. x: bounds.left + border.l,
  7147. y: bounds.top + border.t,
  7148. w: width - border.l - border.r,
  7149. h: height - border.t - border.b,
  7150. radius: {
  7151. topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
  7152. topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
  7153. bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
  7154. bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r))
  7155. }
  7156. }
  7157. };
  7158. }
  7159. function inRange(bar, x, y, useFinalPosition) {
  7160. const skipX = x === null;
  7161. const skipY = y === null;
  7162. const skipBoth = skipX && skipY;
  7163. const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
  7164. return bounds && (skipX || _isBetween(x, bounds.left, bounds.right)) && (skipY || _isBetween(y, bounds.top, bounds.bottom));
  7165. }
  7166. function hasRadius(radius) {
  7167. return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
  7168. }
  7169. function addNormalRectPath(ctx, rect) {
  7170. ctx.rect(rect.x, rect.y, rect.w, rect.h);
  7171. }
  7172. function inflateRect(rect, amount, refRect = {}) {
  7173. const x = rect.x !== refRect.x ? -amount : 0;
  7174. const y = rect.y !== refRect.y ? -amount : 0;
  7175. const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;
  7176. const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;
  7177. return {
  7178. x: rect.x + x,
  7179. y: rect.y + y,
  7180. w: rect.w + w,
  7181. h: rect.h + h,
  7182. radius: rect.radius
  7183. };
  7184. }
  7185. class BarElement extends Element {
  7186. static id = 'bar';
  7187. static defaults = {
  7188. borderSkipped: 'start',
  7189. borderWidth: 0,
  7190. borderRadius: 0,
  7191. inflateAmount: 'auto',
  7192. pointStyle: undefined
  7193. };
  7194. static defaultRoutes = {
  7195. backgroundColor: 'backgroundColor',
  7196. borderColor: 'borderColor'
  7197. };
  7198. constructor(cfg){
  7199. super();
  7200. this.options = undefined;
  7201. this.horizontal = undefined;
  7202. this.base = undefined;
  7203. this.width = undefined;
  7204. this.height = undefined;
  7205. this.inflateAmount = undefined;
  7206. if (cfg) {
  7207. Object.assign(this, cfg);
  7208. }
  7209. }
  7210. draw(ctx) {
  7211. const { inflateAmount , options: { borderColor , backgroundColor } } = this;
  7212. const { inner , outer } = boundingRects(this);
  7213. const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;
  7214. ctx.save();
  7215. if (outer.w !== inner.w || outer.h !== inner.h) {
  7216. ctx.beginPath();
  7217. addRectPath(ctx, inflateRect(outer, inflateAmount, inner));
  7218. ctx.clip();
  7219. addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));
  7220. ctx.fillStyle = borderColor;
  7221. ctx.fill('evenodd');
  7222. }
  7223. ctx.beginPath();
  7224. addRectPath(ctx, inflateRect(inner, inflateAmount));
  7225. ctx.fillStyle = backgroundColor;
  7226. ctx.fill();
  7227. ctx.restore();
  7228. }
  7229. inRange(mouseX, mouseY, useFinalPosition) {
  7230. return inRange(this, mouseX, mouseY, useFinalPosition);
  7231. }
  7232. inXRange(mouseX, useFinalPosition) {
  7233. return inRange(this, mouseX, null, useFinalPosition);
  7234. }
  7235. inYRange(mouseY, useFinalPosition) {
  7236. return inRange(this, null, mouseY, useFinalPosition);
  7237. }
  7238. getCenterPoint(useFinalPosition) {
  7239. const { x , y , base , horizontal } = this.getProps([
  7240. 'x',
  7241. 'y',
  7242. 'base',
  7243. 'horizontal'
  7244. ], useFinalPosition);
  7245. return {
  7246. x: horizontal ? (x + base) / 2 : x,
  7247. y: horizontal ? y : (y + base) / 2
  7248. };
  7249. }
  7250. getRange(axis) {
  7251. return axis === 'x' ? this.width / 2 : this.height / 2;
  7252. }
  7253. }
  7254. var elements = /*#__PURE__*/Object.freeze({
  7255. __proto__: null,
  7256. ArcElement: ArcElement,
  7257. BarElement: BarElement,
  7258. LineElement: LineElement,
  7259. PointElement: PointElement
  7260. });
  7261. const BORDER_COLORS = [
  7262. 'rgb(54, 162, 235)',
  7263. 'rgb(255, 99, 132)',
  7264. 'rgb(255, 159, 64)',
  7265. 'rgb(255, 205, 86)',
  7266. 'rgb(75, 192, 192)',
  7267. 'rgb(153, 102, 255)',
  7268. 'rgb(201, 203, 207)' // grey
  7269. ];
  7270. // Border colors with 50% transparency
  7271. const BACKGROUND_COLORS = /* #__PURE__ */ BORDER_COLORS.map((color)=>color.replace('rgb(', 'rgba(').replace(')', ', 0.5)'));
  7272. function getBorderColor(i) {
  7273. return BORDER_COLORS[i % BORDER_COLORS.length];
  7274. }
  7275. function getBackgroundColor(i) {
  7276. return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length];
  7277. }
  7278. function colorizeDefaultDataset(dataset, i) {
  7279. dataset.borderColor = getBorderColor(i);
  7280. dataset.backgroundColor = getBackgroundColor(i);
  7281. return ++i;
  7282. }
  7283. function colorizeDoughnutDataset(dataset, i) {
  7284. dataset.backgroundColor = dataset.data.map(()=>getBorderColor(i++));
  7285. return i;
  7286. }
  7287. function colorizePolarAreaDataset(dataset, i) {
  7288. dataset.backgroundColor = dataset.data.map(()=>getBackgroundColor(i++));
  7289. return i;
  7290. }
  7291. function getColorizer(chart) {
  7292. let i = 0;
  7293. return (dataset, datasetIndex)=>{
  7294. const controller = chart.getDatasetMeta(datasetIndex).controller;
  7295. if (controller instanceof DoughnutController) {
  7296. i = colorizeDoughnutDataset(dataset, i);
  7297. } else if (controller instanceof PolarAreaController) {
  7298. i = colorizePolarAreaDataset(dataset, i);
  7299. } else if (controller) {
  7300. i = colorizeDefaultDataset(dataset, i);
  7301. }
  7302. };
  7303. }
  7304. function containsColorsDefinitions(descriptors) {
  7305. let k;
  7306. for(k in descriptors){
  7307. if (descriptors[k].borderColor || descriptors[k].backgroundColor) {
  7308. return true;
  7309. }
  7310. }
  7311. return false;
  7312. }
  7313. function containsColorsDefinition(descriptor) {
  7314. return descriptor && (descriptor.borderColor || descriptor.backgroundColor);
  7315. }
  7316. var plugin_colors = {
  7317. id: 'colors',
  7318. defaults: {
  7319. enabled: true,
  7320. forceOverride: false
  7321. },
  7322. beforeLayout (chart, _args, options) {
  7323. if (!options.enabled) {
  7324. return;
  7325. }
  7326. const { data: { datasets } , options: chartOptions } = chart.config;
  7327. const { elements } = chartOptions;
  7328. if (!options.forceOverride && (containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || elements && containsColorsDefinitions(elements))) {
  7329. return;
  7330. }
  7331. const colorizer = getColorizer(chart);
  7332. datasets.forEach(colorizer);
  7333. }
  7334. };
  7335. function lttbDecimation(data, start, count, availableWidth, options) {
  7336. const samples = options.samples || availableWidth;
  7337. if (samples >= count) {
  7338. return data.slice(start, start + count);
  7339. }
  7340. const decimated = [];
  7341. const bucketWidth = (count - 2) / (samples - 2);
  7342. let sampledIndex = 0;
  7343. const endIndex = start + count - 1;
  7344. let a = start;
  7345. let i, maxAreaPoint, maxArea, area, nextA;
  7346. decimated[sampledIndex++] = data[a];
  7347. for(i = 0; i < samples - 2; i++){
  7348. let avgX = 0;
  7349. let avgY = 0;
  7350. let j;
  7351. const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
  7352. const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
  7353. const avgRangeLength = avgRangeEnd - avgRangeStart;
  7354. for(j = avgRangeStart; j < avgRangeEnd; j++){
  7355. avgX += data[j].x;
  7356. avgY += data[j].y;
  7357. }
  7358. avgX /= avgRangeLength;
  7359. avgY /= avgRangeLength;
  7360. const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
  7361. const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;
  7362. const { x: pointAx , y: pointAy } = data[a];
  7363. maxArea = area = -1;
  7364. for(j = rangeOffs; j < rangeTo; j++){
  7365. area = 0.5 * Math.abs((pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy));
  7366. if (area > maxArea) {
  7367. maxArea = area;
  7368. maxAreaPoint = data[j];
  7369. nextA = j;
  7370. }
  7371. }
  7372. decimated[sampledIndex++] = maxAreaPoint;
  7373. a = nextA;
  7374. }
  7375. decimated[sampledIndex++] = data[endIndex];
  7376. return decimated;
  7377. }
  7378. function minMaxDecimation(data, start, count, availableWidth) {
  7379. let avgX = 0;
  7380. let countX = 0;
  7381. let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
  7382. const decimated = [];
  7383. const endIndex = start + count - 1;
  7384. const xMin = data[start].x;
  7385. const xMax = data[endIndex].x;
  7386. const dx = xMax - xMin;
  7387. for(i = start; i < start + count; ++i){
  7388. point = data[i];
  7389. x = (point.x - xMin) / dx * availableWidth;
  7390. y = point.y;
  7391. const truncX = x | 0;
  7392. if (truncX === prevX) {
  7393. if (y < minY) {
  7394. minY = y;
  7395. minIndex = i;
  7396. } else if (y > maxY) {
  7397. maxY = y;
  7398. maxIndex = i;
  7399. }
  7400. avgX = (countX * avgX + point.x) / ++countX;
  7401. } else {
  7402. const lastIndex = i - 1;
  7403. if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {
  7404. const intermediateIndex1 = Math.min(minIndex, maxIndex);
  7405. const intermediateIndex2 = Math.max(minIndex, maxIndex);
  7406. if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
  7407. decimated.push({
  7408. ...data[intermediateIndex1],
  7409. x: avgX
  7410. });
  7411. }
  7412. if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
  7413. decimated.push({
  7414. ...data[intermediateIndex2],
  7415. x: avgX
  7416. });
  7417. }
  7418. }
  7419. if (i > 0 && lastIndex !== startIndex) {
  7420. decimated.push(data[lastIndex]);
  7421. }
  7422. decimated.push(point);
  7423. prevX = truncX;
  7424. countX = 0;
  7425. minY = maxY = y;
  7426. minIndex = maxIndex = startIndex = i;
  7427. }
  7428. }
  7429. return decimated;
  7430. }
  7431. function cleanDecimatedDataset(dataset) {
  7432. if (dataset._decimated) {
  7433. const data = dataset._data;
  7434. delete dataset._decimated;
  7435. delete dataset._data;
  7436. Object.defineProperty(dataset, 'data', {
  7437. configurable: true,
  7438. enumerable: true,
  7439. writable: true,
  7440. value: data
  7441. });
  7442. }
  7443. }
  7444. function cleanDecimatedData(chart) {
  7445. chart.data.datasets.forEach((dataset)=>{
  7446. cleanDecimatedDataset(dataset);
  7447. });
  7448. }
  7449. function getStartAndCountOfVisiblePointsSimplified(meta, points) {
  7450. const pointCount = points.length;
  7451. let start = 0;
  7452. let count;
  7453. const { iScale } = meta;
  7454. const { min , max , minDefined , maxDefined } = iScale.getUserBounds();
  7455. if (minDefined) {
  7456. start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
  7457. }
  7458. if (maxDefined) {
  7459. count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
  7460. } else {
  7461. count = pointCount - start;
  7462. }
  7463. return {
  7464. start,
  7465. count
  7466. };
  7467. }
  7468. var plugin_decimation = {
  7469. id: 'decimation',
  7470. defaults: {
  7471. algorithm: 'min-max',
  7472. enabled: false
  7473. },
  7474. beforeElementsUpdate: (chart, args, options)=>{
  7475. if (!options.enabled) {
  7476. cleanDecimatedData(chart);
  7477. return;
  7478. }
  7479. const availableWidth = chart.width;
  7480. chart.data.datasets.forEach((dataset, datasetIndex)=>{
  7481. const { _data , indexAxis } = dataset;
  7482. const meta = chart.getDatasetMeta(datasetIndex);
  7483. const data = _data || dataset.data;
  7484. if (resolve([
  7485. indexAxis,
  7486. chart.options.indexAxis
  7487. ]) === 'y') {
  7488. return;
  7489. }
  7490. if (!meta.controller.supportsDecimation) {
  7491. return;
  7492. }
  7493. const xAxis = chart.scales[meta.xAxisID];
  7494. if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
  7495. return;
  7496. }
  7497. if (chart.options.parsing) {
  7498. return;
  7499. }
  7500. let { start , count } = getStartAndCountOfVisiblePointsSimplified(meta, data);
  7501. const threshold = options.threshold || 4 * availableWidth;
  7502. if (count <= threshold) {
  7503. cleanDecimatedDataset(dataset);
  7504. return;
  7505. }
  7506. if (isNullOrUndef(_data)) {
  7507. dataset._data = data;
  7508. delete dataset.data;
  7509. Object.defineProperty(dataset, 'data', {
  7510. configurable: true,
  7511. enumerable: true,
  7512. get: function() {
  7513. return this._decimated;
  7514. },
  7515. set: function(d) {
  7516. this._data = d;
  7517. }
  7518. });
  7519. }
  7520. let decimated;
  7521. switch(options.algorithm){
  7522. case 'lttb':
  7523. decimated = lttbDecimation(data, start, count, availableWidth, options);
  7524. break;
  7525. case 'min-max':
  7526. decimated = minMaxDecimation(data, start, count, availableWidth);
  7527. break;
  7528. default:
  7529. throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
  7530. }
  7531. dataset._decimated = decimated;
  7532. });
  7533. },
  7534. destroy (chart) {
  7535. cleanDecimatedData(chart);
  7536. }
  7537. };
  7538. function _segments(line, target, property) {
  7539. const segments = line.segments;
  7540. const points = line.points;
  7541. const tpoints = target.points;
  7542. const parts = [];
  7543. for (const segment of segments){
  7544. let { start , end } = segment;
  7545. end = _findSegmentEnd(start, end, points);
  7546. const bounds = _getBounds(property, points[start], points[end], segment.loop);
  7547. if (!target.segments) {
  7548. parts.push({
  7549. source: segment,
  7550. target: bounds,
  7551. start: points[start],
  7552. end: points[end]
  7553. });
  7554. continue;
  7555. }
  7556. const targetSegments = _boundSegments(target, bounds);
  7557. for (const tgt of targetSegments){
  7558. const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
  7559. const fillSources = _boundSegment(segment, points, subBounds);
  7560. for (const fillSource of fillSources){
  7561. parts.push({
  7562. source: fillSource,
  7563. target: tgt,
  7564. start: {
  7565. [property]: _getEdge(bounds, subBounds, 'start', Math.max)
  7566. },
  7567. end: {
  7568. [property]: _getEdge(bounds, subBounds, 'end', Math.min)
  7569. }
  7570. });
  7571. }
  7572. }
  7573. }
  7574. return parts;
  7575. }
  7576. function _getBounds(property, first, last, loop) {
  7577. if (loop) {
  7578. return;
  7579. }
  7580. let start = first[property];
  7581. let end = last[property];
  7582. if (property === 'angle') {
  7583. start = _normalizeAngle(start);
  7584. end = _normalizeAngle(end);
  7585. }
  7586. return {
  7587. property,
  7588. start,
  7589. end
  7590. };
  7591. }
  7592. function _pointsFromSegments(boundary, line) {
  7593. const { x =null , y =null } = boundary || {};
  7594. const linePoints = line.points;
  7595. const points = [];
  7596. line.segments.forEach(({ start , end })=>{
  7597. end = _findSegmentEnd(start, end, linePoints);
  7598. const first = linePoints[start];
  7599. const last = linePoints[end];
  7600. if (y !== null) {
  7601. points.push({
  7602. x: first.x,
  7603. y
  7604. });
  7605. points.push({
  7606. x: last.x,
  7607. y
  7608. });
  7609. } else if (x !== null) {
  7610. points.push({
  7611. x,
  7612. y: first.y
  7613. });
  7614. points.push({
  7615. x,
  7616. y: last.y
  7617. });
  7618. }
  7619. });
  7620. return points;
  7621. }
  7622. function _findSegmentEnd(start, end, points) {
  7623. for(; end > start; end--){
  7624. const point = points[end];
  7625. if (!isNaN(point.x) && !isNaN(point.y)) {
  7626. break;
  7627. }
  7628. }
  7629. return end;
  7630. }
  7631. function _getEdge(a, b, prop, fn) {
  7632. if (a && b) {
  7633. return fn(a[prop], b[prop]);
  7634. }
  7635. return a ? a[prop] : b ? b[prop] : 0;
  7636. }
  7637. function _createBoundaryLine(boundary, line) {
  7638. let points = [];
  7639. let _loop = false;
  7640. if (isArray(boundary)) {
  7641. _loop = true;
  7642. points = boundary;
  7643. } else {
  7644. points = _pointsFromSegments(boundary, line);
  7645. }
  7646. return points.length ? new LineElement({
  7647. points,
  7648. options: {
  7649. tension: 0
  7650. },
  7651. _loop,
  7652. _fullLoop: _loop
  7653. }) : null;
  7654. }
  7655. function _shouldApplyFill(source) {
  7656. return source && source.fill !== false;
  7657. }
  7658. function _resolveTarget(sources, index, propagate) {
  7659. const source = sources[index];
  7660. let fill = source.fill;
  7661. const visited = [
  7662. index
  7663. ];
  7664. let target;
  7665. if (!propagate) {
  7666. return fill;
  7667. }
  7668. while(fill !== false && visited.indexOf(fill) === -1){
  7669. if (!isNumberFinite(fill)) {
  7670. return fill;
  7671. }
  7672. target = sources[fill];
  7673. if (!target) {
  7674. return false;
  7675. }
  7676. if (target.visible) {
  7677. return fill;
  7678. }
  7679. visited.push(fill);
  7680. fill = target.fill;
  7681. }
  7682. return false;
  7683. }
  7684. function _decodeFill(line, index, count) {
  7685. const fill = parseFillOption(line);
  7686. if (isObject(fill)) {
  7687. return isNaN(fill.value) ? false : fill;
  7688. }
  7689. let target = parseFloat(fill);
  7690. if (isNumberFinite(target) && Math.floor(target) === target) {
  7691. return decodeTargetIndex(fill[0], index, target, count);
  7692. }
  7693. return [
  7694. 'origin',
  7695. 'start',
  7696. 'end',
  7697. 'stack',
  7698. 'shape'
  7699. ].indexOf(fill) >= 0 && fill;
  7700. }
  7701. function decodeTargetIndex(firstCh, index, target, count) {
  7702. if (firstCh === '-' || firstCh === '+') {
  7703. target = index + target;
  7704. }
  7705. if (target === index || target < 0 || target >= count) {
  7706. return false;
  7707. }
  7708. return target;
  7709. }
  7710. function _getTargetPixel(fill, scale) {
  7711. let pixel = null;
  7712. if (fill === 'start') {
  7713. pixel = scale.bottom;
  7714. } else if (fill === 'end') {
  7715. pixel = scale.top;
  7716. } else if (isObject(fill)) {
  7717. pixel = scale.getPixelForValue(fill.value);
  7718. } else if (scale.getBasePixel) {
  7719. pixel = scale.getBasePixel();
  7720. }
  7721. return pixel;
  7722. }
  7723. function _getTargetValue(fill, scale, startValue) {
  7724. let value;
  7725. if (fill === 'start') {
  7726. value = startValue;
  7727. } else if (fill === 'end') {
  7728. value = scale.options.reverse ? scale.min : scale.max;
  7729. } else if (isObject(fill)) {
  7730. value = fill.value;
  7731. } else {
  7732. value = scale.getBaseValue();
  7733. }
  7734. return value;
  7735. }
  7736. function parseFillOption(line) {
  7737. const options = line.options;
  7738. const fillOption = options.fill;
  7739. let fill = valueOrDefault(fillOption && fillOption.target, fillOption);
  7740. if (fill === undefined) {
  7741. fill = !!options.backgroundColor;
  7742. }
  7743. if (fill === false || fill === null) {
  7744. return false;
  7745. }
  7746. if (fill === true) {
  7747. return 'origin';
  7748. }
  7749. return fill;
  7750. }
  7751. function _buildStackLine(source) {
  7752. const { scale , index , line } = source;
  7753. const points = [];
  7754. const segments = line.segments;
  7755. const sourcePoints = line.points;
  7756. const linesBelow = getLinesBelow(scale, index);
  7757. linesBelow.push(_createBoundaryLine({
  7758. x: null,
  7759. y: scale.bottom
  7760. }, line));
  7761. for(let i = 0; i < segments.length; i++){
  7762. const segment = segments[i];
  7763. for(let j = segment.start; j <= segment.end; j++){
  7764. addPointsBelow(points, sourcePoints[j], linesBelow);
  7765. }
  7766. }
  7767. return new LineElement({
  7768. points,
  7769. options: {}
  7770. });
  7771. }
  7772. function getLinesBelow(scale, index) {
  7773. const below = [];
  7774. const metas = scale.getMatchingVisibleMetas('line');
  7775. for(let i = 0; i < metas.length; i++){
  7776. const meta = metas[i];
  7777. if (meta.index === index) {
  7778. break;
  7779. }
  7780. if (!meta.hidden) {
  7781. below.unshift(meta.dataset);
  7782. }
  7783. }
  7784. return below;
  7785. }
  7786. function addPointsBelow(points, sourcePoint, linesBelow) {
  7787. const postponed = [];
  7788. for(let j = 0; j < linesBelow.length; j++){
  7789. const line = linesBelow[j];
  7790. const { first , last , point } = findPoint(line, sourcePoint, 'x');
  7791. if (!point || first && last) {
  7792. continue;
  7793. }
  7794. if (first) {
  7795. postponed.unshift(point);
  7796. } else {
  7797. points.push(point);
  7798. if (!last) {
  7799. break;
  7800. }
  7801. }
  7802. }
  7803. points.push(...postponed);
  7804. }
  7805. function findPoint(line, sourcePoint, property) {
  7806. const point = line.interpolate(sourcePoint, property);
  7807. if (!point) {
  7808. return {};
  7809. }
  7810. const pointValue = point[property];
  7811. const segments = line.segments;
  7812. const linePoints = line.points;
  7813. let first = false;
  7814. let last = false;
  7815. for(let i = 0; i < segments.length; i++){
  7816. const segment = segments[i];
  7817. const firstValue = linePoints[segment.start][property];
  7818. const lastValue = linePoints[segment.end][property];
  7819. if (_isBetween(pointValue, firstValue, lastValue)) {
  7820. first = pointValue === firstValue;
  7821. last = pointValue === lastValue;
  7822. break;
  7823. }
  7824. }
  7825. return {
  7826. first,
  7827. last,
  7828. point
  7829. };
  7830. }
  7831. class simpleArc {
  7832. constructor(opts){
  7833. this.x = opts.x;
  7834. this.y = opts.y;
  7835. this.radius = opts.radius;
  7836. }
  7837. pathSegment(ctx, bounds, opts) {
  7838. const { x , y , radius } = this;
  7839. bounds = bounds || {
  7840. start: 0,
  7841. end: TAU
  7842. };
  7843. ctx.arc(x, y, radius, bounds.end, bounds.start, true);
  7844. return !opts.bounds;
  7845. }
  7846. interpolate(point) {
  7847. const { x , y , radius } = this;
  7848. const angle = point.angle;
  7849. return {
  7850. x: x + Math.cos(angle) * radius,
  7851. y: y + Math.sin(angle) * radius,
  7852. angle
  7853. };
  7854. }
  7855. }
  7856. function _getTarget(source) {
  7857. const { chart , fill , line } = source;
  7858. if (isNumberFinite(fill)) {
  7859. return getLineByIndex(chart, fill);
  7860. }
  7861. if (fill === 'stack') {
  7862. return _buildStackLine(source);
  7863. }
  7864. if (fill === 'shape') {
  7865. return true;
  7866. }
  7867. const boundary = computeBoundary(source);
  7868. if (boundary instanceof simpleArc) {
  7869. return boundary;
  7870. }
  7871. return _createBoundaryLine(boundary, line);
  7872. }
  7873. function getLineByIndex(chart, index) {
  7874. const meta = chart.getDatasetMeta(index);
  7875. const visible = meta && chart.isDatasetVisible(index);
  7876. return visible ? meta.dataset : null;
  7877. }
  7878. function computeBoundary(source) {
  7879. const scale = source.scale || {};
  7880. if (scale.getPointPositionForValue) {
  7881. return computeCircularBoundary(source);
  7882. }
  7883. return computeLinearBoundary(source);
  7884. }
  7885. function computeLinearBoundary(source) {
  7886. const { scale ={} , fill } = source;
  7887. const pixel = _getTargetPixel(fill, scale);
  7888. if (isNumberFinite(pixel)) {
  7889. const horizontal = scale.isHorizontal();
  7890. return {
  7891. x: horizontal ? pixel : null,
  7892. y: horizontal ? null : pixel
  7893. };
  7894. }
  7895. return null;
  7896. }
  7897. function computeCircularBoundary(source) {
  7898. const { scale , fill } = source;
  7899. const options = scale.options;
  7900. const length = scale.getLabels().length;
  7901. const start = options.reverse ? scale.max : scale.min;
  7902. const value = _getTargetValue(fill, scale, start);
  7903. const target = [];
  7904. if (options.grid.circular) {
  7905. const center = scale.getPointPositionForValue(0, start);
  7906. return new simpleArc({
  7907. x: center.x,
  7908. y: center.y,
  7909. radius: scale.getDistanceFromCenterForValue(value)
  7910. });
  7911. }
  7912. for(let i = 0; i < length; ++i){
  7913. target.push(scale.getPointPositionForValue(i, value));
  7914. }
  7915. return target;
  7916. }
  7917. function _drawfill(ctx, source, area) {
  7918. const target = _getTarget(source);
  7919. const { line , scale , axis } = source;
  7920. const lineOpts = line.options;
  7921. const fillOption = lineOpts.fill;
  7922. const color = lineOpts.backgroundColor;
  7923. const { above =color , below =color } = fillOption || {};
  7924. if (target && line.points.length) {
  7925. clipArea(ctx, area);
  7926. doFill(ctx, {
  7927. line,
  7928. target,
  7929. above,
  7930. below,
  7931. area,
  7932. scale,
  7933. axis
  7934. });
  7935. unclipArea(ctx);
  7936. }
  7937. }
  7938. function doFill(ctx, cfg) {
  7939. const { line , target , above , below , area , scale } = cfg;
  7940. const property = line._loop ? 'angle' : cfg.axis;
  7941. ctx.save();
  7942. if (property === 'x' && below !== above) {
  7943. clipVertical(ctx, target, area.top);
  7944. fill(ctx, {
  7945. line,
  7946. target,
  7947. color: above,
  7948. scale,
  7949. property
  7950. });
  7951. ctx.restore();
  7952. ctx.save();
  7953. clipVertical(ctx, target, area.bottom);
  7954. }
  7955. fill(ctx, {
  7956. line,
  7957. target,
  7958. color: below,
  7959. scale,
  7960. property
  7961. });
  7962. ctx.restore();
  7963. }
  7964. function clipVertical(ctx, target, clipY) {
  7965. const { segments , points } = target;
  7966. let first = true;
  7967. let lineLoop = false;
  7968. ctx.beginPath();
  7969. for (const segment of segments){
  7970. const { start , end } = segment;
  7971. const firstPoint = points[start];
  7972. const lastPoint = points[_findSegmentEnd(start, end, points)];
  7973. if (first) {
  7974. ctx.moveTo(firstPoint.x, firstPoint.y);
  7975. first = false;
  7976. } else {
  7977. ctx.lineTo(firstPoint.x, clipY);
  7978. ctx.lineTo(firstPoint.x, firstPoint.y);
  7979. }
  7980. lineLoop = !!target.pathSegment(ctx, segment, {
  7981. move: lineLoop
  7982. });
  7983. if (lineLoop) {
  7984. ctx.closePath();
  7985. } else {
  7986. ctx.lineTo(lastPoint.x, clipY);
  7987. }
  7988. }
  7989. ctx.lineTo(target.first().x, clipY);
  7990. ctx.closePath();
  7991. ctx.clip();
  7992. }
  7993. function fill(ctx, cfg) {
  7994. const { line , target , property , color , scale } = cfg;
  7995. const segments = _segments(line, target, property);
  7996. for (const { source: src , target: tgt , start , end } of segments){
  7997. const { style: { backgroundColor =color } = {} } = src;
  7998. const notShape = target !== true;
  7999. ctx.save();
  8000. ctx.fillStyle = backgroundColor;
  8001. clipBounds(ctx, scale, notShape && _getBounds(property, start, end));
  8002. ctx.beginPath();
  8003. const lineLoop = !!line.pathSegment(ctx, src);
  8004. let loop;
  8005. if (notShape) {
  8006. if (lineLoop) {
  8007. ctx.closePath();
  8008. } else {
  8009. interpolatedLineTo(ctx, target, end, property);
  8010. }
  8011. const targetLoop = !!target.pathSegment(ctx, tgt, {
  8012. move: lineLoop,
  8013. reverse: true
  8014. });
  8015. loop = lineLoop && targetLoop;
  8016. if (!loop) {
  8017. interpolatedLineTo(ctx, target, start, property);
  8018. }
  8019. }
  8020. ctx.closePath();
  8021. ctx.fill(loop ? 'evenodd' : 'nonzero');
  8022. ctx.restore();
  8023. }
  8024. }
  8025. function clipBounds(ctx, scale, bounds) {
  8026. const { top , bottom } = scale.chart.chartArea;
  8027. const { property , start , end } = bounds || {};
  8028. if (property === 'x') {
  8029. ctx.beginPath();
  8030. ctx.rect(start, top, end - start, bottom - top);
  8031. ctx.clip();
  8032. }
  8033. }
  8034. function interpolatedLineTo(ctx, target, point, property) {
  8035. const interpolatedPoint = target.interpolate(point, property);
  8036. if (interpolatedPoint) {
  8037. ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
  8038. }
  8039. }
  8040. var index = {
  8041. id: 'filler',
  8042. afterDatasetsUpdate (chart, _args, options) {
  8043. const count = (chart.data.datasets || []).length;
  8044. const sources = [];
  8045. let meta, i, line, source;
  8046. for(i = 0; i < count; ++i){
  8047. meta = chart.getDatasetMeta(i);
  8048. line = meta.dataset;
  8049. source = null;
  8050. if (line && line.options && line instanceof LineElement) {
  8051. source = {
  8052. visible: chart.isDatasetVisible(i),
  8053. index: i,
  8054. fill: _decodeFill(line, i, count),
  8055. chart,
  8056. axis: meta.controller.options.indexAxis,
  8057. scale: meta.vScale,
  8058. line
  8059. };
  8060. }
  8061. meta.$filler = source;
  8062. sources.push(source);
  8063. }
  8064. for(i = 0; i < count; ++i){
  8065. source = sources[i];
  8066. if (!source || source.fill === false) {
  8067. continue;
  8068. }
  8069. source.fill = _resolveTarget(sources, i, options.propagate);
  8070. }
  8071. },
  8072. beforeDraw (chart, _args, options) {
  8073. const draw = options.drawTime === 'beforeDraw';
  8074. const metasets = chart.getSortedVisibleDatasetMetas();
  8075. const area = chart.chartArea;
  8076. for(let i = metasets.length - 1; i >= 0; --i){
  8077. const source = metasets[i].$filler;
  8078. if (!source) {
  8079. continue;
  8080. }
  8081. source.line.updateControlPoints(area, source.axis);
  8082. if (draw && source.fill) {
  8083. _drawfill(chart.ctx, source, area);
  8084. }
  8085. }
  8086. },
  8087. beforeDatasetsDraw (chart, _args, options) {
  8088. if (options.drawTime !== 'beforeDatasetsDraw') {
  8089. return;
  8090. }
  8091. const metasets = chart.getSortedVisibleDatasetMetas();
  8092. for(let i = metasets.length - 1; i >= 0; --i){
  8093. const source = metasets[i].$filler;
  8094. if (_shouldApplyFill(source)) {
  8095. _drawfill(chart.ctx, source, chart.chartArea);
  8096. }
  8097. }
  8098. },
  8099. beforeDatasetDraw (chart, args, options) {
  8100. const source = args.meta.$filler;
  8101. if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') {
  8102. return;
  8103. }
  8104. _drawfill(chart.ctx, source, chart.chartArea);
  8105. },
  8106. defaults: {
  8107. propagate: true,
  8108. drawTime: 'beforeDatasetDraw'
  8109. }
  8110. };
  8111. const getBoxSize = (labelOpts, fontSize)=>{
  8112. let { boxHeight =fontSize , boxWidth =fontSize } = labelOpts;
  8113. if (labelOpts.usePointStyle) {
  8114. boxHeight = Math.min(boxHeight, fontSize);
  8115. boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize);
  8116. }
  8117. return {
  8118. boxWidth,
  8119. boxHeight,
  8120. itemHeight: Math.max(fontSize, boxHeight)
  8121. };
  8122. };
  8123. const itemsEqual = (a, b)=>a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
  8124. class Legend extends Element {
  8125. constructor(config){
  8126. super();
  8127. this._added = false;
  8128. this.legendHitBoxes = [];
  8129. this._hoveredItem = null;
  8130. this.doughnutMode = false;
  8131. this.chart = config.chart;
  8132. this.options = config.options;
  8133. this.ctx = config.ctx;
  8134. this.legendItems = undefined;
  8135. this.columnSizes = undefined;
  8136. this.lineWidths = undefined;
  8137. this.maxHeight = undefined;
  8138. this.maxWidth = undefined;
  8139. this.top = undefined;
  8140. this.bottom = undefined;
  8141. this.left = undefined;
  8142. this.right = undefined;
  8143. this.height = undefined;
  8144. this.width = undefined;
  8145. this._margins = undefined;
  8146. this.position = undefined;
  8147. this.weight = undefined;
  8148. this.fullSize = undefined;
  8149. }
  8150. update(maxWidth, maxHeight, margins) {
  8151. this.maxWidth = maxWidth;
  8152. this.maxHeight = maxHeight;
  8153. this._margins = margins;
  8154. this.setDimensions();
  8155. this.buildLabels();
  8156. this.fit();
  8157. }
  8158. setDimensions() {
  8159. if (this.isHorizontal()) {
  8160. this.width = this.maxWidth;
  8161. this.left = this._margins.left;
  8162. this.right = this.width;
  8163. } else {
  8164. this.height = this.maxHeight;
  8165. this.top = this._margins.top;
  8166. this.bottom = this.height;
  8167. }
  8168. }
  8169. buildLabels() {
  8170. const labelOpts = this.options.labels || {};
  8171. let legendItems = callback(labelOpts.generateLabels, [
  8172. this.chart
  8173. ], this) || [];
  8174. if (labelOpts.filter) {
  8175. legendItems = legendItems.filter((item)=>labelOpts.filter(item, this.chart.data));
  8176. }
  8177. if (labelOpts.sort) {
  8178. legendItems = legendItems.sort((a, b)=>labelOpts.sort(a, b, this.chart.data));
  8179. }
  8180. if (this.options.reverse) {
  8181. legendItems.reverse();
  8182. }
  8183. this.legendItems = legendItems;
  8184. }
  8185. fit() {
  8186. const { options , ctx } = this;
  8187. if (!options.display) {
  8188. this.width = this.height = 0;
  8189. return;
  8190. }
  8191. const labelOpts = options.labels;
  8192. const labelFont = toFont(labelOpts.font);
  8193. const fontSize = labelFont.size;
  8194. const titleHeight = this._computeTitleHeight();
  8195. const { boxWidth , itemHeight } = getBoxSize(labelOpts, fontSize);
  8196. let width, height;
  8197. ctx.font = labelFont.string;
  8198. if (this.isHorizontal()) {
  8199. width = this.maxWidth;
  8200. height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  8201. } else {
  8202. height = this.maxHeight;
  8203. width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10;
  8204. }
  8205. this.width = Math.min(width, options.maxWidth || this.maxWidth);
  8206. this.height = Math.min(height, options.maxHeight || this.maxHeight);
  8207. }
  8208. _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
  8209. const { ctx , maxWidth , options: { labels: { padding } } } = this;
  8210. const hitboxes = this.legendHitBoxes = [];
  8211. const lineWidths = this.lineWidths = [
  8212. 0
  8213. ];
  8214. const lineHeight = itemHeight + padding;
  8215. let totalHeight = titleHeight;
  8216. ctx.textAlign = 'left';
  8217. ctx.textBaseline = 'middle';
  8218. let row = -1;
  8219. let top = -lineHeight;
  8220. this.legendItems.forEach((legendItem, i)=>{
  8221. const itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width;
  8222. if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
  8223. totalHeight += lineHeight;
  8224. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  8225. top += lineHeight;
  8226. row++;
  8227. }
  8228. hitboxes[i] = {
  8229. left: 0,
  8230. top,
  8231. row,
  8232. width: itemWidth,
  8233. height: itemHeight
  8234. };
  8235. lineWidths[lineWidths.length - 1] += itemWidth + padding;
  8236. });
  8237. return totalHeight;
  8238. }
  8239. _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) {
  8240. const { ctx , maxHeight , options: { labels: { padding } } } = this;
  8241. const hitboxes = this.legendHitBoxes = [];
  8242. const columnSizes = this.columnSizes = [];
  8243. const heightLimit = maxHeight - titleHeight;
  8244. let totalWidth = padding;
  8245. let currentColWidth = 0;
  8246. let currentColHeight = 0;
  8247. let left = 0;
  8248. let col = 0;
  8249. this.legendItems.forEach((legendItem, i)=>{
  8250. const { itemWidth , itemHeight } = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight);
  8251. if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {
  8252. totalWidth += currentColWidth + padding;
  8253. columnSizes.push({
  8254. width: currentColWidth,
  8255. height: currentColHeight
  8256. });
  8257. left += currentColWidth + padding;
  8258. col++;
  8259. currentColWidth = currentColHeight = 0;
  8260. }
  8261. hitboxes[i] = {
  8262. left,
  8263. top: currentColHeight,
  8264. col,
  8265. width: itemWidth,
  8266. height: itemHeight
  8267. };
  8268. currentColWidth = Math.max(currentColWidth, itemWidth);
  8269. currentColHeight += itemHeight + padding;
  8270. });
  8271. totalWidth += currentColWidth;
  8272. columnSizes.push({
  8273. width: currentColWidth,
  8274. height: currentColHeight
  8275. });
  8276. return totalWidth;
  8277. }
  8278. adjustHitBoxes() {
  8279. if (!this.options.display) {
  8280. return;
  8281. }
  8282. const titleHeight = this._computeTitleHeight();
  8283. const { legendHitBoxes: hitboxes , options: { align , labels: { padding } , rtl } } = this;
  8284. const rtlHelper = getRtlAdapter(rtl, this.left, this.width);
  8285. if (this.isHorizontal()) {
  8286. let row = 0;
  8287. let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  8288. for (const hitbox of hitboxes){
  8289. if (row !== hitbox.row) {
  8290. row = hitbox.row;
  8291. left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  8292. }
  8293. hitbox.top += this.top + titleHeight + padding;
  8294. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);
  8295. left += hitbox.width + padding;
  8296. }
  8297. } else {
  8298. let col = 0;
  8299. let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  8300. for (const hitbox of hitboxes){
  8301. if (hitbox.col !== col) {
  8302. col = hitbox.col;
  8303. top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  8304. }
  8305. hitbox.top = top;
  8306. hitbox.left += this.left + padding;
  8307. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);
  8308. top += hitbox.height + padding;
  8309. }
  8310. }
  8311. }
  8312. isHorizontal() {
  8313. return this.options.position === 'top' || this.options.position === 'bottom';
  8314. }
  8315. draw() {
  8316. if (this.options.display) {
  8317. const ctx = this.ctx;
  8318. clipArea(ctx, this);
  8319. this._draw();
  8320. unclipArea(ctx);
  8321. }
  8322. }
  8323. _draw() {
  8324. const { options: opts , columnSizes , lineWidths , ctx } = this;
  8325. const { align , labels: labelOpts } = opts;
  8326. const defaultColor = defaults.color;
  8327. const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);
  8328. const labelFont = toFont(labelOpts.font);
  8329. const { padding } = labelOpts;
  8330. const fontSize = labelFont.size;
  8331. const halfFontSize = fontSize / 2;
  8332. let cursor;
  8333. this.drawTitle();
  8334. ctx.textAlign = rtlHelper.textAlign('left');
  8335. ctx.textBaseline = 'middle';
  8336. ctx.lineWidth = 0.5;
  8337. ctx.font = labelFont.string;
  8338. const { boxWidth , boxHeight , itemHeight } = getBoxSize(labelOpts, fontSize);
  8339. const drawLegendBox = function(x, y, legendItem) {
  8340. if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
  8341. return;
  8342. }
  8343. ctx.save();
  8344. const lineWidth = valueOrDefault(legendItem.lineWidth, 1);
  8345. ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
  8346. ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');
  8347. ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);
  8348. ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');
  8349. ctx.lineWidth = lineWidth;
  8350. ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);
  8351. ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));
  8352. if (labelOpts.usePointStyle) {
  8353. const drawOptions = {
  8354. radius: boxHeight * Math.SQRT2 / 2,
  8355. pointStyle: legendItem.pointStyle,
  8356. rotation: legendItem.rotation,
  8357. borderWidth: lineWidth
  8358. };
  8359. const centerX = rtlHelper.xPlus(x, boxWidth / 2);
  8360. const centerY = y + halfFontSize;
  8361. drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth);
  8362. } else {
  8363. const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
  8364. const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
  8365. const borderRadius = toTRBLCorners(legendItem.borderRadius);
  8366. ctx.beginPath();
  8367. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  8368. addRoundedRectPath(ctx, {
  8369. x: xBoxLeft,
  8370. y: yBoxTop,
  8371. w: boxWidth,
  8372. h: boxHeight,
  8373. radius: borderRadius
  8374. });
  8375. } else {
  8376. ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
  8377. }
  8378. ctx.fill();
  8379. if (lineWidth !== 0) {
  8380. ctx.stroke();
  8381. }
  8382. }
  8383. ctx.restore();
  8384. };
  8385. const fillText = function(x, y, legendItem) {
  8386. renderText(ctx, legendItem.text, x, y + itemHeight / 2, labelFont, {
  8387. strikethrough: legendItem.hidden,
  8388. textAlign: rtlHelper.textAlign(legendItem.textAlign)
  8389. });
  8390. };
  8391. const isHorizontal = this.isHorizontal();
  8392. const titleHeight = this._computeTitleHeight();
  8393. if (isHorizontal) {
  8394. cursor = {
  8395. x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]),
  8396. y: this.top + padding + titleHeight,
  8397. line: 0
  8398. };
  8399. } else {
  8400. cursor = {
  8401. x: this.left + padding,
  8402. y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height),
  8403. line: 0
  8404. };
  8405. }
  8406. overrideTextDirection(this.ctx, opts.textDirection);
  8407. const lineHeight = itemHeight + padding;
  8408. this.legendItems.forEach((legendItem, i)=>{
  8409. ctx.strokeStyle = legendItem.fontColor;
  8410. ctx.fillStyle = legendItem.fontColor;
  8411. const textWidth = ctx.measureText(legendItem.text).width;
  8412. const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
  8413. const width = boxWidth + halfFontSize + textWidth;
  8414. let x = cursor.x;
  8415. let y = cursor.y;
  8416. rtlHelper.setWidth(this.width);
  8417. if (isHorizontal) {
  8418. if (i > 0 && x + width + padding > this.right) {
  8419. y = cursor.y += lineHeight;
  8420. cursor.line++;
  8421. x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]);
  8422. }
  8423. } else if (i > 0 && y + lineHeight > this.bottom) {
  8424. x = cursor.x = x + columnSizes[cursor.line].width + padding;
  8425. cursor.line++;
  8426. y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height);
  8427. }
  8428. const realX = rtlHelper.x(x);
  8429. drawLegendBox(realX, y, legendItem);
  8430. x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl);
  8431. fillText(rtlHelper.x(x), y, legendItem);
  8432. if (isHorizontal) {
  8433. cursor.x += width + padding;
  8434. } else if (typeof legendItem.text !== 'string') {
  8435. const fontLineHeight = labelFont.lineHeight;
  8436. cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding;
  8437. } else {
  8438. cursor.y += lineHeight;
  8439. }
  8440. });
  8441. restoreTextDirection(this.ctx, opts.textDirection);
  8442. }
  8443. drawTitle() {
  8444. const opts = this.options;
  8445. const titleOpts = opts.title;
  8446. const titleFont = toFont(titleOpts.font);
  8447. const titlePadding = toPadding(titleOpts.padding);
  8448. if (!titleOpts.display) {
  8449. return;
  8450. }
  8451. const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);
  8452. const ctx = this.ctx;
  8453. const position = titleOpts.position;
  8454. const halfFontSize = titleFont.size / 2;
  8455. const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
  8456. let y;
  8457. let left = this.left;
  8458. let maxWidth = this.width;
  8459. if (this.isHorizontal()) {
  8460. maxWidth = Math.max(...this.lineWidths);
  8461. y = this.top + topPaddingPlusHalfFontSize;
  8462. left = _alignStartEnd(opts.align, left, this.right - maxWidth);
  8463. } else {
  8464. const maxHeight = this.columnSizes.reduce((acc, size)=>Math.max(acc, size.height), 0);
  8465. y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight());
  8466. }
  8467. const x = _alignStartEnd(position, left, left + maxWidth);
  8468. ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));
  8469. ctx.textBaseline = 'middle';
  8470. ctx.strokeStyle = titleOpts.color;
  8471. ctx.fillStyle = titleOpts.color;
  8472. ctx.font = titleFont.string;
  8473. renderText(ctx, titleOpts.text, x, y, titleFont);
  8474. }
  8475. _computeTitleHeight() {
  8476. const titleOpts = this.options.title;
  8477. const titleFont = toFont(titleOpts.font);
  8478. const titlePadding = toPadding(titleOpts.padding);
  8479. return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
  8480. }
  8481. _getLegendItemAt(x, y) {
  8482. let i, hitBox, lh;
  8483. if (_isBetween(x, this.left, this.right) && _isBetween(y, this.top, this.bottom)) {
  8484. lh = this.legendHitBoxes;
  8485. for(i = 0; i < lh.length; ++i){
  8486. hitBox = lh[i];
  8487. if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width) && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) {
  8488. return this.legendItems[i];
  8489. }
  8490. }
  8491. }
  8492. return null;
  8493. }
  8494. handleEvent(e) {
  8495. const opts = this.options;
  8496. if (!isListened(e.type, opts)) {
  8497. return;
  8498. }
  8499. const hoveredItem = this._getLegendItemAt(e.x, e.y);
  8500. if (e.type === 'mousemove' || e.type === 'mouseout') {
  8501. const previous = this._hoveredItem;
  8502. const sameItem = itemsEqual(previous, hoveredItem);
  8503. if (previous && !sameItem) {
  8504. callback(opts.onLeave, [
  8505. e,
  8506. previous,
  8507. this
  8508. ], this);
  8509. }
  8510. this._hoveredItem = hoveredItem;
  8511. if (hoveredItem && !sameItem) {
  8512. callback(opts.onHover, [
  8513. e,
  8514. hoveredItem,
  8515. this
  8516. ], this);
  8517. }
  8518. } else if (hoveredItem) {
  8519. callback(opts.onClick, [
  8520. e,
  8521. hoveredItem,
  8522. this
  8523. ], this);
  8524. }
  8525. }
  8526. }
  8527. function calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) {
  8528. const itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx);
  8529. const itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight);
  8530. return {
  8531. itemWidth,
  8532. itemHeight
  8533. };
  8534. }
  8535. function calculateItemWidth(legendItem, boxWidth, labelFont, ctx) {
  8536. let legendItemText = legendItem.text;
  8537. if (legendItemText && typeof legendItemText !== 'string') {
  8538. legendItemText = legendItemText.reduce((a, b)=>a.length > b.length ? a : b);
  8539. }
  8540. return boxWidth + labelFont.size / 2 + ctx.measureText(legendItemText).width;
  8541. }
  8542. function calculateItemHeight(_itemHeight, legendItem, fontLineHeight) {
  8543. let itemHeight = _itemHeight;
  8544. if (typeof legendItem.text !== 'string') {
  8545. itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight);
  8546. }
  8547. return itemHeight;
  8548. }
  8549. function calculateLegendItemHeight(legendItem, fontLineHeight) {
  8550. const labelHeight = legendItem.text ? legendItem.text.length : 0;
  8551. return fontLineHeight * labelHeight;
  8552. }
  8553. function isListened(type, opts) {
  8554. if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) {
  8555. return true;
  8556. }
  8557. if (opts.onClick && (type === 'click' || type === 'mouseup')) {
  8558. return true;
  8559. }
  8560. return false;
  8561. }
  8562. var plugin_legend = {
  8563. id: 'legend',
  8564. _element: Legend,
  8565. start (chart, _args, options) {
  8566. const legend = chart.legend = new Legend({
  8567. ctx: chart.ctx,
  8568. options,
  8569. chart
  8570. });
  8571. layouts.configure(chart, legend, options);
  8572. layouts.addBox(chart, legend);
  8573. },
  8574. stop (chart) {
  8575. layouts.removeBox(chart, chart.legend);
  8576. delete chart.legend;
  8577. },
  8578. beforeUpdate (chart, _args, options) {
  8579. const legend = chart.legend;
  8580. layouts.configure(chart, legend, options);
  8581. legend.options = options;
  8582. },
  8583. afterUpdate (chart) {
  8584. const legend = chart.legend;
  8585. legend.buildLabels();
  8586. legend.adjustHitBoxes();
  8587. },
  8588. afterEvent (chart, args) {
  8589. if (!args.replay) {
  8590. chart.legend.handleEvent(args.event);
  8591. }
  8592. },
  8593. defaults: {
  8594. display: true,
  8595. position: 'top',
  8596. align: 'center',
  8597. fullSize: true,
  8598. reverse: false,
  8599. weight: 1000,
  8600. onClick (e, legendItem, legend) {
  8601. const index = legendItem.datasetIndex;
  8602. const ci = legend.chart;
  8603. if (ci.isDatasetVisible(index)) {
  8604. ci.hide(index);
  8605. legendItem.hidden = true;
  8606. } else {
  8607. ci.show(index);
  8608. legendItem.hidden = false;
  8609. }
  8610. },
  8611. onHover: null,
  8612. onLeave: null,
  8613. labels: {
  8614. color: (ctx)=>ctx.chart.options.color,
  8615. boxWidth: 40,
  8616. padding: 10,
  8617. generateLabels (chart) {
  8618. const datasets = chart.data.datasets;
  8619. const { labels: { usePointStyle , pointStyle , textAlign , color , useBorderRadius , borderRadius } } = chart.legend.options;
  8620. return chart._getSortedDatasetMetas().map((meta)=>{
  8621. const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  8622. const borderWidth = toPadding(style.borderWidth);
  8623. return {
  8624. text: datasets[meta.index].label,
  8625. fillStyle: style.backgroundColor,
  8626. fontColor: color,
  8627. hidden: !meta.visible,
  8628. lineCap: style.borderCapStyle,
  8629. lineDash: style.borderDash,
  8630. lineDashOffset: style.borderDashOffset,
  8631. lineJoin: style.borderJoinStyle,
  8632. lineWidth: (borderWidth.width + borderWidth.height) / 4,
  8633. strokeStyle: style.borderColor,
  8634. pointStyle: pointStyle || style.pointStyle,
  8635. rotation: style.rotation,
  8636. textAlign: textAlign || style.textAlign,
  8637. borderRadius: useBorderRadius && (borderRadius || style.borderRadius),
  8638. datasetIndex: meta.index
  8639. };
  8640. }, this);
  8641. }
  8642. },
  8643. title: {
  8644. color: (ctx)=>ctx.chart.options.color,
  8645. display: false,
  8646. position: 'center',
  8647. text: ''
  8648. }
  8649. },
  8650. descriptors: {
  8651. _scriptable: (name)=>!name.startsWith('on'),
  8652. labels: {
  8653. _scriptable: (name)=>![
  8654. 'generateLabels',
  8655. 'filter',
  8656. 'sort'
  8657. ].includes(name)
  8658. }
  8659. }
  8660. };
  8661. class Title extends Element {
  8662. constructor(config){
  8663. super();
  8664. this.chart = config.chart;
  8665. this.options = config.options;
  8666. this.ctx = config.ctx;
  8667. this._padding = undefined;
  8668. this.top = undefined;
  8669. this.bottom = undefined;
  8670. this.left = undefined;
  8671. this.right = undefined;
  8672. this.width = undefined;
  8673. this.height = undefined;
  8674. this.position = undefined;
  8675. this.weight = undefined;
  8676. this.fullSize = undefined;
  8677. }
  8678. update(maxWidth, maxHeight) {
  8679. const opts = this.options;
  8680. this.left = 0;
  8681. this.top = 0;
  8682. if (!opts.display) {
  8683. this.width = this.height = this.right = this.bottom = 0;
  8684. return;
  8685. }
  8686. this.width = this.right = maxWidth;
  8687. this.height = this.bottom = maxHeight;
  8688. const lineCount = isArray(opts.text) ? opts.text.length : 1;
  8689. this._padding = toPadding(opts.padding);
  8690. const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height;
  8691. if (this.isHorizontal()) {
  8692. this.height = textSize;
  8693. } else {
  8694. this.width = textSize;
  8695. }
  8696. }
  8697. isHorizontal() {
  8698. const pos = this.options.position;
  8699. return pos === 'top' || pos === 'bottom';
  8700. }
  8701. _drawArgs(offset) {
  8702. const { top , left , bottom , right , options } = this;
  8703. const align = options.align;
  8704. let rotation = 0;
  8705. let maxWidth, titleX, titleY;
  8706. if (this.isHorizontal()) {
  8707. titleX = _alignStartEnd(align, left, right);
  8708. titleY = top + offset;
  8709. maxWidth = right - left;
  8710. } else {
  8711. if (options.position === 'left') {
  8712. titleX = left + offset;
  8713. titleY = _alignStartEnd(align, bottom, top);
  8714. rotation = PI * -0.5;
  8715. } else {
  8716. titleX = right - offset;
  8717. titleY = _alignStartEnd(align, top, bottom);
  8718. rotation = PI * 0.5;
  8719. }
  8720. maxWidth = bottom - top;
  8721. }
  8722. return {
  8723. titleX,
  8724. titleY,
  8725. maxWidth,
  8726. rotation
  8727. };
  8728. }
  8729. draw() {
  8730. const ctx = this.ctx;
  8731. const opts = this.options;
  8732. if (!opts.display) {
  8733. return;
  8734. }
  8735. const fontOpts = toFont(opts.font);
  8736. const lineHeight = fontOpts.lineHeight;
  8737. const offset = lineHeight / 2 + this._padding.top;
  8738. const { titleX , titleY , maxWidth , rotation } = this._drawArgs(offset);
  8739. renderText(ctx, opts.text, 0, 0, fontOpts, {
  8740. color: opts.color,
  8741. maxWidth,
  8742. rotation,
  8743. textAlign: _toLeftRightCenter(opts.align),
  8744. textBaseline: 'middle',
  8745. translation: [
  8746. titleX,
  8747. titleY
  8748. ]
  8749. });
  8750. }
  8751. }
  8752. function createTitle(chart, titleOpts) {
  8753. const title = new Title({
  8754. ctx: chart.ctx,
  8755. options: titleOpts,
  8756. chart
  8757. });
  8758. layouts.configure(chart, title, titleOpts);
  8759. layouts.addBox(chart, title);
  8760. chart.titleBlock = title;
  8761. }
  8762. var plugin_title = {
  8763. id: 'title',
  8764. _element: Title,
  8765. start (chart, _args, options) {
  8766. createTitle(chart, options);
  8767. },
  8768. stop (chart) {
  8769. const titleBlock = chart.titleBlock;
  8770. layouts.removeBox(chart, titleBlock);
  8771. delete chart.titleBlock;
  8772. },
  8773. beforeUpdate (chart, _args, options) {
  8774. const title = chart.titleBlock;
  8775. layouts.configure(chart, title, options);
  8776. title.options = options;
  8777. },
  8778. defaults: {
  8779. align: 'center',
  8780. display: false,
  8781. font: {
  8782. weight: 'bold'
  8783. },
  8784. fullSize: true,
  8785. padding: 10,
  8786. position: 'top',
  8787. text: '',
  8788. weight: 2000
  8789. },
  8790. defaultRoutes: {
  8791. color: 'color'
  8792. },
  8793. descriptors: {
  8794. _scriptable: true,
  8795. _indexable: false
  8796. }
  8797. };
  8798. const map = new WeakMap();
  8799. var plugin_subtitle = {
  8800. id: 'subtitle',
  8801. start (chart, _args, options) {
  8802. const title = new Title({
  8803. ctx: chart.ctx,
  8804. options,
  8805. chart
  8806. });
  8807. layouts.configure(chart, title, options);
  8808. layouts.addBox(chart, title);
  8809. map.set(chart, title);
  8810. },
  8811. stop (chart) {
  8812. layouts.removeBox(chart, map.get(chart));
  8813. map.delete(chart);
  8814. },
  8815. beforeUpdate (chart, _args, options) {
  8816. const title = map.get(chart);
  8817. layouts.configure(chart, title, options);
  8818. title.options = options;
  8819. },
  8820. defaults: {
  8821. align: 'center',
  8822. display: false,
  8823. font: {
  8824. weight: 'normal'
  8825. },
  8826. fullSize: true,
  8827. padding: 0,
  8828. position: 'top',
  8829. text: '',
  8830. weight: 1500
  8831. },
  8832. defaultRoutes: {
  8833. color: 'color'
  8834. },
  8835. descriptors: {
  8836. _scriptable: true,
  8837. _indexable: false
  8838. }
  8839. };
  8840. const positioners = {
  8841. average (items) {
  8842. if (!items.length) {
  8843. return false;
  8844. }
  8845. let i, len;
  8846. let xSet = new Set();
  8847. let y = 0;
  8848. let count = 0;
  8849. for(i = 0, len = items.length; i < len; ++i){
  8850. const el = items[i].element;
  8851. if (el && el.hasValue()) {
  8852. const pos = el.tooltipPosition();
  8853. xSet.add(pos.x);
  8854. y += pos.y;
  8855. ++count;
  8856. }
  8857. }
  8858. const xAverage = [
  8859. ...xSet
  8860. ].reduce((a, b)=>a + b) / xSet.size;
  8861. return {
  8862. x: xAverage,
  8863. y: y / count
  8864. };
  8865. },
  8866. nearest (items, eventPosition) {
  8867. if (!items.length) {
  8868. return false;
  8869. }
  8870. let x = eventPosition.x;
  8871. let y = eventPosition.y;
  8872. let minDistance = Number.POSITIVE_INFINITY;
  8873. let i, len, nearestElement;
  8874. for(i = 0, len = items.length; i < len; ++i){
  8875. const el = items[i].element;
  8876. if (el && el.hasValue()) {
  8877. const center = el.getCenterPoint();
  8878. const d = distanceBetweenPoints(eventPosition, center);
  8879. if (d < minDistance) {
  8880. minDistance = d;
  8881. nearestElement = el;
  8882. }
  8883. }
  8884. }
  8885. if (nearestElement) {
  8886. const tp = nearestElement.tooltipPosition();
  8887. x = tp.x;
  8888. y = tp.y;
  8889. }
  8890. return {
  8891. x,
  8892. y
  8893. };
  8894. }
  8895. };
  8896. function pushOrConcat(base, toPush) {
  8897. if (toPush) {
  8898. if (isArray(toPush)) {
  8899. Array.prototype.push.apply(base, toPush);
  8900. } else {
  8901. base.push(toPush);
  8902. }
  8903. }
  8904. return base;
  8905. }
  8906. function splitNewlines(str) {
  8907. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  8908. return str.split('\n');
  8909. }
  8910. return str;
  8911. }
  8912. function createTooltipItem(chart, item) {
  8913. const { element , datasetIndex , index } = item;
  8914. const controller = chart.getDatasetMeta(datasetIndex).controller;
  8915. const { label , value } = controller.getLabelAndValue(index);
  8916. return {
  8917. chart,
  8918. label,
  8919. parsed: controller.getParsed(index),
  8920. raw: chart.data.datasets[datasetIndex].data[index],
  8921. formattedValue: value,
  8922. dataset: controller.getDataset(),
  8923. dataIndex: index,
  8924. datasetIndex,
  8925. element
  8926. };
  8927. }
  8928. function getTooltipSize(tooltip, options) {
  8929. const ctx = tooltip.chart.ctx;
  8930. const { body , footer , title } = tooltip;
  8931. const { boxWidth , boxHeight } = options;
  8932. const bodyFont = toFont(options.bodyFont);
  8933. const titleFont = toFont(options.titleFont);
  8934. const footerFont = toFont(options.footerFont);
  8935. const titleLineCount = title.length;
  8936. const footerLineCount = footer.length;
  8937. const bodyLineItemCount = body.length;
  8938. const padding = toPadding(options.padding);
  8939. let height = padding.height;
  8940. let width = 0;
  8941. let combinedBodyLength = body.reduce((count, bodyItem)=>count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
  8942. combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
  8943. if (titleLineCount) {
  8944. height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom;
  8945. }
  8946. if (combinedBodyLength) {
  8947. const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
  8948. height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing;
  8949. }
  8950. if (footerLineCount) {
  8951. height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing;
  8952. }
  8953. let widthPadding = 0;
  8954. const maxLineWidth = function(line) {
  8955. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  8956. };
  8957. ctx.save();
  8958. ctx.font = titleFont.string;
  8959. each(tooltip.title, maxLineWidth);
  8960. ctx.font = bodyFont.string;
  8961. each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
  8962. widthPadding = options.displayColors ? boxWidth + 2 + options.boxPadding : 0;
  8963. each(body, (bodyItem)=>{
  8964. each(bodyItem.before, maxLineWidth);
  8965. each(bodyItem.lines, maxLineWidth);
  8966. each(bodyItem.after, maxLineWidth);
  8967. });
  8968. widthPadding = 0;
  8969. ctx.font = footerFont.string;
  8970. each(tooltip.footer, maxLineWidth);
  8971. ctx.restore();
  8972. width += padding.width;
  8973. return {
  8974. width,
  8975. height
  8976. };
  8977. }
  8978. function determineYAlign(chart, size) {
  8979. const { y , height } = size;
  8980. if (y < height / 2) {
  8981. return 'top';
  8982. } else if (y > chart.height - height / 2) {
  8983. return 'bottom';
  8984. }
  8985. return 'center';
  8986. }
  8987. function doesNotFitWithAlign(xAlign, chart, options, size) {
  8988. const { x , width } = size;
  8989. const caret = options.caretSize + options.caretPadding;
  8990. if (xAlign === 'left' && x + width + caret > chart.width) {
  8991. return true;
  8992. }
  8993. if (xAlign === 'right' && x - width - caret < 0) {
  8994. return true;
  8995. }
  8996. }
  8997. function determineXAlign(chart, options, size, yAlign) {
  8998. const { x , width } = size;
  8999. const { width: chartWidth , chartArea: { left , right } } = chart;
  9000. let xAlign = 'center';
  9001. if (yAlign === 'center') {
  9002. xAlign = x <= (left + right) / 2 ? 'left' : 'right';
  9003. } else if (x <= width / 2) {
  9004. xAlign = 'left';
  9005. } else if (x >= chartWidth - width / 2) {
  9006. xAlign = 'right';
  9007. }
  9008. if (doesNotFitWithAlign(xAlign, chart, options, size)) {
  9009. xAlign = 'center';
  9010. }
  9011. return xAlign;
  9012. }
  9013. function determineAlignment(chart, options, size) {
  9014. const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size);
  9015. return {
  9016. xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign),
  9017. yAlign
  9018. };
  9019. }
  9020. function alignX(size, xAlign) {
  9021. let { x , width } = size;
  9022. if (xAlign === 'right') {
  9023. x -= width;
  9024. } else if (xAlign === 'center') {
  9025. x -= width / 2;
  9026. }
  9027. return x;
  9028. }
  9029. function alignY(size, yAlign, paddingAndSize) {
  9030. let { y , height } = size;
  9031. if (yAlign === 'top') {
  9032. y += paddingAndSize;
  9033. } else if (yAlign === 'bottom') {
  9034. y -= height + paddingAndSize;
  9035. } else {
  9036. y -= height / 2;
  9037. }
  9038. return y;
  9039. }
  9040. function getBackgroundPoint(options, size, alignment, chart) {
  9041. const { caretSize , caretPadding , cornerRadius } = options;
  9042. const { xAlign , yAlign } = alignment;
  9043. const paddingAndSize = caretSize + caretPadding;
  9044. const { topLeft , topRight , bottomLeft , bottomRight } = toTRBLCorners(cornerRadius);
  9045. let x = alignX(size, xAlign);
  9046. const y = alignY(size, yAlign, paddingAndSize);
  9047. if (yAlign === 'center') {
  9048. if (xAlign === 'left') {
  9049. x += paddingAndSize;
  9050. } else if (xAlign === 'right') {
  9051. x -= paddingAndSize;
  9052. }
  9053. } else if (xAlign === 'left') {
  9054. x -= Math.max(topLeft, bottomLeft) + caretSize;
  9055. } else if (xAlign === 'right') {
  9056. x += Math.max(topRight, bottomRight) + caretSize;
  9057. }
  9058. return {
  9059. x: _limitValue(x, 0, chart.width - size.width),
  9060. y: _limitValue(y, 0, chart.height - size.height)
  9061. };
  9062. }
  9063. function getAlignedX(tooltip, align, options) {
  9064. const padding = toPadding(options.padding);
  9065. return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left;
  9066. }
  9067. function getBeforeAfterBodyLines(callback) {
  9068. return pushOrConcat([], splitNewlines(callback));
  9069. }
  9070. function createTooltipContext(parent, tooltip, tooltipItems) {
  9071. return createContext(parent, {
  9072. tooltip,
  9073. tooltipItems,
  9074. type: 'tooltip'
  9075. });
  9076. }
  9077. function overrideCallbacks(callbacks, context) {
  9078. const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
  9079. return override ? callbacks.override(override) : callbacks;
  9080. }
  9081. const defaultCallbacks = {
  9082. beforeTitle: noop,
  9083. title (tooltipItems) {
  9084. if (tooltipItems.length > 0) {
  9085. const item = tooltipItems[0];
  9086. const labels = item.chart.data.labels;
  9087. const labelCount = labels ? labels.length : 0;
  9088. if (this && this.options && this.options.mode === 'dataset') {
  9089. return item.dataset.label || '';
  9090. } else if (item.label) {
  9091. return item.label;
  9092. } else if (labelCount > 0 && item.dataIndex < labelCount) {
  9093. return labels[item.dataIndex];
  9094. }
  9095. }
  9096. return '';
  9097. },
  9098. afterTitle: noop,
  9099. beforeBody: noop,
  9100. beforeLabel: noop,
  9101. label (tooltipItem) {
  9102. if (this && this.options && this.options.mode === 'dataset') {
  9103. return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
  9104. }
  9105. let label = tooltipItem.dataset.label || '';
  9106. if (label) {
  9107. label += ': ';
  9108. }
  9109. const value = tooltipItem.formattedValue;
  9110. if (!isNullOrUndef(value)) {
  9111. label += value;
  9112. }
  9113. return label;
  9114. },
  9115. labelColor (tooltipItem) {
  9116. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9117. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9118. return {
  9119. borderColor: options.borderColor,
  9120. backgroundColor: options.backgroundColor,
  9121. borderWidth: options.borderWidth,
  9122. borderDash: options.borderDash,
  9123. borderDashOffset: options.borderDashOffset,
  9124. borderRadius: 0
  9125. };
  9126. },
  9127. labelTextColor () {
  9128. return this.options.bodyColor;
  9129. },
  9130. labelPointStyle (tooltipItem) {
  9131. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9132. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9133. return {
  9134. pointStyle: options.pointStyle,
  9135. rotation: options.rotation
  9136. };
  9137. },
  9138. afterLabel: noop,
  9139. afterBody: noop,
  9140. beforeFooter: noop,
  9141. footer: noop,
  9142. afterFooter: noop
  9143. };
  9144. function invokeCallbackWithFallback(callbacks, name, ctx, arg) {
  9145. const result = callbacks[name].call(ctx, arg);
  9146. if (typeof result === 'undefined') {
  9147. return defaultCallbacks[name].call(ctx, arg);
  9148. }
  9149. return result;
  9150. }
  9151. class Tooltip extends Element {
  9152. static positioners = positioners;
  9153. constructor(config){
  9154. super();
  9155. this.opacity = 0;
  9156. this._active = [];
  9157. this._eventPosition = undefined;
  9158. this._size = undefined;
  9159. this._cachedAnimations = undefined;
  9160. this._tooltipItems = [];
  9161. this.$animations = undefined;
  9162. this.$context = undefined;
  9163. this.chart = config.chart;
  9164. this.options = config.options;
  9165. this.dataPoints = undefined;
  9166. this.title = undefined;
  9167. this.beforeBody = undefined;
  9168. this.body = undefined;
  9169. this.afterBody = undefined;
  9170. this.footer = undefined;
  9171. this.xAlign = undefined;
  9172. this.yAlign = undefined;
  9173. this.x = undefined;
  9174. this.y = undefined;
  9175. this.height = undefined;
  9176. this.width = undefined;
  9177. this.caretX = undefined;
  9178. this.caretY = undefined;
  9179. this.labelColors = undefined;
  9180. this.labelPointStyles = undefined;
  9181. this.labelTextColors = undefined;
  9182. }
  9183. initialize(options) {
  9184. this.options = options;
  9185. this._cachedAnimations = undefined;
  9186. this.$context = undefined;
  9187. }
  9188. _resolveAnimations() {
  9189. const cached = this._cachedAnimations;
  9190. if (cached) {
  9191. return cached;
  9192. }
  9193. const chart = this.chart;
  9194. const options = this.options.setContext(this.getContext());
  9195. const opts = options.enabled && chart.options.animation && options.animations;
  9196. const animations = new Animations(this.chart, opts);
  9197. if (opts._cacheable) {
  9198. this._cachedAnimations = Object.freeze(animations);
  9199. }
  9200. return animations;
  9201. }
  9202. getContext() {
  9203. return this.$context || (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems));
  9204. }
  9205. getTitle(context, options) {
  9206. const { callbacks } = options;
  9207. const beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context);
  9208. const title = invokeCallbackWithFallback(callbacks, 'title', this, context);
  9209. const afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context);
  9210. let lines = [];
  9211. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  9212. lines = pushOrConcat(lines, splitNewlines(title));
  9213. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  9214. return lines;
  9215. }
  9216. getBeforeBody(tooltipItems, options) {
  9217. return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems));
  9218. }
  9219. getBody(tooltipItems, options) {
  9220. const { callbacks } = options;
  9221. const bodyItems = [];
  9222. each(tooltipItems, (context)=>{
  9223. const bodyItem = {
  9224. before: [],
  9225. lines: [],
  9226. after: []
  9227. };
  9228. const scoped = overrideCallbacks(callbacks, context);
  9229. pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', this, context)));
  9230. pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', this, context));
  9231. pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', this, context)));
  9232. bodyItems.push(bodyItem);
  9233. });
  9234. return bodyItems;
  9235. }
  9236. getAfterBody(tooltipItems, options) {
  9237. return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems));
  9238. }
  9239. getFooter(tooltipItems, options) {
  9240. const { callbacks } = options;
  9241. const beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems);
  9242. const footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems);
  9243. const afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems);
  9244. let lines = [];
  9245. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  9246. lines = pushOrConcat(lines, splitNewlines(footer));
  9247. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  9248. return lines;
  9249. }
  9250. _createItems(options) {
  9251. const active = this._active;
  9252. const data = this.chart.data;
  9253. const labelColors = [];
  9254. const labelPointStyles = [];
  9255. const labelTextColors = [];
  9256. let tooltipItems = [];
  9257. let i, len;
  9258. for(i = 0, len = active.length; i < len; ++i){
  9259. tooltipItems.push(createTooltipItem(this.chart, active[i]));
  9260. }
  9261. if (options.filter) {
  9262. tooltipItems = tooltipItems.filter((element, index, array)=>options.filter(element, index, array, data));
  9263. }
  9264. if (options.itemSort) {
  9265. tooltipItems = tooltipItems.sort((a, b)=>options.itemSort(a, b, data));
  9266. }
  9267. each(tooltipItems, (context)=>{
  9268. const scoped = overrideCallbacks(options.callbacks, context);
  9269. labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', this, context));
  9270. labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', this, context));
  9271. labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', this, context));
  9272. });
  9273. this.labelColors = labelColors;
  9274. this.labelPointStyles = labelPointStyles;
  9275. this.labelTextColors = labelTextColors;
  9276. this.dataPoints = tooltipItems;
  9277. return tooltipItems;
  9278. }
  9279. update(changed, replay) {
  9280. const options = this.options.setContext(this.getContext());
  9281. const active = this._active;
  9282. let properties;
  9283. let tooltipItems = [];
  9284. if (!active.length) {
  9285. if (this.opacity !== 0) {
  9286. properties = {
  9287. opacity: 0
  9288. };
  9289. }
  9290. } else {
  9291. const position = positioners[options.position].call(this, active, this._eventPosition);
  9292. tooltipItems = this._createItems(options);
  9293. this.title = this.getTitle(tooltipItems, options);
  9294. this.beforeBody = this.getBeforeBody(tooltipItems, options);
  9295. this.body = this.getBody(tooltipItems, options);
  9296. this.afterBody = this.getAfterBody(tooltipItems, options);
  9297. this.footer = this.getFooter(tooltipItems, options);
  9298. const size = this._size = getTooltipSize(this, options);
  9299. const positionAndSize = Object.assign({}, position, size);
  9300. const alignment = determineAlignment(this.chart, options, positionAndSize);
  9301. const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart);
  9302. this.xAlign = alignment.xAlign;
  9303. this.yAlign = alignment.yAlign;
  9304. properties = {
  9305. opacity: 1,
  9306. x: backgroundPoint.x,
  9307. y: backgroundPoint.y,
  9308. width: size.width,
  9309. height: size.height,
  9310. caretX: position.x,
  9311. caretY: position.y
  9312. };
  9313. }
  9314. this._tooltipItems = tooltipItems;
  9315. this.$context = undefined;
  9316. if (properties) {
  9317. this._resolveAnimations().update(this, properties);
  9318. }
  9319. if (changed && options.external) {
  9320. options.external.call(this, {
  9321. chart: this.chart,
  9322. tooltip: this,
  9323. replay
  9324. });
  9325. }
  9326. }
  9327. drawCaret(tooltipPoint, ctx, size, options) {
  9328. const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
  9329. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  9330. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  9331. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  9332. }
  9333. getCaretPosition(tooltipPoint, size, options) {
  9334. const { xAlign , yAlign } = this;
  9335. const { caretSize , cornerRadius } = options;
  9336. const { topLeft , topRight , bottomLeft , bottomRight } = toTRBLCorners(cornerRadius);
  9337. const { x: ptX , y: ptY } = tooltipPoint;
  9338. const { width , height } = size;
  9339. let x1, x2, x3, y1, y2, y3;
  9340. if (yAlign === 'center') {
  9341. y2 = ptY + height / 2;
  9342. if (xAlign === 'left') {
  9343. x1 = ptX;
  9344. x2 = x1 - caretSize;
  9345. y1 = y2 + caretSize;
  9346. y3 = y2 - caretSize;
  9347. } else {
  9348. x1 = ptX + width;
  9349. x2 = x1 + caretSize;
  9350. y1 = y2 - caretSize;
  9351. y3 = y2 + caretSize;
  9352. }
  9353. x3 = x1;
  9354. } else {
  9355. if (xAlign === 'left') {
  9356. x2 = ptX + Math.max(topLeft, bottomLeft) + caretSize;
  9357. } else if (xAlign === 'right') {
  9358. x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize;
  9359. } else {
  9360. x2 = this.caretX;
  9361. }
  9362. if (yAlign === 'top') {
  9363. y1 = ptY;
  9364. y2 = y1 - caretSize;
  9365. x1 = x2 - caretSize;
  9366. x3 = x2 + caretSize;
  9367. } else {
  9368. y1 = ptY + height;
  9369. y2 = y1 + caretSize;
  9370. x1 = x2 + caretSize;
  9371. x3 = x2 - caretSize;
  9372. }
  9373. y3 = y1;
  9374. }
  9375. return {
  9376. x1,
  9377. x2,
  9378. x3,
  9379. y1,
  9380. y2,
  9381. y3
  9382. };
  9383. }
  9384. drawTitle(pt, ctx, options) {
  9385. const title = this.title;
  9386. const length = title.length;
  9387. let titleFont, titleSpacing, i;
  9388. if (length) {
  9389. const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
  9390. pt.x = getAlignedX(this, options.titleAlign, options);
  9391. ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
  9392. ctx.textBaseline = 'middle';
  9393. titleFont = toFont(options.titleFont);
  9394. titleSpacing = options.titleSpacing;
  9395. ctx.fillStyle = options.titleColor;
  9396. ctx.font = titleFont.string;
  9397. for(i = 0; i < length; ++i){
  9398. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
  9399. pt.y += titleFont.lineHeight + titleSpacing;
  9400. if (i + 1 === length) {
  9401. pt.y += options.titleMarginBottom - titleSpacing;
  9402. }
  9403. }
  9404. }
  9405. }
  9406. _drawColorBox(ctx, pt, i, rtlHelper, options) {
  9407. const labelColor = this.labelColors[i];
  9408. const labelPointStyle = this.labelPointStyles[i];
  9409. const { boxHeight , boxWidth } = options;
  9410. const bodyFont = toFont(options.bodyFont);
  9411. const colorX = getAlignedX(this, 'left', options);
  9412. const rtlColorX = rtlHelper.x(colorX);
  9413. const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
  9414. const colorY = pt.y + yOffSet;
  9415. if (options.usePointStyle) {
  9416. const drawOptions = {
  9417. radius: Math.min(boxWidth, boxHeight) / 2,
  9418. pointStyle: labelPointStyle.pointStyle,
  9419. rotation: labelPointStyle.rotation,
  9420. borderWidth: 1
  9421. };
  9422. const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
  9423. const centerY = colorY + boxHeight / 2;
  9424. ctx.strokeStyle = options.multiKeyBackground;
  9425. ctx.fillStyle = options.multiKeyBackground;
  9426. drawPoint(ctx, drawOptions, centerX, centerY);
  9427. ctx.strokeStyle = labelColor.borderColor;
  9428. ctx.fillStyle = labelColor.backgroundColor;
  9429. drawPoint(ctx, drawOptions, centerX, centerY);
  9430. } else {
  9431. ctx.lineWidth = isObject(labelColor.borderWidth) ? Math.max(...Object.values(labelColor.borderWidth)) : labelColor.borderWidth || 1;
  9432. ctx.strokeStyle = labelColor.borderColor;
  9433. ctx.setLineDash(labelColor.borderDash || []);
  9434. ctx.lineDashOffset = labelColor.borderDashOffset || 0;
  9435. const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
  9436. const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
  9437. const borderRadius = toTRBLCorners(labelColor.borderRadius);
  9438. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  9439. ctx.beginPath();
  9440. ctx.fillStyle = options.multiKeyBackground;
  9441. addRoundedRectPath(ctx, {
  9442. x: outerX,
  9443. y: colorY,
  9444. w: boxWidth,
  9445. h: boxHeight,
  9446. radius: borderRadius
  9447. });
  9448. ctx.fill();
  9449. ctx.stroke();
  9450. ctx.fillStyle = labelColor.backgroundColor;
  9451. ctx.beginPath();
  9452. addRoundedRectPath(ctx, {
  9453. x: innerX,
  9454. y: colorY + 1,
  9455. w: boxWidth - 2,
  9456. h: boxHeight - 2,
  9457. radius: borderRadius
  9458. });
  9459. ctx.fill();
  9460. } else {
  9461. ctx.fillStyle = options.multiKeyBackground;
  9462. ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
  9463. ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
  9464. ctx.fillStyle = labelColor.backgroundColor;
  9465. ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
  9466. }
  9467. }
  9468. ctx.fillStyle = this.labelTextColors[i];
  9469. }
  9470. drawBody(pt, ctx, options) {
  9471. const { body } = this;
  9472. const { bodySpacing , bodyAlign , displayColors , boxHeight , boxWidth , boxPadding } = options;
  9473. const bodyFont = toFont(options.bodyFont);
  9474. let bodyLineHeight = bodyFont.lineHeight;
  9475. let xLinePadding = 0;
  9476. const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
  9477. const fillLineOfText = function(line) {
  9478. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
  9479. pt.y += bodyLineHeight + bodySpacing;
  9480. };
  9481. const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  9482. let bodyItem, textColor, lines, i, j, ilen, jlen;
  9483. ctx.textAlign = bodyAlign;
  9484. ctx.textBaseline = 'middle';
  9485. ctx.font = bodyFont.string;
  9486. pt.x = getAlignedX(this, bodyAlignForCalculation, options);
  9487. ctx.fillStyle = options.bodyColor;
  9488. each(this.beforeBody, fillLineOfText);
  9489. xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? boxWidth / 2 + boxPadding : boxWidth + 2 + boxPadding : 0;
  9490. for(i = 0, ilen = body.length; i < ilen; ++i){
  9491. bodyItem = body[i];
  9492. textColor = this.labelTextColors[i];
  9493. ctx.fillStyle = textColor;
  9494. each(bodyItem.before, fillLineOfText);
  9495. lines = bodyItem.lines;
  9496. if (displayColors && lines.length) {
  9497. this._drawColorBox(ctx, pt, i, rtlHelper, options);
  9498. bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
  9499. }
  9500. for(j = 0, jlen = lines.length; j < jlen; ++j){
  9501. fillLineOfText(lines[j]);
  9502. bodyLineHeight = bodyFont.lineHeight;
  9503. }
  9504. each(bodyItem.after, fillLineOfText);
  9505. }
  9506. xLinePadding = 0;
  9507. bodyLineHeight = bodyFont.lineHeight;
  9508. each(this.afterBody, fillLineOfText);
  9509. pt.y -= bodySpacing;
  9510. }
  9511. drawFooter(pt, ctx, options) {
  9512. const footer = this.footer;
  9513. const length = footer.length;
  9514. let footerFont, i;
  9515. if (length) {
  9516. const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
  9517. pt.x = getAlignedX(this, options.footerAlign, options);
  9518. pt.y += options.footerMarginTop;
  9519. ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
  9520. ctx.textBaseline = 'middle';
  9521. footerFont = toFont(options.footerFont);
  9522. ctx.fillStyle = options.footerColor;
  9523. ctx.font = footerFont.string;
  9524. for(i = 0; i < length; ++i){
  9525. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
  9526. pt.y += footerFont.lineHeight + options.footerSpacing;
  9527. }
  9528. }
  9529. }
  9530. drawBackground(pt, ctx, tooltipSize, options) {
  9531. const { xAlign , yAlign } = this;
  9532. const { x , y } = pt;
  9533. const { width , height } = tooltipSize;
  9534. const { topLeft , topRight , bottomLeft , bottomRight } = toTRBLCorners(options.cornerRadius);
  9535. ctx.fillStyle = options.backgroundColor;
  9536. ctx.strokeStyle = options.borderColor;
  9537. ctx.lineWidth = options.borderWidth;
  9538. ctx.beginPath();
  9539. ctx.moveTo(x + topLeft, y);
  9540. if (yAlign === 'top') {
  9541. this.drawCaret(pt, ctx, tooltipSize, options);
  9542. }
  9543. ctx.lineTo(x + width - topRight, y);
  9544. ctx.quadraticCurveTo(x + width, y, x + width, y + topRight);
  9545. if (yAlign === 'center' && xAlign === 'right') {
  9546. this.drawCaret(pt, ctx, tooltipSize, options);
  9547. }
  9548. ctx.lineTo(x + width, y + height - bottomRight);
  9549. ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height);
  9550. if (yAlign === 'bottom') {
  9551. this.drawCaret(pt, ctx, tooltipSize, options);
  9552. }
  9553. ctx.lineTo(x + bottomLeft, y + height);
  9554. ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft);
  9555. if (yAlign === 'center' && xAlign === 'left') {
  9556. this.drawCaret(pt, ctx, tooltipSize, options);
  9557. }
  9558. ctx.lineTo(x, y + topLeft);
  9559. ctx.quadraticCurveTo(x, y, x + topLeft, y);
  9560. ctx.closePath();
  9561. ctx.fill();
  9562. if (options.borderWidth > 0) {
  9563. ctx.stroke();
  9564. }
  9565. }
  9566. _updateAnimationTarget(options) {
  9567. const chart = this.chart;
  9568. const anims = this.$animations;
  9569. const animX = anims && anims.x;
  9570. const animY = anims && anims.y;
  9571. if (animX || animY) {
  9572. const position = positioners[options.position].call(this, this._active, this._eventPosition);
  9573. if (!position) {
  9574. return;
  9575. }
  9576. const size = this._size = getTooltipSize(this, options);
  9577. const positionAndSize = Object.assign({}, position, this._size);
  9578. const alignment = determineAlignment(chart, options, positionAndSize);
  9579. const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
  9580. if (animX._to !== point.x || animY._to !== point.y) {
  9581. this.xAlign = alignment.xAlign;
  9582. this.yAlign = alignment.yAlign;
  9583. this.width = size.width;
  9584. this.height = size.height;
  9585. this.caretX = position.x;
  9586. this.caretY = position.y;
  9587. this._resolveAnimations().update(this, point);
  9588. }
  9589. }
  9590. }
  9591. _willRender() {
  9592. return !!this.opacity;
  9593. }
  9594. draw(ctx) {
  9595. const options = this.options.setContext(this.getContext());
  9596. let opacity = this.opacity;
  9597. if (!opacity) {
  9598. return;
  9599. }
  9600. this._updateAnimationTarget(options);
  9601. const tooltipSize = {
  9602. width: this.width,
  9603. height: this.height
  9604. };
  9605. const pt = {
  9606. x: this.x,
  9607. y: this.y
  9608. };
  9609. opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
  9610. const padding = toPadding(options.padding);
  9611. const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length;
  9612. if (options.enabled && hasTooltipContent) {
  9613. ctx.save();
  9614. ctx.globalAlpha = opacity;
  9615. this.drawBackground(pt, ctx, tooltipSize, options);
  9616. overrideTextDirection(ctx, options.textDirection);
  9617. pt.y += padding.top;
  9618. this.drawTitle(pt, ctx, options);
  9619. this.drawBody(pt, ctx, options);
  9620. this.drawFooter(pt, ctx, options);
  9621. restoreTextDirection(ctx, options.textDirection);
  9622. ctx.restore();
  9623. }
  9624. }
  9625. getActiveElements() {
  9626. return this._active || [];
  9627. }
  9628. setActiveElements(activeElements, eventPosition) {
  9629. const lastActive = this._active;
  9630. const active = activeElements.map(({ datasetIndex , index })=>{
  9631. const meta = this.chart.getDatasetMeta(datasetIndex);
  9632. if (!meta) {
  9633. throw new Error('Cannot find a dataset at index ' + datasetIndex);
  9634. }
  9635. return {
  9636. datasetIndex,
  9637. element: meta.data[index],
  9638. index
  9639. };
  9640. });
  9641. const changed = !_elementsEqual(lastActive, active);
  9642. const positionChanged = this._positionChanged(active, eventPosition);
  9643. if (changed || positionChanged) {
  9644. this._active = active;
  9645. this._eventPosition = eventPosition;
  9646. this._ignoreReplayEvents = true;
  9647. this.update(true);
  9648. }
  9649. }
  9650. handleEvent(e, replay, inChartArea = true) {
  9651. if (replay && this._ignoreReplayEvents) {
  9652. return false;
  9653. }
  9654. this._ignoreReplayEvents = false;
  9655. const options = this.options;
  9656. const lastActive = this._active || [];
  9657. const active = this._getActiveElements(e, lastActive, replay, inChartArea);
  9658. const positionChanged = this._positionChanged(active, e);
  9659. const changed = replay || !_elementsEqual(active, lastActive) || positionChanged;
  9660. if (changed) {
  9661. this._active = active;
  9662. if (options.enabled || options.external) {
  9663. this._eventPosition = {
  9664. x: e.x,
  9665. y: e.y
  9666. };
  9667. this.update(true, replay);
  9668. }
  9669. }
  9670. return changed;
  9671. }
  9672. _getActiveElements(e, lastActive, replay, inChartArea) {
  9673. const options = this.options;
  9674. if (e.type === 'mouseout') {
  9675. return [];
  9676. }
  9677. if (!inChartArea) {
  9678. return lastActive.filter((i)=>this.chart.data.datasets[i.datasetIndex] && this.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined);
  9679. }
  9680. const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay);
  9681. if (options.reverse) {
  9682. active.reverse();
  9683. }
  9684. return active;
  9685. }
  9686. _positionChanged(active, e) {
  9687. const { caretX , caretY , options } = this;
  9688. const position = positioners[options.position].call(this, active, e);
  9689. return position !== false && (caretX !== position.x || caretY !== position.y);
  9690. }
  9691. }
  9692. var plugin_tooltip = {
  9693. id: 'tooltip',
  9694. _element: Tooltip,
  9695. positioners,
  9696. afterInit (chart, _args, options) {
  9697. if (options) {
  9698. chart.tooltip = new Tooltip({
  9699. chart,
  9700. options
  9701. });
  9702. }
  9703. },
  9704. beforeUpdate (chart, _args, options) {
  9705. if (chart.tooltip) {
  9706. chart.tooltip.initialize(options);
  9707. }
  9708. },
  9709. reset (chart, _args, options) {
  9710. if (chart.tooltip) {
  9711. chart.tooltip.initialize(options);
  9712. }
  9713. },
  9714. afterDraw (chart) {
  9715. const tooltip = chart.tooltip;
  9716. if (tooltip && tooltip._willRender()) {
  9717. const args = {
  9718. tooltip
  9719. };
  9720. if (chart.notifyPlugins('beforeTooltipDraw', {
  9721. ...args,
  9722. cancelable: true
  9723. }) === false) {
  9724. return;
  9725. }
  9726. tooltip.draw(chart.ctx);
  9727. chart.notifyPlugins('afterTooltipDraw', args);
  9728. }
  9729. },
  9730. afterEvent (chart, args) {
  9731. if (chart.tooltip) {
  9732. const useFinalPosition = args.replay;
  9733. if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) {
  9734. args.changed = true;
  9735. }
  9736. }
  9737. },
  9738. defaults: {
  9739. enabled: true,
  9740. external: null,
  9741. position: 'average',
  9742. backgroundColor: 'rgba(0,0,0,0.8)',
  9743. titleColor: '#fff',
  9744. titleFont: {
  9745. weight: 'bold'
  9746. },
  9747. titleSpacing: 2,
  9748. titleMarginBottom: 6,
  9749. titleAlign: 'left',
  9750. bodyColor: '#fff',
  9751. bodySpacing: 2,
  9752. bodyFont: {},
  9753. bodyAlign: 'left',
  9754. footerColor: '#fff',
  9755. footerSpacing: 2,
  9756. footerMarginTop: 6,
  9757. footerFont: {
  9758. weight: 'bold'
  9759. },
  9760. footerAlign: 'left',
  9761. padding: 6,
  9762. caretPadding: 2,
  9763. caretSize: 5,
  9764. cornerRadius: 6,
  9765. boxHeight: (ctx, opts)=>opts.bodyFont.size,
  9766. boxWidth: (ctx, opts)=>opts.bodyFont.size,
  9767. multiKeyBackground: '#fff',
  9768. displayColors: true,
  9769. boxPadding: 0,
  9770. borderColor: 'rgba(0,0,0,0)',
  9771. borderWidth: 0,
  9772. animation: {
  9773. duration: 400,
  9774. easing: 'easeOutQuart'
  9775. },
  9776. animations: {
  9777. numbers: {
  9778. type: 'number',
  9779. properties: [
  9780. 'x',
  9781. 'y',
  9782. 'width',
  9783. 'height',
  9784. 'caretX',
  9785. 'caretY'
  9786. ]
  9787. },
  9788. opacity: {
  9789. easing: 'linear',
  9790. duration: 200
  9791. }
  9792. },
  9793. callbacks: defaultCallbacks
  9794. },
  9795. defaultRoutes: {
  9796. bodyFont: 'font',
  9797. footerFont: 'font',
  9798. titleFont: 'font'
  9799. },
  9800. descriptors: {
  9801. _scriptable: (name)=>name !== 'filter' && name !== 'itemSort' && name !== 'external',
  9802. _indexable: false,
  9803. callbacks: {
  9804. _scriptable: false,
  9805. _indexable: false
  9806. },
  9807. animation: {
  9808. _fallback: false
  9809. },
  9810. animations: {
  9811. _fallback: 'animation'
  9812. }
  9813. },
  9814. additionalOptionScopes: [
  9815. 'interaction'
  9816. ]
  9817. };
  9818. var plugins = /*#__PURE__*/Object.freeze({
  9819. __proto__: null,
  9820. Colors: plugin_colors,
  9821. Decimation: plugin_decimation,
  9822. Filler: index,
  9823. Legend: plugin_legend,
  9824. SubTitle: plugin_subtitle,
  9825. Title: plugin_title,
  9826. Tooltip: plugin_tooltip
  9827. });
  9828. const addIfString = (labels, raw, index, addedLabels)=>{
  9829. if (typeof raw === 'string') {
  9830. index = labels.push(raw) - 1;
  9831. addedLabels.unshift({
  9832. index,
  9833. label: raw
  9834. });
  9835. } else if (isNaN(raw)) {
  9836. index = null;
  9837. }
  9838. return index;
  9839. };
  9840. function findOrAddLabel(labels, raw, index, addedLabels) {
  9841. const first = labels.indexOf(raw);
  9842. if (first === -1) {
  9843. return addIfString(labels, raw, index, addedLabels);
  9844. }
  9845. const last = labels.lastIndexOf(raw);
  9846. return first !== last ? index : first;
  9847. }
  9848. const validIndex = (index, max)=>index === null ? null : _limitValue(Math.round(index), 0, max);
  9849. function _getLabelForValue(value) {
  9850. const labels = this.getLabels();
  9851. if (value >= 0 && value < labels.length) {
  9852. return labels[value];
  9853. }
  9854. return value;
  9855. }
  9856. class CategoryScale extends Scale {
  9857. static id = 'category';
  9858. static defaults = {
  9859. ticks: {
  9860. callback: _getLabelForValue
  9861. }
  9862. };
  9863. constructor(cfg){
  9864. super(cfg);
  9865. this._startValue = undefined;
  9866. this._valueRange = 0;
  9867. this._addedLabels = [];
  9868. }
  9869. init(scaleOptions) {
  9870. const added = this._addedLabels;
  9871. if (added.length) {
  9872. const labels = this.getLabels();
  9873. for (const { index , label } of added){
  9874. if (labels[index] === label) {
  9875. labels.splice(index, 1);
  9876. }
  9877. }
  9878. this._addedLabels = [];
  9879. }
  9880. super.init(scaleOptions);
  9881. }
  9882. parse(raw, index) {
  9883. if (isNullOrUndef(raw)) {
  9884. return null;
  9885. }
  9886. const labels = this.getLabels();
  9887. index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels);
  9888. return validIndex(index, labels.length - 1);
  9889. }
  9890. determineDataLimits() {
  9891. const { minDefined , maxDefined } = this.getUserBounds();
  9892. let { min , max } = this.getMinMax(true);
  9893. if (this.options.bounds === 'ticks') {
  9894. if (!minDefined) {
  9895. min = 0;
  9896. }
  9897. if (!maxDefined) {
  9898. max = this.getLabels().length - 1;
  9899. }
  9900. }
  9901. this.min = min;
  9902. this.max = max;
  9903. }
  9904. buildTicks() {
  9905. const min = this.min;
  9906. const max = this.max;
  9907. const offset = this.options.offset;
  9908. const ticks = [];
  9909. let labels = this.getLabels();
  9910. labels = min === 0 && max === labels.length - 1 ? labels : labels.slice(min, max + 1);
  9911. this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
  9912. this._startValue = this.min - (offset ? 0.5 : 0);
  9913. for(let value = min; value <= max; value++){
  9914. ticks.push({
  9915. value
  9916. });
  9917. }
  9918. return ticks;
  9919. }
  9920. getLabelForValue(value) {
  9921. return _getLabelForValue.call(this, value);
  9922. }
  9923. configure() {
  9924. super.configure();
  9925. if (!this.isHorizontal()) {
  9926. this._reversePixels = !this._reversePixels;
  9927. }
  9928. }
  9929. getPixelForValue(value) {
  9930. if (typeof value !== 'number') {
  9931. value = this.parse(value);
  9932. }
  9933. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  9934. }
  9935. getPixelForTick(index) {
  9936. const ticks = this.ticks;
  9937. if (index < 0 || index > ticks.length - 1) {
  9938. return null;
  9939. }
  9940. return this.getPixelForValue(ticks[index].value);
  9941. }
  9942. getValueForPixel(pixel) {
  9943. return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange);
  9944. }
  9945. getBasePixel() {
  9946. return this.bottom;
  9947. }
  9948. }
  9949. function generateTicks$1(generationOptions, dataRange) {
  9950. const ticks = [];
  9951. const MIN_SPACING = 1e-14;
  9952. const { bounds , step , min , max , precision , count , maxTicks , maxDigits , includeBounds } = generationOptions;
  9953. const unit = step || 1;
  9954. const maxSpaces = maxTicks - 1;
  9955. const { min: rmin , max: rmax } = dataRange;
  9956. const minDefined = !isNullOrUndef(min);
  9957. const maxDefined = !isNullOrUndef(max);
  9958. const countDefined = !isNullOrUndef(count);
  9959. const minSpacing = (rmax - rmin) / (maxDigits + 1);
  9960. let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;
  9961. let factor, niceMin, niceMax, numSpaces;
  9962. if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
  9963. return [
  9964. {
  9965. value: rmin
  9966. },
  9967. {
  9968. value: rmax
  9969. }
  9970. ];
  9971. }
  9972. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  9973. if (numSpaces > maxSpaces) {
  9974. spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
  9975. }
  9976. if (!isNullOrUndef(precision)) {
  9977. factor = Math.pow(10, precision);
  9978. spacing = Math.ceil(spacing * factor) / factor;
  9979. }
  9980. if (bounds === 'ticks') {
  9981. niceMin = Math.floor(rmin / spacing) * spacing;
  9982. niceMax = Math.ceil(rmax / spacing) * spacing;
  9983. } else {
  9984. niceMin = rmin;
  9985. niceMax = rmax;
  9986. }
  9987. if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {
  9988. numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));
  9989. spacing = (max - min) / numSpaces;
  9990. niceMin = min;
  9991. niceMax = max;
  9992. } else if (countDefined) {
  9993. niceMin = minDefined ? min : niceMin;
  9994. niceMax = maxDefined ? max : niceMax;
  9995. numSpaces = count - 1;
  9996. spacing = (niceMax - niceMin) / numSpaces;
  9997. } else {
  9998. numSpaces = (niceMax - niceMin) / spacing;
  9999. if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10000. numSpaces = Math.round(numSpaces);
  10001. } else {
  10002. numSpaces = Math.ceil(numSpaces);
  10003. }
  10004. }
  10005. const decimalPlaces = Math.max(_decimalPlaces(spacing), _decimalPlaces(niceMin));
  10006. factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);
  10007. niceMin = Math.round(niceMin * factor) / factor;
  10008. niceMax = Math.round(niceMax * factor) / factor;
  10009. let j = 0;
  10010. if (minDefined) {
  10011. if (includeBounds && niceMin !== min) {
  10012. ticks.push({
  10013. value: min
  10014. });
  10015. if (niceMin < min) {
  10016. j++;
  10017. }
  10018. if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {
  10019. j++;
  10020. }
  10021. } else if (niceMin < min) {
  10022. j++;
  10023. }
  10024. }
  10025. for(; j < numSpaces; ++j){
  10026. const tickValue = Math.round((niceMin + j * spacing) * factor) / factor;
  10027. if (maxDefined && tickValue > max) {
  10028. break;
  10029. }
  10030. ticks.push({
  10031. value: tickValue
  10032. });
  10033. }
  10034. if (maxDefined && includeBounds && niceMax !== max) {
  10035. if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {
  10036. ticks[ticks.length - 1].value = max;
  10037. } else {
  10038. ticks.push({
  10039. value: max
  10040. });
  10041. }
  10042. } else if (!maxDefined || niceMax === max) {
  10043. ticks.push({
  10044. value: niceMax
  10045. });
  10046. }
  10047. return ticks;
  10048. }
  10049. function relativeLabelSize(value, minSpacing, { horizontal , minRotation }) {
  10050. const rad = toRadians(minRotation);
  10051. const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;
  10052. const length = 0.75 * minSpacing * ('' + value).length;
  10053. return Math.min(minSpacing / ratio, length);
  10054. }
  10055. class LinearScaleBase extends Scale {
  10056. constructor(cfg){
  10057. super(cfg);
  10058. this.start = undefined;
  10059. this.end = undefined;
  10060. this._startValue = undefined;
  10061. this._endValue = undefined;
  10062. this._valueRange = 0;
  10063. }
  10064. parse(raw, index) {
  10065. if (isNullOrUndef(raw)) {
  10066. return null;
  10067. }
  10068. if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
  10069. return null;
  10070. }
  10071. return +raw;
  10072. }
  10073. handleTickRangeOptions() {
  10074. const { beginAtZero } = this.options;
  10075. const { minDefined , maxDefined } = this.getUserBounds();
  10076. let { min , max } = this;
  10077. const setMin = (v)=>min = minDefined ? min : v;
  10078. const setMax = (v)=>max = maxDefined ? max : v;
  10079. if (beginAtZero) {
  10080. const minSign = sign(min);
  10081. const maxSign = sign(max);
  10082. if (minSign < 0 && maxSign < 0) {
  10083. setMax(0);
  10084. } else if (minSign > 0 && maxSign > 0) {
  10085. setMin(0);
  10086. }
  10087. }
  10088. if (min === max) {
  10089. let offset = max === 0 ? 1 : Math.abs(max * 0.05);
  10090. setMax(max + offset);
  10091. if (!beginAtZero) {
  10092. setMin(min - offset);
  10093. }
  10094. }
  10095. this.min = min;
  10096. this.max = max;
  10097. }
  10098. getTickLimit() {
  10099. const tickOpts = this.options.ticks;
  10100. let { maxTicksLimit , stepSize } = tickOpts;
  10101. let maxTicks;
  10102. if (stepSize) {
  10103. maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1;
  10104. if (maxTicks > 1000) {
  10105. console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`);
  10106. maxTicks = 1000;
  10107. }
  10108. } else {
  10109. maxTicks = this.computeTickLimit();
  10110. maxTicksLimit = maxTicksLimit || 11;
  10111. }
  10112. if (maxTicksLimit) {
  10113. maxTicks = Math.min(maxTicksLimit, maxTicks);
  10114. }
  10115. return maxTicks;
  10116. }
  10117. computeTickLimit() {
  10118. return Number.POSITIVE_INFINITY;
  10119. }
  10120. buildTicks() {
  10121. const opts = this.options;
  10122. const tickOpts = opts.ticks;
  10123. let maxTicks = this.getTickLimit();
  10124. maxTicks = Math.max(2, maxTicks);
  10125. const numericGeneratorOptions = {
  10126. maxTicks,
  10127. bounds: opts.bounds,
  10128. min: opts.min,
  10129. max: opts.max,
  10130. precision: tickOpts.precision,
  10131. step: tickOpts.stepSize,
  10132. count: tickOpts.count,
  10133. maxDigits: this._maxDigits(),
  10134. horizontal: this.isHorizontal(),
  10135. minRotation: tickOpts.minRotation || 0,
  10136. includeBounds: tickOpts.includeBounds !== false
  10137. };
  10138. const dataRange = this._range || this;
  10139. const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
  10140. if (opts.bounds === 'ticks') {
  10141. _setMinAndMaxByKey(ticks, this, 'value');
  10142. }
  10143. if (opts.reverse) {
  10144. ticks.reverse();
  10145. this.start = this.max;
  10146. this.end = this.min;
  10147. } else {
  10148. this.start = this.min;
  10149. this.end = this.max;
  10150. }
  10151. return ticks;
  10152. }
  10153. configure() {
  10154. const ticks = this.ticks;
  10155. let start = this.min;
  10156. let end = this.max;
  10157. super.configure();
  10158. if (this.options.offset && ticks.length) {
  10159. const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  10160. start -= offset;
  10161. end += offset;
  10162. }
  10163. this._startValue = start;
  10164. this._endValue = end;
  10165. this._valueRange = end - start;
  10166. }
  10167. getLabelForValue(value) {
  10168. return formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  10169. }
  10170. }
  10171. class LinearScale extends LinearScaleBase {
  10172. static id = 'linear';
  10173. static defaults = {
  10174. ticks: {
  10175. callback: Ticks.formatters.numeric
  10176. }
  10177. };
  10178. determineDataLimits() {
  10179. const { min , max } = this.getMinMax(true);
  10180. this.min = isNumberFinite(min) ? min : 0;
  10181. this.max = isNumberFinite(max) ? max : 1;
  10182. this.handleTickRangeOptions();
  10183. }
  10184. computeTickLimit() {
  10185. const horizontal = this.isHorizontal();
  10186. const length = horizontal ? this.width : this.height;
  10187. const minRotation = toRadians(this.options.ticks.minRotation);
  10188. const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;
  10189. const tickFont = this._resolveTickFontOptions(0);
  10190. return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));
  10191. }
  10192. getPixelForValue(value) {
  10193. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  10194. }
  10195. getValueForPixel(pixel) {
  10196. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  10197. }
  10198. }
  10199. const log10Floor = (v)=>Math.floor(log10(v));
  10200. const changeExponent = (v, m)=>Math.pow(10, log10Floor(v) + m);
  10201. function isMajor(tickVal) {
  10202. const remain = tickVal / Math.pow(10, log10Floor(tickVal));
  10203. return remain === 1;
  10204. }
  10205. function steps(min, max, rangeExp) {
  10206. const rangeStep = Math.pow(10, rangeExp);
  10207. const start = Math.floor(min / rangeStep);
  10208. const end = Math.ceil(max / rangeStep);
  10209. return end - start;
  10210. }
  10211. function startExp(min, max) {
  10212. const range = max - min;
  10213. let rangeExp = log10Floor(range);
  10214. while(steps(min, max, rangeExp) > 10){
  10215. rangeExp++;
  10216. }
  10217. while(steps(min, max, rangeExp) < 10){
  10218. rangeExp--;
  10219. }
  10220. return Math.min(rangeExp, log10Floor(min));
  10221. }
  10222. function generateTicks(generationOptions, { min , max }) {
  10223. min = finiteOrDefault(generationOptions.min, min);
  10224. const ticks = [];
  10225. const minExp = log10Floor(min);
  10226. let exp = startExp(min, max);
  10227. let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  10228. const stepSize = Math.pow(10, exp);
  10229. const base = minExp > exp ? Math.pow(10, minExp) : 0;
  10230. const start = Math.round((min - base) * precision) / precision;
  10231. const offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10;
  10232. let significand = Math.floor((start - offset) / Math.pow(10, exp));
  10233. let value = finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision);
  10234. while(value < max){
  10235. ticks.push({
  10236. value,
  10237. major: isMajor(value),
  10238. significand
  10239. });
  10240. if (significand >= 10) {
  10241. significand = significand < 15 ? 15 : 20;
  10242. } else {
  10243. significand++;
  10244. }
  10245. if (significand >= 20) {
  10246. exp++;
  10247. significand = 2;
  10248. precision = exp >= 0 ? 1 : precision;
  10249. }
  10250. value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision;
  10251. }
  10252. const lastTick = finiteOrDefault(generationOptions.max, value);
  10253. ticks.push({
  10254. value: lastTick,
  10255. major: isMajor(lastTick),
  10256. significand
  10257. });
  10258. return ticks;
  10259. }
  10260. class LogarithmicScale extends Scale {
  10261. static id = 'logarithmic';
  10262. static defaults = {
  10263. ticks: {
  10264. callback: Ticks.formatters.logarithmic,
  10265. major: {
  10266. enabled: true
  10267. }
  10268. }
  10269. };
  10270. constructor(cfg){
  10271. super(cfg);
  10272. this.start = undefined;
  10273. this.end = undefined;
  10274. this._startValue = undefined;
  10275. this._valueRange = 0;
  10276. }
  10277. parse(raw, index) {
  10278. const value = LinearScaleBase.prototype.parse.apply(this, [
  10279. raw,
  10280. index
  10281. ]);
  10282. if (value === 0) {
  10283. this._zero = true;
  10284. return undefined;
  10285. }
  10286. return isNumberFinite(value) && value > 0 ? value : null;
  10287. }
  10288. determineDataLimits() {
  10289. const { min , max } = this.getMinMax(true);
  10290. this.min = isNumberFinite(min) ? Math.max(0, min) : null;
  10291. this.max = isNumberFinite(max) ? Math.max(0, max) : null;
  10292. if (this.options.beginAtZero) {
  10293. this._zero = true;
  10294. }
  10295. if (this._zero && this.min !== this._suggestedMin && !isNumberFinite(this._userMin)) {
  10296. this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0);
  10297. }
  10298. this.handleTickRangeOptions();
  10299. }
  10300. handleTickRangeOptions() {
  10301. const { minDefined , maxDefined } = this.getUserBounds();
  10302. let min = this.min;
  10303. let max = this.max;
  10304. const setMin = (v)=>min = minDefined ? min : v;
  10305. const setMax = (v)=>max = maxDefined ? max : v;
  10306. if (min === max) {
  10307. if (min <= 0) {
  10308. setMin(1);
  10309. setMax(10);
  10310. } else {
  10311. setMin(changeExponent(min, -1));
  10312. setMax(changeExponent(max, +1));
  10313. }
  10314. }
  10315. if (min <= 0) {
  10316. setMin(changeExponent(max, -1));
  10317. }
  10318. if (max <= 0) {
  10319. setMax(changeExponent(min, +1));
  10320. }
  10321. this.min = min;
  10322. this.max = max;
  10323. }
  10324. buildTicks() {
  10325. const opts = this.options;
  10326. const generationOptions = {
  10327. min: this._userMin,
  10328. max: this._userMax
  10329. };
  10330. const ticks = generateTicks(generationOptions, this);
  10331. if (opts.bounds === 'ticks') {
  10332. _setMinAndMaxByKey(ticks, this, 'value');
  10333. }
  10334. if (opts.reverse) {
  10335. ticks.reverse();
  10336. this.start = this.max;
  10337. this.end = this.min;
  10338. } else {
  10339. this.start = this.min;
  10340. this.end = this.max;
  10341. }
  10342. return ticks;
  10343. }
  10344. getLabelForValue(value) {
  10345. return value === undefined ? '0' : formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  10346. }
  10347. configure() {
  10348. const start = this.min;
  10349. super.configure();
  10350. this._startValue = log10(start);
  10351. this._valueRange = log10(this.max) - log10(start);
  10352. }
  10353. getPixelForValue(value) {
  10354. if (value === undefined || value === 0) {
  10355. value = this.min;
  10356. }
  10357. if (value === null || isNaN(value)) {
  10358. return NaN;
  10359. }
  10360. return this.getPixelForDecimal(value === this.min ? 0 : (log10(value) - this._startValue) / this._valueRange);
  10361. }
  10362. getValueForPixel(pixel) {
  10363. const decimal = this.getDecimalForPixel(pixel);
  10364. return Math.pow(10, this._startValue + decimal * this._valueRange);
  10365. }
  10366. }
  10367. function getTickBackdropHeight(opts) {
  10368. const tickOpts = opts.ticks;
  10369. if (tickOpts.display && opts.display) {
  10370. const padding = toPadding(tickOpts.backdropPadding);
  10371. return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;
  10372. }
  10373. return 0;
  10374. }
  10375. function measureLabelSize(ctx, font, label) {
  10376. label = isArray(label) ? label : [
  10377. label
  10378. ];
  10379. return {
  10380. w: _longestText(ctx, font.string, label),
  10381. h: label.length * font.lineHeight
  10382. };
  10383. }
  10384. function determineLimits(angle, pos, size, min, max) {
  10385. if (angle === min || angle === max) {
  10386. return {
  10387. start: pos - size / 2,
  10388. end: pos + size / 2
  10389. };
  10390. } else if (angle < min || angle > max) {
  10391. return {
  10392. start: pos - size,
  10393. end: pos
  10394. };
  10395. }
  10396. return {
  10397. start: pos,
  10398. end: pos + size
  10399. };
  10400. }
  10401. function fitWithPointLabels(scale) {
  10402. const orig = {
  10403. l: scale.left + scale._padding.left,
  10404. r: scale.right - scale._padding.right,
  10405. t: scale.top + scale._padding.top,
  10406. b: scale.bottom - scale._padding.bottom
  10407. };
  10408. const limits = Object.assign({}, orig);
  10409. const labelSizes = [];
  10410. const padding = [];
  10411. const valueCount = scale._pointLabels.length;
  10412. const pointLabelOpts = scale.options.pointLabels;
  10413. const additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0;
  10414. for(let i = 0; i < valueCount; i++){
  10415. const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i));
  10416. padding[i] = opts.padding;
  10417. const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle);
  10418. const plFont = toFont(opts.font);
  10419. const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);
  10420. labelSizes[i] = textSize;
  10421. const angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle);
  10422. const angle = Math.round(toDegrees(angleRadians));
  10423. const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  10424. const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  10425. updateLimits(limits, orig, angleRadians, hLimits, vLimits);
  10426. }
  10427. scale.setCenterPoint(orig.l - limits.l, limits.r - orig.r, orig.t - limits.t, limits.b - orig.b);
  10428. scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);
  10429. }
  10430. function updateLimits(limits, orig, angle, hLimits, vLimits) {
  10431. const sin = Math.abs(Math.sin(angle));
  10432. const cos = Math.abs(Math.cos(angle));
  10433. let x = 0;
  10434. let y = 0;
  10435. if (hLimits.start < orig.l) {
  10436. x = (orig.l - hLimits.start) / sin;
  10437. limits.l = Math.min(limits.l, orig.l - x);
  10438. } else if (hLimits.end > orig.r) {
  10439. x = (hLimits.end - orig.r) / sin;
  10440. limits.r = Math.max(limits.r, orig.r + x);
  10441. }
  10442. if (vLimits.start < orig.t) {
  10443. y = (orig.t - vLimits.start) / cos;
  10444. limits.t = Math.min(limits.t, orig.t - y);
  10445. } else if (vLimits.end > orig.b) {
  10446. y = (vLimits.end - orig.b) / cos;
  10447. limits.b = Math.max(limits.b, orig.b + y);
  10448. }
  10449. }
  10450. function createPointLabelItem(scale, index, itemOpts) {
  10451. const outerDistance = scale.drawingArea;
  10452. const { extra , additionalAngle , padding , size } = itemOpts;
  10453. const pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle);
  10454. const angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI)));
  10455. const y = yForAngle(pointLabelPosition.y, size.h, angle);
  10456. const textAlign = getTextAlignForAngle(angle);
  10457. const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);
  10458. return {
  10459. visible: true,
  10460. x: pointLabelPosition.x,
  10461. y,
  10462. textAlign,
  10463. left,
  10464. top: y,
  10465. right: left + size.w,
  10466. bottom: y + size.h
  10467. };
  10468. }
  10469. function isNotOverlapped(item, area) {
  10470. if (!area) {
  10471. return true;
  10472. }
  10473. const { left , top , right , bottom } = item;
  10474. const apexesInArea = _isPointInArea({
  10475. x: left,
  10476. y: top
  10477. }, area) || _isPointInArea({
  10478. x: left,
  10479. y: bottom
  10480. }, area) || _isPointInArea({
  10481. x: right,
  10482. y: top
  10483. }, area) || _isPointInArea({
  10484. x: right,
  10485. y: bottom
  10486. }, area);
  10487. return !apexesInArea;
  10488. }
  10489. function buildPointLabelItems(scale, labelSizes, padding) {
  10490. const items = [];
  10491. const valueCount = scale._pointLabels.length;
  10492. const opts = scale.options;
  10493. const { centerPointLabels , display } = opts.pointLabels;
  10494. const itemOpts = {
  10495. extra: getTickBackdropHeight(opts) / 2,
  10496. additionalAngle: centerPointLabels ? PI / valueCount : 0
  10497. };
  10498. let area;
  10499. for(let i = 0; i < valueCount; i++){
  10500. itemOpts.padding = padding[i];
  10501. itemOpts.size = labelSizes[i];
  10502. const item = createPointLabelItem(scale, i, itemOpts);
  10503. items.push(item);
  10504. if (display === 'auto') {
  10505. item.visible = isNotOverlapped(item, area);
  10506. if (item.visible) {
  10507. area = item;
  10508. }
  10509. }
  10510. }
  10511. return items;
  10512. }
  10513. function getTextAlignForAngle(angle) {
  10514. if (angle === 0 || angle === 180) {
  10515. return 'center';
  10516. } else if (angle < 180) {
  10517. return 'left';
  10518. }
  10519. return 'right';
  10520. }
  10521. function leftForTextAlign(x, w, align) {
  10522. if (align === 'right') {
  10523. x -= w;
  10524. } else if (align === 'center') {
  10525. x -= w / 2;
  10526. }
  10527. return x;
  10528. }
  10529. function yForAngle(y, h, angle) {
  10530. if (angle === 90 || angle === 270) {
  10531. y -= h / 2;
  10532. } else if (angle > 270 || angle < 90) {
  10533. y -= h;
  10534. }
  10535. return y;
  10536. }
  10537. function drawPointLabelBox(ctx, opts, item) {
  10538. const { left , top , right , bottom } = item;
  10539. const { backdropColor } = opts;
  10540. if (!isNullOrUndef(backdropColor)) {
  10541. const borderRadius = toTRBLCorners(opts.borderRadius);
  10542. const padding = toPadding(opts.backdropPadding);
  10543. ctx.fillStyle = backdropColor;
  10544. const backdropLeft = left - padding.left;
  10545. const backdropTop = top - padding.top;
  10546. const backdropWidth = right - left + padding.width;
  10547. const backdropHeight = bottom - top + padding.height;
  10548. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  10549. ctx.beginPath();
  10550. addRoundedRectPath(ctx, {
  10551. x: backdropLeft,
  10552. y: backdropTop,
  10553. w: backdropWidth,
  10554. h: backdropHeight,
  10555. radius: borderRadius
  10556. });
  10557. ctx.fill();
  10558. } else {
  10559. ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight);
  10560. }
  10561. }
  10562. }
  10563. function drawPointLabels(scale, labelCount) {
  10564. const { ctx , options: { pointLabels } } = scale;
  10565. for(let i = labelCount - 1; i >= 0; i--){
  10566. const item = scale._pointLabelItems[i];
  10567. if (!item.visible) {
  10568. continue;
  10569. }
  10570. const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));
  10571. drawPointLabelBox(ctx, optsAtIndex, item);
  10572. const plFont = toFont(optsAtIndex.font);
  10573. const { x , y , textAlign } = item;
  10574. renderText(ctx, scale._pointLabels[i], x, y + plFont.lineHeight / 2, plFont, {
  10575. color: optsAtIndex.color,
  10576. textAlign: textAlign,
  10577. textBaseline: 'middle'
  10578. });
  10579. }
  10580. }
  10581. function pathRadiusLine(scale, radius, circular, labelCount) {
  10582. const { ctx } = scale;
  10583. if (circular) {
  10584. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);
  10585. } else {
  10586. let pointPosition = scale.getPointPosition(0, radius);
  10587. ctx.moveTo(pointPosition.x, pointPosition.y);
  10588. for(let i = 1; i < labelCount; i++){
  10589. pointPosition = scale.getPointPosition(i, radius);
  10590. ctx.lineTo(pointPosition.x, pointPosition.y);
  10591. }
  10592. }
  10593. }
  10594. function drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) {
  10595. const ctx = scale.ctx;
  10596. const circular = gridLineOpts.circular;
  10597. const { color , lineWidth } = gridLineOpts;
  10598. if (!circular && !labelCount || !color || !lineWidth || radius < 0) {
  10599. return;
  10600. }
  10601. ctx.save();
  10602. ctx.strokeStyle = color;
  10603. ctx.lineWidth = lineWidth;
  10604. ctx.setLineDash(borderOpts.dash);
  10605. ctx.lineDashOffset = borderOpts.dashOffset;
  10606. ctx.beginPath();
  10607. pathRadiusLine(scale, radius, circular, labelCount);
  10608. ctx.closePath();
  10609. ctx.stroke();
  10610. ctx.restore();
  10611. }
  10612. function createPointLabelContext(parent, index, label) {
  10613. return createContext(parent, {
  10614. label,
  10615. index,
  10616. type: 'pointLabel'
  10617. });
  10618. }
  10619. class RadialLinearScale extends LinearScaleBase {
  10620. static id = 'radialLinear';
  10621. static defaults = {
  10622. display: true,
  10623. animate: true,
  10624. position: 'chartArea',
  10625. angleLines: {
  10626. display: true,
  10627. lineWidth: 1,
  10628. borderDash: [],
  10629. borderDashOffset: 0.0
  10630. },
  10631. grid: {
  10632. circular: false
  10633. },
  10634. startAngle: 0,
  10635. ticks: {
  10636. showLabelBackdrop: true,
  10637. callback: Ticks.formatters.numeric
  10638. },
  10639. pointLabels: {
  10640. backdropColor: undefined,
  10641. backdropPadding: 2,
  10642. display: true,
  10643. font: {
  10644. size: 10
  10645. },
  10646. callback (label) {
  10647. return label;
  10648. },
  10649. padding: 5,
  10650. centerPointLabels: false
  10651. }
  10652. };
  10653. static defaultRoutes = {
  10654. 'angleLines.color': 'borderColor',
  10655. 'pointLabels.color': 'color',
  10656. 'ticks.color': 'color'
  10657. };
  10658. static descriptors = {
  10659. angleLines: {
  10660. _fallback: 'grid'
  10661. }
  10662. };
  10663. constructor(cfg){
  10664. super(cfg);
  10665. this.xCenter = undefined;
  10666. this.yCenter = undefined;
  10667. this.drawingArea = undefined;
  10668. this._pointLabels = [];
  10669. this._pointLabelItems = [];
  10670. }
  10671. setDimensions() {
  10672. const padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2);
  10673. const w = this.width = this.maxWidth - padding.width;
  10674. const h = this.height = this.maxHeight - padding.height;
  10675. this.xCenter = Math.floor(this.left + w / 2 + padding.left);
  10676. this.yCenter = Math.floor(this.top + h / 2 + padding.top);
  10677. this.drawingArea = Math.floor(Math.min(w, h) / 2);
  10678. }
  10679. determineDataLimits() {
  10680. const { min , max } = this.getMinMax(false);
  10681. this.min = isNumberFinite(min) && !isNaN(min) ? min : 0;
  10682. this.max = isNumberFinite(max) && !isNaN(max) ? max : 0;
  10683. this.handleTickRangeOptions();
  10684. }
  10685. computeTickLimit() {
  10686. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  10687. }
  10688. generateTickLabels(ticks) {
  10689. LinearScaleBase.prototype.generateTickLabels.call(this, ticks);
  10690. this._pointLabels = this.getLabels().map((value, index)=>{
  10691. const label = callback(this.options.pointLabels.callback, [
  10692. value,
  10693. index
  10694. ], this);
  10695. return label || label === 0 ? label : '';
  10696. }).filter((v, i)=>this.chart.getDataVisibility(i));
  10697. }
  10698. fit() {
  10699. const opts = this.options;
  10700. if (opts.display && opts.pointLabels.display) {
  10701. fitWithPointLabels(this);
  10702. } else {
  10703. this.setCenterPoint(0, 0, 0, 0);
  10704. }
  10705. }
  10706. setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
  10707. this.xCenter += Math.floor((leftMovement - rightMovement) / 2);
  10708. this.yCenter += Math.floor((topMovement - bottomMovement) / 2);
  10709. this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement));
  10710. }
  10711. getIndexAngle(index) {
  10712. const angleMultiplier = TAU / (this._pointLabels.length || 1);
  10713. const startAngle = this.options.startAngle || 0;
  10714. return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
  10715. }
  10716. getDistanceFromCenterForValue(value) {
  10717. if (isNullOrUndef(value)) {
  10718. return NaN;
  10719. }
  10720. const scalingFactor = this.drawingArea / (this.max - this.min);
  10721. if (this.options.reverse) {
  10722. return (this.max - value) * scalingFactor;
  10723. }
  10724. return (value - this.min) * scalingFactor;
  10725. }
  10726. getValueForDistanceFromCenter(distance) {
  10727. if (isNullOrUndef(distance)) {
  10728. return NaN;
  10729. }
  10730. const scaledDistance = distance / (this.drawingArea / (this.max - this.min));
  10731. return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance;
  10732. }
  10733. getPointLabelContext(index) {
  10734. const pointLabels = this._pointLabels || [];
  10735. if (index >= 0 && index < pointLabels.length) {
  10736. const pointLabel = pointLabels[index];
  10737. return createPointLabelContext(this.getContext(), index, pointLabel);
  10738. }
  10739. }
  10740. getPointPosition(index, distanceFromCenter, additionalAngle = 0) {
  10741. const angle = this.getIndexAngle(index) - HALF_PI + additionalAngle;
  10742. return {
  10743. x: Math.cos(angle) * distanceFromCenter + this.xCenter,
  10744. y: Math.sin(angle) * distanceFromCenter + this.yCenter,
  10745. angle
  10746. };
  10747. }
  10748. getPointPositionForValue(index, value) {
  10749. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  10750. }
  10751. getBasePosition(index) {
  10752. return this.getPointPositionForValue(index || 0, this.getBaseValue());
  10753. }
  10754. getPointLabelPosition(index) {
  10755. const { left , top , right , bottom } = this._pointLabelItems[index];
  10756. return {
  10757. left,
  10758. top,
  10759. right,
  10760. bottom
  10761. };
  10762. }
  10763. drawBackground() {
  10764. const { backgroundColor , grid: { circular } } = this.options;
  10765. if (backgroundColor) {
  10766. const ctx = this.ctx;
  10767. ctx.save();
  10768. ctx.beginPath();
  10769. pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length);
  10770. ctx.closePath();
  10771. ctx.fillStyle = backgroundColor;
  10772. ctx.fill();
  10773. ctx.restore();
  10774. }
  10775. }
  10776. drawGrid() {
  10777. const ctx = this.ctx;
  10778. const opts = this.options;
  10779. const { angleLines , grid , border } = opts;
  10780. const labelCount = this._pointLabels.length;
  10781. let i, offset, position;
  10782. if (opts.pointLabels.display) {
  10783. drawPointLabels(this, labelCount);
  10784. }
  10785. if (grid.display) {
  10786. this.ticks.forEach((tick, index)=>{
  10787. if (index !== 0 || index === 0 && this.min < 0) {
  10788. offset = this.getDistanceFromCenterForValue(tick.value);
  10789. const context = this.getContext(index);
  10790. const optsAtIndex = grid.setContext(context);
  10791. const optsAtIndexBorder = border.setContext(context);
  10792. drawRadiusLine(this, optsAtIndex, offset, labelCount, optsAtIndexBorder);
  10793. }
  10794. });
  10795. }
  10796. if (angleLines.display) {
  10797. ctx.save();
  10798. for(i = labelCount - 1; i >= 0; i--){
  10799. const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i));
  10800. const { color , lineWidth } = optsAtIndex;
  10801. if (!lineWidth || !color) {
  10802. continue;
  10803. }
  10804. ctx.lineWidth = lineWidth;
  10805. ctx.strokeStyle = color;
  10806. ctx.setLineDash(optsAtIndex.borderDash);
  10807. ctx.lineDashOffset = optsAtIndex.borderDashOffset;
  10808. offset = this.getDistanceFromCenterForValue(opts.ticks.reverse ? this.min : this.max);
  10809. position = this.getPointPosition(i, offset);
  10810. ctx.beginPath();
  10811. ctx.moveTo(this.xCenter, this.yCenter);
  10812. ctx.lineTo(position.x, position.y);
  10813. ctx.stroke();
  10814. }
  10815. ctx.restore();
  10816. }
  10817. }
  10818. drawBorder() {}
  10819. drawLabels() {
  10820. const ctx = this.ctx;
  10821. const opts = this.options;
  10822. const tickOpts = opts.ticks;
  10823. if (!tickOpts.display) {
  10824. return;
  10825. }
  10826. const startAngle = this.getIndexAngle(0);
  10827. let offset, width;
  10828. ctx.save();
  10829. ctx.translate(this.xCenter, this.yCenter);
  10830. ctx.rotate(startAngle);
  10831. ctx.textAlign = 'center';
  10832. ctx.textBaseline = 'middle';
  10833. this.ticks.forEach((tick, index)=>{
  10834. if (index === 0 && this.min >= 0 && !opts.reverse) {
  10835. return;
  10836. }
  10837. const optsAtIndex = tickOpts.setContext(this.getContext(index));
  10838. const tickFont = toFont(optsAtIndex.font);
  10839. offset = this.getDistanceFromCenterForValue(this.ticks[index].value);
  10840. if (optsAtIndex.showLabelBackdrop) {
  10841. ctx.font = tickFont.string;
  10842. width = ctx.measureText(tick.label).width;
  10843. ctx.fillStyle = optsAtIndex.backdropColor;
  10844. const padding = toPadding(optsAtIndex.backdropPadding);
  10845. ctx.fillRect(-width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height);
  10846. }
  10847. renderText(ctx, tick.label, 0, -offset, tickFont, {
  10848. color: optsAtIndex.color,
  10849. strokeColor: optsAtIndex.textStrokeColor,
  10850. strokeWidth: optsAtIndex.textStrokeWidth
  10851. });
  10852. });
  10853. ctx.restore();
  10854. }
  10855. drawTitle() {}
  10856. }
  10857. const INTERVALS = {
  10858. millisecond: {
  10859. common: true,
  10860. size: 1,
  10861. steps: 1000
  10862. },
  10863. second: {
  10864. common: true,
  10865. size: 1000,
  10866. steps: 60
  10867. },
  10868. minute: {
  10869. common: true,
  10870. size: 60000,
  10871. steps: 60
  10872. },
  10873. hour: {
  10874. common: true,
  10875. size: 3600000,
  10876. steps: 24
  10877. },
  10878. day: {
  10879. common: true,
  10880. size: 86400000,
  10881. steps: 30
  10882. },
  10883. week: {
  10884. common: false,
  10885. size: 604800000,
  10886. steps: 4
  10887. },
  10888. month: {
  10889. common: true,
  10890. size: 2.628e9,
  10891. steps: 12
  10892. },
  10893. quarter: {
  10894. common: false,
  10895. size: 7.884e9,
  10896. steps: 4
  10897. },
  10898. year: {
  10899. common: true,
  10900. size: 3.154e10
  10901. }
  10902. };
  10903. const UNITS = /* #__PURE__ */ Object.keys(INTERVALS);
  10904. function sorter(a, b) {
  10905. return a - b;
  10906. }
  10907. function parse(scale, input) {
  10908. if (isNullOrUndef(input)) {
  10909. return null;
  10910. }
  10911. const adapter = scale._adapter;
  10912. const { parser , round , isoWeekday } = scale._parseOpts;
  10913. let value = input;
  10914. if (typeof parser === 'function') {
  10915. value = parser(value);
  10916. }
  10917. if (!isNumberFinite(value)) {
  10918. value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value);
  10919. }
  10920. if (value === null) {
  10921. return null;
  10922. }
  10923. if (round) {
  10924. value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round);
  10925. }
  10926. return +value;
  10927. }
  10928. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  10929. const ilen = UNITS.length;
  10930. for(let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i){
  10931. const interval = INTERVALS[UNITS[i]];
  10932. const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
  10933. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  10934. return UNITS[i];
  10935. }
  10936. }
  10937. return UNITS[ilen - 1];
  10938. }
  10939. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  10940. for(let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--){
  10941. const unit = UNITS[i];
  10942. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  10943. return unit;
  10944. }
  10945. }
  10946. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  10947. }
  10948. function determineMajorUnit(unit) {
  10949. for(let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i){
  10950. if (INTERVALS[UNITS[i]].common) {
  10951. return UNITS[i];
  10952. }
  10953. }
  10954. }
  10955. function addTick(ticks, time, timestamps) {
  10956. if (!timestamps) {
  10957. ticks[time] = true;
  10958. } else if (timestamps.length) {
  10959. const { lo , hi } = _lookup(timestamps, time);
  10960. const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
  10961. ticks[timestamp] = true;
  10962. }
  10963. }
  10964. function setMajorTicks(scale, ticks, map, majorUnit) {
  10965. const adapter = scale._adapter;
  10966. const first = +adapter.startOf(ticks[0].value, majorUnit);
  10967. const last = ticks[ticks.length - 1].value;
  10968. let major, index;
  10969. for(major = first; major <= last; major = +adapter.add(major, 1, majorUnit)){
  10970. index = map[major];
  10971. if (index >= 0) {
  10972. ticks[index].major = true;
  10973. }
  10974. }
  10975. return ticks;
  10976. }
  10977. function ticksFromTimestamps(scale, values, majorUnit) {
  10978. const ticks = [];
  10979. const map = {};
  10980. const ilen = values.length;
  10981. let i, value;
  10982. for(i = 0; i < ilen; ++i){
  10983. value = values[i];
  10984. map[value] = i;
  10985. ticks.push({
  10986. value,
  10987. major: false
  10988. });
  10989. }
  10990. return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  10991. }
  10992. class TimeScale extends Scale {
  10993. static id = 'time';
  10994. static defaults = {
  10995. bounds: 'data',
  10996. adapters: {},
  10997. time: {
  10998. parser: false,
  10999. unit: false,
  11000. round: false,
  11001. isoWeekday: false,
  11002. minUnit: 'millisecond',
  11003. displayFormats: {}
  11004. },
  11005. ticks: {
  11006. source: 'auto',
  11007. callback: false,
  11008. major: {
  11009. enabled: false
  11010. }
  11011. }
  11012. };
  11013. constructor(props){
  11014. super(props);
  11015. this._cache = {
  11016. data: [],
  11017. labels: [],
  11018. all: []
  11019. };
  11020. this._unit = 'day';
  11021. this._majorUnit = undefined;
  11022. this._offsets = {};
  11023. this._normalized = false;
  11024. this._parseOpts = undefined;
  11025. }
  11026. init(scaleOpts, opts = {}) {
  11027. const time = scaleOpts.time || (scaleOpts.time = {});
  11028. const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
  11029. adapter.init(opts);
  11030. mergeIf(time.displayFormats, adapter.formats());
  11031. this._parseOpts = {
  11032. parser: time.parser,
  11033. round: time.round,
  11034. isoWeekday: time.isoWeekday
  11035. };
  11036. super.init(scaleOpts);
  11037. this._normalized = opts.normalized;
  11038. }
  11039. parse(raw, index) {
  11040. if (raw === undefined) {
  11041. return null;
  11042. }
  11043. return parse(this, raw);
  11044. }
  11045. beforeLayout() {
  11046. super.beforeLayout();
  11047. this._cache = {
  11048. data: [],
  11049. labels: [],
  11050. all: []
  11051. };
  11052. }
  11053. determineDataLimits() {
  11054. const options = this.options;
  11055. const adapter = this._adapter;
  11056. const unit = options.time.unit || 'day';
  11057. let { min , max , minDefined , maxDefined } = this.getUserBounds();
  11058. function _applyBounds(bounds) {
  11059. if (!minDefined && !isNaN(bounds.min)) {
  11060. min = Math.min(min, bounds.min);
  11061. }
  11062. if (!maxDefined && !isNaN(bounds.max)) {
  11063. max = Math.max(max, bounds.max);
  11064. }
  11065. }
  11066. if (!minDefined || !maxDefined) {
  11067. _applyBounds(this._getLabelBounds());
  11068. if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
  11069. _applyBounds(this.getMinMax(false));
  11070. }
  11071. }
  11072. min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
  11073. max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
  11074. this.min = Math.min(min, max - 1);
  11075. this.max = Math.max(min + 1, max);
  11076. }
  11077. _getLabelBounds() {
  11078. const arr = this.getLabelTimestamps();
  11079. let min = Number.POSITIVE_INFINITY;
  11080. let max = Number.NEGATIVE_INFINITY;
  11081. if (arr.length) {
  11082. min = arr[0];
  11083. max = arr[arr.length - 1];
  11084. }
  11085. return {
  11086. min,
  11087. max
  11088. };
  11089. }
  11090. buildTicks() {
  11091. const options = this.options;
  11092. const timeOpts = options.time;
  11093. const tickOpts = options.ticks;
  11094. const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate();
  11095. if (options.bounds === 'ticks' && timestamps.length) {
  11096. this.min = this._userMin || timestamps[0];
  11097. this.max = this._userMax || timestamps[timestamps.length - 1];
  11098. }
  11099. const min = this.min;
  11100. const max = this.max;
  11101. const ticks = _filterBetween(timestamps, min, max);
  11102. this._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min)) : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max));
  11103. this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined : determineMajorUnit(this._unit);
  11104. this.initOffsets(timestamps);
  11105. if (options.reverse) {
  11106. ticks.reverse();
  11107. }
  11108. return ticksFromTimestamps(this, ticks, this._majorUnit);
  11109. }
  11110. afterAutoSkip() {
  11111. if (this.options.offsetAfterAutoskip) {
  11112. this.initOffsets(this.ticks.map((tick)=>+tick.value));
  11113. }
  11114. }
  11115. initOffsets(timestamps = []) {
  11116. let start = 0;
  11117. let end = 0;
  11118. let first, last;
  11119. if (this.options.offset && timestamps.length) {
  11120. first = this.getDecimalForValue(timestamps[0]);
  11121. if (timestamps.length === 1) {
  11122. start = 1 - first;
  11123. } else {
  11124. start = (this.getDecimalForValue(timestamps[1]) - first) / 2;
  11125. }
  11126. last = this.getDecimalForValue(timestamps[timestamps.length - 1]);
  11127. if (timestamps.length === 1) {
  11128. end = last;
  11129. } else {
  11130. end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
  11131. }
  11132. }
  11133. const limit = timestamps.length < 3 ? 0.5 : 0.25;
  11134. start = _limitValue(start, 0, limit);
  11135. end = _limitValue(end, 0, limit);
  11136. this._offsets = {
  11137. start,
  11138. end,
  11139. factor: 1 / (start + 1 + end)
  11140. };
  11141. }
  11142. _generate() {
  11143. const adapter = this._adapter;
  11144. const min = this.min;
  11145. const max = this.max;
  11146. const options = this.options;
  11147. const timeOpts = options.time;
  11148. const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min));
  11149. const stepSize = valueOrDefault(options.ticks.stepSize, 1);
  11150. const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  11151. const hasWeekday = isNumber(weekday) || weekday === true;
  11152. const ticks = {};
  11153. let first = min;
  11154. let time, count;
  11155. if (hasWeekday) {
  11156. first = +adapter.startOf(first, 'isoWeek', weekday);
  11157. }
  11158. first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
  11159. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  11160. throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
  11161. }
  11162. const timestamps = options.ticks.source === 'data' && this.getDataTimestamps();
  11163. for(time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++){
  11164. addTick(ticks, time, timestamps);
  11165. }
  11166. if (time === max || options.bounds === 'ticks' || count === 1) {
  11167. addTick(ticks, time, timestamps);
  11168. }
  11169. return Object.keys(ticks).sort(sorter).map((x)=>+x);
  11170. }
  11171. getLabelForValue(value) {
  11172. const adapter = this._adapter;
  11173. const timeOpts = this.options.time;
  11174. if (timeOpts.tooltipFormat) {
  11175. return adapter.format(value, timeOpts.tooltipFormat);
  11176. }
  11177. return adapter.format(value, timeOpts.displayFormats.datetime);
  11178. }
  11179. format(value, format) {
  11180. const options = this.options;
  11181. const formats = options.time.displayFormats;
  11182. const unit = this._unit;
  11183. const fmt = format || formats[unit];
  11184. return this._adapter.format(value, fmt);
  11185. }
  11186. _tickFormatFunction(time, index, ticks, format) {
  11187. const options = this.options;
  11188. const formatter = options.ticks.callback;
  11189. if (formatter) {
  11190. return callback(formatter, [
  11191. time,
  11192. index,
  11193. ticks
  11194. ], this);
  11195. }
  11196. const formats = options.time.displayFormats;
  11197. const unit = this._unit;
  11198. const majorUnit = this._majorUnit;
  11199. const minorFormat = unit && formats[unit];
  11200. const majorFormat = majorUnit && formats[majorUnit];
  11201. const tick = ticks[index];
  11202. const major = majorUnit && majorFormat && tick && tick.major;
  11203. return this._adapter.format(time, format || (major ? majorFormat : minorFormat));
  11204. }
  11205. generateTickLabels(ticks) {
  11206. let i, ilen, tick;
  11207. for(i = 0, ilen = ticks.length; i < ilen; ++i){
  11208. tick = ticks[i];
  11209. tick.label = this._tickFormatFunction(tick.value, i, ticks);
  11210. }
  11211. }
  11212. getDecimalForValue(value) {
  11213. return value === null ? NaN : (value - this.min) / (this.max - this.min);
  11214. }
  11215. getPixelForValue(value) {
  11216. const offsets = this._offsets;
  11217. const pos = this.getDecimalForValue(value);
  11218. return this.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  11219. }
  11220. getValueForPixel(pixel) {
  11221. const offsets = this._offsets;
  11222. const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  11223. return this.min + pos * (this.max - this.min);
  11224. }
  11225. _getLabelSize(label) {
  11226. const ticksOpts = this.options.ticks;
  11227. const tickLabelWidth = this.ctx.measureText(label).width;
  11228. const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  11229. const cosRotation = Math.cos(angle);
  11230. const sinRotation = Math.sin(angle);
  11231. const tickFontSize = this._resolveTickFontOptions(0).size;
  11232. return {
  11233. w: tickLabelWidth * cosRotation + tickFontSize * sinRotation,
  11234. h: tickLabelWidth * sinRotation + tickFontSize * cosRotation
  11235. };
  11236. }
  11237. _getLabelCapacity(exampleTime) {
  11238. const timeOpts = this.options.time;
  11239. const displayFormats = timeOpts.displayFormats;
  11240. const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  11241. const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [
  11242. exampleTime
  11243. ], this._majorUnit), format);
  11244. const size = this._getLabelSize(exampleLabel);
  11245. const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1;
  11246. return capacity > 0 ? capacity : 1;
  11247. }
  11248. getDataTimestamps() {
  11249. let timestamps = this._cache.data || [];
  11250. let i, ilen;
  11251. if (timestamps.length) {
  11252. return timestamps;
  11253. }
  11254. const metas = this.getMatchingVisibleMetas();
  11255. if (this._normalized && metas.length) {
  11256. return this._cache.data = metas[0].controller.getAllParsedValues(this);
  11257. }
  11258. for(i = 0, ilen = metas.length; i < ilen; ++i){
  11259. timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this));
  11260. }
  11261. return this._cache.data = this.normalize(timestamps);
  11262. }
  11263. getLabelTimestamps() {
  11264. const timestamps = this._cache.labels || [];
  11265. let i, ilen;
  11266. if (timestamps.length) {
  11267. return timestamps;
  11268. }
  11269. const labels = this.getLabels();
  11270. for(i = 0, ilen = labels.length; i < ilen; ++i){
  11271. timestamps.push(parse(this, labels[i]));
  11272. }
  11273. return this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps);
  11274. }
  11275. normalize(values) {
  11276. return _arrayUnique(values.sort(sorter));
  11277. }
  11278. }
  11279. function interpolate(table, val, reverse) {
  11280. let lo = 0;
  11281. let hi = table.length - 1;
  11282. let prevSource, nextSource, prevTarget, nextTarget;
  11283. if (reverse) {
  11284. if (val >= table[lo].pos && val <= table[hi].pos) {
  11285. ({ lo , hi } = _lookupByKey(table, 'pos', val));
  11286. }
  11287. ({ pos: prevSource , time: prevTarget } = table[lo]);
  11288. ({ pos: nextSource , time: nextTarget } = table[hi]);
  11289. } else {
  11290. if (val >= table[lo].time && val <= table[hi].time) {
  11291. ({ lo , hi } = _lookupByKey(table, 'time', val));
  11292. }
  11293. ({ time: prevSource , pos: prevTarget } = table[lo]);
  11294. ({ time: nextSource , pos: nextTarget } = table[hi]);
  11295. }
  11296. const span = nextSource - prevSource;
  11297. return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
  11298. }
  11299. class TimeSeriesScale extends TimeScale {
  11300. static id = 'timeseries';
  11301. static defaults = TimeScale.defaults;
  11302. constructor(props){
  11303. super(props);
  11304. this._table = [];
  11305. this._minPos = undefined;
  11306. this._tableRange = undefined;
  11307. }
  11308. initOffsets() {
  11309. const timestamps = this._getTimestampsForTable();
  11310. const table = this._table = this.buildLookupTable(timestamps);
  11311. this._minPos = interpolate(table, this.min);
  11312. this._tableRange = interpolate(table, this.max) - this._minPos;
  11313. super.initOffsets(timestamps);
  11314. }
  11315. buildLookupTable(timestamps) {
  11316. const { min , max } = this;
  11317. const items = [];
  11318. const table = [];
  11319. let i, ilen, prev, curr, next;
  11320. for(i = 0, ilen = timestamps.length; i < ilen; ++i){
  11321. curr = timestamps[i];
  11322. if (curr >= min && curr <= max) {
  11323. items.push(curr);
  11324. }
  11325. }
  11326. if (items.length < 2) {
  11327. return [
  11328. {
  11329. time: min,
  11330. pos: 0
  11331. },
  11332. {
  11333. time: max,
  11334. pos: 1
  11335. }
  11336. ];
  11337. }
  11338. for(i = 0, ilen = items.length; i < ilen; ++i){
  11339. next = items[i + 1];
  11340. prev = items[i - 1];
  11341. curr = items[i];
  11342. if (Math.round((next + prev) / 2) !== curr) {
  11343. table.push({
  11344. time: curr,
  11345. pos: i / (ilen - 1)
  11346. });
  11347. }
  11348. }
  11349. return table;
  11350. }
  11351. _generate() {
  11352. const min = this.min;
  11353. const max = this.max;
  11354. let timestamps = super.getDataTimestamps();
  11355. if (!timestamps.includes(min) || !timestamps.length) {
  11356. timestamps.splice(0, 0, min);
  11357. }
  11358. if (!timestamps.includes(max) || timestamps.length === 1) {
  11359. timestamps.push(max);
  11360. }
  11361. return timestamps.sort((a, b)=>a - b);
  11362. }
  11363. _getTimestampsForTable() {
  11364. let timestamps = this._cache.all || [];
  11365. if (timestamps.length) {
  11366. return timestamps;
  11367. }
  11368. const data = this.getDataTimestamps();
  11369. const label = this.getLabelTimestamps();
  11370. if (data.length && label.length) {
  11371. timestamps = this.normalize(data.concat(label));
  11372. } else {
  11373. timestamps = data.length ? data : label;
  11374. }
  11375. timestamps = this._cache.all = timestamps;
  11376. return timestamps;
  11377. }
  11378. getDecimalForValue(value) {
  11379. return (interpolate(this._table, value) - this._minPos) / this._tableRange;
  11380. }
  11381. getValueForPixel(pixel) {
  11382. const offsets = this._offsets;
  11383. const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  11384. return interpolate(this._table, decimal * this._tableRange + this._minPos, true);
  11385. }
  11386. }
  11387. var scales = /*#__PURE__*/Object.freeze({
  11388. __proto__: null,
  11389. CategoryScale: CategoryScale,
  11390. LinearScale: LinearScale,
  11391. LogarithmicScale: LogarithmicScale,
  11392. RadialLinearScale: RadialLinearScale,
  11393. TimeScale: TimeScale,
  11394. TimeSeriesScale: TimeSeriesScale
  11395. });
  11396. const registerables = [
  11397. controllers,
  11398. elements,
  11399. plugins,
  11400. scales
  11401. ];
  11402. export { Animation, Animations, ArcElement, BarController, BarElement, BasePlatform, BasicPlatform, BubbleController, CategoryScale, Chart, plugin_colors as Colors, DatasetController, plugin_decimation as Decimation, DomPlatform, DoughnutController, Element, index as Filler, Interaction, plugin_legend as Legend, LineController, LineElement, LinearScale, LogarithmicScale, PieController, PointElement, PolarAreaController, RadarController, RadialLinearScale, Scale, ScatterController, plugin_subtitle as SubTitle, Ticks, TimeScale, TimeSeriesScale, plugin_title as Title, plugin_tooltip as Tooltip, adapters as _adapters, _detectPlatform, animator, controllers, defaults, elements, layouts, plugins, registerables, registry, scales };
  11403. //# sourceMappingURL=chart.js.map