chart.cjs 400 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510
  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. 'use strict';
  8. var helpers_segment = require('./chunks/helpers.segment.cjs');
  9. require('@kurkle/color');
  10. class Animator {
  11. constructor(){
  12. this._request = null;
  13. this._charts = new Map();
  14. this._running = false;
  15. this._lastDate = undefined;
  16. }
  17. _notify(chart, anims, date, type) {
  18. const callbacks = anims.listeners[type];
  19. const numSteps = anims.duration;
  20. callbacks.forEach((fn)=>fn({
  21. chart,
  22. initial: anims.initial,
  23. numSteps,
  24. currentStep: Math.min(date - anims.start, numSteps)
  25. }));
  26. }
  27. _refresh() {
  28. if (this._request) {
  29. return;
  30. }
  31. this._running = true;
  32. this._request = helpers_segment.requestAnimFrame.call(window, ()=>{
  33. this._update();
  34. this._request = null;
  35. if (this._running) {
  36. this._refresh();
  37. }
  38. });
  39. }
  40. _update(date = Date.now()) {
  41. let remaining = 0;
  42. this._charts.forEach((anims, chart)=>{
  43. if (!anims.running || !anims.items.length) {
  44. return;
  45. }
  46. const items = anims.items;
  47. let i = items.length - 1;
  48. let draw = false;
  49. let item;
  50. for(; i >= 0; --i){
  51. item = items[i];
  52. if (item._active) {
  53. if (item._total > anims.duration) {
  54. anims.duration = item._total;
  55. }
  56. item.tick(date);
  57. draw = true;
  58. } else {
  59. items[i] = items[items.length - 1];
  60. items.pop();
  61. }
  62. }
  63. if (draw) {
  64. chart.draw();
  65. this._notify(chart, anims, date, 'progress');
  66. }
  67. if (!items.length) {
  68. anims.running = false;
  69. this._notify(chart, anims, date, 'complete');
  70. anims.initial = false;
  71. }
  72. remaining += items.length;
  73. });
  74. this._lastDate = date;
  75. if (remaining === 0) {
  76. this._running = false;
  77. }
  78. }
  79. _getAnims(chart) {
  80. const charts = this._charts;
  81. let anims = charts.get(chart);
  82. if (!anims) {
  83. anims = {
  84. running: false,
  85. initial: true,
  86. items: [],
  87. listeners: {
  88. complete: [],
  89. progress: []
  90. }
  91. };
  92. charts.set(chart, anims);
  93. }
  94. return anims;
  95. }
  96. listen(chart, event, cb) {
  97. this._getAnims(chart).listeners[event].push(cb);
  98. }
  99. add(chart, items) {
  100. if (!items || !items.length) {
  101. return;
  102. }
  103. this._getAnims(chart).items.push(...items);
  104. }
  105. has(chart) {
  106. return this._getAnims(chart).items.length > 0;
  107. }
  108. start(chart) {
  109. const anims = this._charts.get(chart);
  110. if (!anims) {
  111. return;
  112. }
  113. anims.running = true;
  114. anims.start = Date.now();
  115. anims.duration = anims.items.reduce((acc, cur)=>Math.max(acc, cur._duration), 0);
  116. this._refresh();
  117. }
  118. running(chart) {
  119. if (!this._running) {
  120. return false;
  121. }
  122. const anims = this._charts.get(chart);
  123. if (!anims || !anims.running || !anims.items.length) {
  124. return false;
  125. }
  126. return true;
  127. }
  128. stop(chart) {
  129. const anims = this._charts.get(chart);
  130. if (!anims || !anims.items.length) {
  131. return;
  132. }
  133. const items = anims.items;
  134. let i = items.length - 1;
  135. for(; i >= 0; --i){
  136. items[i].cancel();
  137. }
  138. anims.items = [];
  139. this._notify(chart, anims, Date.now(), 'complete');
  140. }
  141. remove(chart) {
  142. return this._charts.delete(chart);
  143. }
  144. }
  145. var animator = /* #__PURE__ */ new Animator();
  146. const transparent = 'transparent';
  147. const interpolators = {
  148. boolean (from, to, factor) {
  149. return factor > 0.5 ? to : from;
  150. },
  151. color (from, to, factor) {
  152. const c0 = helpers_segment.color(from || transparent);
  153. const c1 = c0.valid && helpers_segment.color(to || transparent);
  154. return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to;
  155. },
  156. number (from, to, factor) {
  157. return from + (to - from) * factor;
  158. }
  159. };
  160. class Animation {
  161. constructor(cfg, target, prop, to){
  162. const currentValue = target[prop];
  163. to = helpers_segment.resolve([
  164. cfg.to,
  165. to,
  166. currentValue,
  167. cfg.from
  168. ]);
  169. const from = helpers_segment.resolve([
  170. cfg.from,
  171. currentValue,
  172. to
  173. ]);
  174. this._active = true;
  175. this._fn = cfg.fn || interpolators[cfg.type || typeof from];
  176. this._easing = helpers_segment.effects[cfg.easing] || helpers_segment.effects.linear;
  177. this._start = Math.floor(Date.now() + (cfg.delay || 0));
  178. this._duration = this._total = Math.floor(cfg.duration);
  179. this._loop = !!cfg.loop;
  180. this._target = target;
  181. this._prop = prop;
  182. this._from = from;
  183. this._to = to;
  184. this._promises = undefined;
  185. }
  186. active() {
  187. return this._active;
  188. }
  189. update(cfg, to, date) {
  190. if (this._active) {
  191. this._notify(false);
  192. const currentValue = this._target[this._prop];
  193. const elapsed = date - this._start;
  194. const remain = this._duration - elapsed;
  195. this._start = date;
  196. this._duration = Math.floor(Math.max(remain, cfg.duration));
  197. this._total += elapsed;
  198. this._loop = !!cfg.loop;
  199. this._to = helpers_segment.resolve([
  200. cfg.to,
  201. to,
  202. currentValue,
  203. cfg.from
  204. ]);
  205. this._from = helpers_segment.resolve([
  206. cfg.from,
  207. currentValue,
  208. to
  209. ]);
  210. }
  211. }
  212. cancel() {
  213. if (this._active) {
  214. this.tick(Date.now());
  215. this._active = false;
  216. this._notify(false);
  217. }
  218. }
  219. tick(date) {
  220. const elapsed = date - this._start;
  221. const duration = this._duration;
  222. const prop = this._prop;
  223. const from = this._from;
  224. const loop = this._loop;
  225. const to = this._to;
  226. let factor;
  227. this._active = from !== to && (loop || elapsed < duration);
  228. if (!this._active) {
  229. this._target[prop] = to;
  230. this._notify(true);
  231. return;
  232. }
  233. if (elapsed < 0) {
  234. this._target[prop] = from;
  235. return;
  236. }
  237. factor = elapsed / duration % 2;
  238. factor = loop && factor > 1 ? 2 - factor : factor;
  239. factor = this._easing(Math.min(1, Math.max(0, factor)));
  240. this._target[prop] = this._fn(from, to, factor);
  241. }
  242. wait() {
  243. const promises = this._promises || (this._promises = []);
  244. return new Promise((res, rej)=>{
  245. promises.push({
  246. res,
  247. rej
  248. });
  249. });
  250. }
  251. _notify(resolved) {
  252. const method = resolved ? 'res' : 'rej';
  253. const promises = this._promises || [];
  254. for(let i = 0; i < promises.length; i++){
  255. promises[i][method]();
  256. }
  257. }
  258. }
  259. class Animations {
  260. constructor(chart, config){
  261. this._chart = chart;
  262. this._properties = new Map();
  263. this.configure(config);
  264. }
  265. configure(config) {
  266. if (!helpers_segment.isObject(config)) {
  267. return;
  268. }
  269. const animationOptions = Object.keys(helpers_segment.defaults.animation);
  270. const animatedProps = this._properties;
  271. Object.getOwnPropertyNames(config).forEach((key)=>{
  272. const cfg = config[key];
  273. if (!helpers_segment.isObject(cfg)) {
  274. return;
  275. }
  276. const resolved = {};
  277. for (const option of animationOptions){
  278. resolved[option] = cfg[option];
  279. }
  280. (helpers_segment.isArray(cfg.properties) && cfg.properties || [
  281. key
  282. ]).forEach((prop)=>{
  283. if (prop === key || !animatedProps.has(prop)) {
  284. animatedProps.set(prop, resolved);
  285. }
  286. });
  287. });
  288. }
  289. _animateOptions(target, values) {
  290. const newOptions = values.options;
  291. const options = resolveTargetOptions(target, newOptions);
  292. if (!options) {
  293. return [];
  294. }
  295. const animations = this._createAnimations(options, newOptions);
  296. if (newOptions.$shared) {
  297. awaitAll(target.options.$animations, newOptions).then(()=>{
  298. target.options = newOptions;
  299. }, ()=>{
  300. });
  301. }
  302. return animations;
  303. }
  304. _createAnimations(target, values) {
  305. const animatedProps = this._properties;
  306. const animations = [];
  307. const running = target.$animations || (target.$animations = {});
  308. const props = Object.keys(values);
  309. const date = Date.now();
  310. let i;
  311. for(i = props.length - 1; i >= 0; --i){
  312. const prop = props[i];
  313. if (prop.charAt(0) === '$') {
  314. continue;
  315. }
  316. if (prop === 'options') {
  317. animations.push(...this._animateOptions(target, values));
  318. continue;
  319. }
  320. const value = values[prop];
  321. let animation = running[prop];
  322. const cfg = animatedProps.get(prop);
  323. if (animation) {
  324. if (cfg && animation.active()) {
  325. animation.update(cfg, value, date);
  326. continue;
  327. } else {
  328. animation.cancel();
  329. }
  330. }
  331. if (!cfg || !cfg.duration) {
  332. target[prop] = value;
  333. continue;
  334. }
  335. running[prop] = animation = new Animation(cfg, target, prop, value);
  336. animations.push(animation);
  337. }
  338. return animations;
  339. }
  340. update(target, values) {
  341. if (this._properties.size === 0) {
  342. Object.assign(target, values);
  343. return;
  344. }
  345. const animations = this._createAnimations(target, values);
  346. if (animations.length) {
  347. animator.add(this._chart, animations);
  348. return true;
  349. }
  350. }
  351. }
  352. function awaitAll(animations, properties) {
  353. const running = [];
  354. const keys = Object.keys(properties);
  355. for(let i = 0; i < keys.length; i++){
  356. const anim = animations[keys[i]];
  357. if (anim && anim.active()) {
  358. running.push(anim.wait());
  359. }
  360. }
  361. return Promise.all(running);
  362. }
  363. function resolveTargetOptions(target, newOptions) {
  364. if (!newOptions) {
  365. return;
  366. }
  367. let options = target.options;
  368. if (!options) {
  369. target.options = newOptions;
  370. return;
  371. }
  372. if (options.$shared) {
  373. target.options = options = Object.assign({}, options, {
  374. $shared: false,
  375. $animations: {}
  376. });
  377. }
  378. return options;
  379. }
  380. function scaleClip(scale, allowedOverflow) {
  381. const opts = scale && scale.options || {};
  382. const reverse = opts.reverse;
  383. const min = opts.min === undefined ? allowedOverflow : 0;
  384. const max = opts.max === undefined ? allowedOverflow : 0;
  385. return {
  386. start: reverse ? max : min,
  387. end: reverse ? min : max
  388. };
  389. }
  390. function defaultClip(xScale, yScale, allowedOverflow) {
  391. if (allowedOverflow === false) {
  392. return false;
  393. }
  394. const x = scaleClip(xScale, allowedOverflow);
  395. const y = scaleClip(yScale, allowedOverflow);
  396. return {
  397. top: y.end,
  398. right: x.end,
  399. bottom: y.start,
  400. left: x.start
  401. };
  402. }
  403. function toClip(value) {
  404. let t, r, b, l;
  405. if (helpers_segment.isObject(value)) {
  406. t = value.top;
  407. r = value.right;
  408. b = value.bottom;
  409. l = value.left;
  410. } else {
  411. t = r = b = l = value;
  412. }
  413. return {
  414. top: t,
  415. right: r,
  416. bottom: b,
  417. left: l,
  418. disabled: value === false
  419. };
  420. }
  421. function getSortedDatasetIndices(chart, filterVisible) {
  422. const keys = [];
  423. const metasets = chart._getSortedDatasetMetas(filterVisible);
  424. let i, ilen;
  425. for(i = 0, ilen = metasets.length; i < ilen; ++i){
  426. keys.push(metasets[i].index);
  427. }
  428. return keys;
  429. }
  430. function applyStack(stack, value, dsIndex, options = {}) {
  431. const keys = stack.keys;
  432. const singleMode = options.mode === 'single';
  433. let i, ilen, datasetIndex, otherValue;
  434. if (value === null) {
  435. return;
  436. }
  437. for(i = 0, ilen = keys.length; i < ilen; ++i){
  438. datasetIndex = +keys[i];
  439. if (datasetIndex === dsIndex) {
  440. if (options.all) {
  441. continue;
  442. }
  443. break;
  444. }
  445. otherValue = stack.values[datasetIndex];
  446. if (helpers_segment.isNumberFinite(otherValue) && (singleMode || value === 0 || helpers_segment.sign(value) === helpers_segment.sign(otherValue))) {
  447. value += otherValue;
  448. }
  449. }
  450. return value;
  451. }
  452. function convertObjectDataToArray(data) {
  453. const keys = Object.keys(data);
  454. const adata = new Array(keys.length);
  455. let i, ilen, key;
  456. for(i = 0, ilen = keys.length; i < ilen; ++i){
  457. key = keys[i];
  458. adata[i] = {
  459. x: key,
  460. y: data[key]
  461. };
  462. }
  463. return adata;
  464. }
  465. function isStacked(scale, meta) {
  466. const stacked = scale && scale.options.stacked;
  467. return stacked || stacked === undefined && meta.stack !== undefined;
  468. }
  469. function getStackKey(indexScale, valueScale, meta) {
  470. return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
  471. }
  472. function getUserBounds(scale) {
  473. const { min , max , minDefined , maxDefined } = scale.getUserBounds();
  474. return {
  475. min: minDefined ? min : Number.NEGATIVE_INFINITY,
  476. max: maxDefined ? max : Number.POSITIVE_INFINITY
  477. };
  478. }
  479. function getOrCreateStack(stacks, stackKey, indexValue) {
  480. const subStack = stacks[stackKey] || (stacks[stackKey] = {});
  481. return subStack[indexValue] || (subStack[indexValue] = {});
  482. }
  483. function getLastIndexInStack(stack, vScale, positive, type) {
  484. for (const meta of vScale.getMatchingVisibleMetas(type).reverse()){
  485. const value = stack[meta.index];
  486. if (positive && value > 0 || !positive && value < 0) {
  487. return meta.index;
  488. }
  489. }
  490. return null;
  491. }
  492. function updateStacks(controller, parsed) {
  493. const { chart , _cachedMeta: meta } = controller;
  494. const stacks = chart._stacks || (chart._stacks = {});
  495. const { iScale , vScale , index: datasetIndex } = meta;
  496. const iAxis = iScale.axis;
  497. const vAxis = vScale.axis;
  498. const key = getStackKey(iScale, vScale, meta);
  499. const ilen = parsed.length;
  500. let stack;
  501. for(let i = 0; i < ilen; ++i){
  502. const item = parsed[i];
  503. const { [iAxis]: index , [vAxis]: value } = item;
  504. const itemStacks = item._stacks || (item._stacks = {});
  505. stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
  506. stack[datasetIndex] = value;
  507. stack._top = getLastIndexInStack(stack, vScale, true, meta.type);
  508. stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);
  509. const visualValues = stack._visualValues || (stack._visualValues = {});
  510. visualValues[datasetIndex] = value;
  511. }
  512. }
  513. function getFirstScaleId(chart, axis) {
  514. const scales = chart.scales;
  515. return Object.keys(scales).filter((key)=>scales[key].axis === axis).shift();
  516. }
  517. function createDatasetContext(parent, index) {
  518. return helpers_segment.createContext(parent, {
  519. active: false,
  520. dataset: undefined,
  521. datasetIndex: index,
  522. index,
  523. mode: 'default',
  524. type: 'dataset'
  525. });
  526. }
  527. function createDataContext(parent, index, element) {
  528. return helpers_segment.createContext(parent, {
  529. active: false,
  530. dataIndex: index,
  531. parsed: undefined,
  532. raw: undefined,
  533. element,
  534. index,
  535. mode: 'default',
  536. type: 'data'
  537. });
  538. }
  539. function clearStacks(meta, items) {
  540. const datasetIndex = meta.controller.index;
  541. const axis = meta.vScale && meta.vScale.axis;
  542. if (!axis) {
  543. return;
  544. }
  545. items = items || meta._parsed;
  546. for (const parsed of items){
  547. const stacks = parsed._stacks;
  548. if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {
  549. return;
  550. }
  551. delete stacks[axis][datasetIndex];
  552. if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {
  553. delete stacks[axis]._visualValues[datasetIndex];
  554. }
  555. }
  556. }
  557. const isDirectUpdateMode = (mode)=>mode === 'reset' || mode === 'none';
  558. const cloneIfNotShared = (cached, shared)=>shared ? cached : Object.assign({}, cached);
  559. const createStack = (canStack, meta, chart)=>canStack && !meta.hidden && meta._stacked && {
  560. keys: getSortedDatasetIndices(chart, true),
  561. values: null
  562. };
  563. class DatasetController {
  564. static defaults = {};
  565. static datasetElementType = null;
  566. static dataElementType = null;
  567. constructor(chart, datasetIndex){
  568. this.chart = chart;
  569. this._ctx = chart.ctx;
  570. this.index = datasetIndex;
  571. this._cachedDataOpts = {};
  572. this._cachedMeta = this.getMeta();
  573. this._type = this._cachedMeta.type;
  574. this.options = undefined;
  575. this._parsing = false;
  576. this._data = undefined;
  577. this._objectData = undefined;
  578. this._sharedOptions = undefined;
  579. this._drawStart = undefined;
  580. this._drawCount = undefined;
  581. this.enableOptionSharing = false;
  582. this.supportsDecimation = false;
  583. this.$context = undefined;
  584. this._syncList = [];
  585. this.datasetElementType = new.target.datasetElementType;
  586. this.dataElementType = new.target.dataElementType;
  587. this.initialize();
  588. }
  589. initialize() {
  590. const meta = this._cachedMeta;
  591. this.configure();
  592. this.linkScales();
  593. meta._stacked = isStacked(meta.vScale, meta);
  594. this.addElements();
  595. if (this.options.fill && !this.chart.isPluginEnabled('filler')) {
  596. 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");
  597. }
  598. }
  599. updateIndex(datasetIndex) {
  600. if (this.index !== datasetIndex) {
  601. clearStacks(this._cachedMeta);
  602. }
  603. this.index = datasetIndex;
  604. }
  605. linkScales() {
  606. const chart = this.chart;
  607. const meta = this._cachedMeta;
  608. const dataset = this.getDataset();
  609. const chooseId = (axis, x, y, r)=>axis === 'x' ? x : axis === 'r' ? r : y;
  610. const xid = meta.xAxisID = helpers_segment.valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
  611. const yid = meta.yAxisID = helpers_segment.valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
  612. const rid = meta.rAxisID = helpers_segment.valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
  613. const indexAxis = meta.indexAxis;
  614. const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
  615. const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
  616. meta.xScale = this.getScaleForId(xid);
  617. meta.yScale = this.getScaleForId(yid);
  618. meta.rScale = this.getScaleForId(rid);
  619. meta.iScale = this.getScaleForId(iid);
  620. meta.vScale = this.getScaleForId(vid);
  621. }
  622. getDataset() {
  623. return this.chart.data.datasets[this.index];
  624. }
  625. getMeta() {
  626. return this.chart.getDatasetMeta(this.index);
  627. }
  628. getScaleForId(scaleID) {
  629. return this.chart.scales[scaleID];
  630. }
  631. _getOtherScale(scale) {
  632. const meta = this._cachedMeta;
  633. return scale === meta.iScale ? meta.vScale : meta.iScale;
  634. }
  635. reset() {
  636. this._update('reset');
  637. }
  638. _destroy() {
  639. const meta = this._cachedMeta;
  640. if (this._data) {
  641. helpers_segment.unlistenArrayEvents(this._data, this);
  642. }
  643. if (meta._stacked) {
  644. clearStacks(meta);
  645. }
  646. }
  647. _dataCheck() {
  648. const dataset = this.getDataset();
  649. const data = dataset.data || (dataset.data = []);
  650. const _data = this._data;
  651. if (helpers_segment.isObject(data)) {
  652. this._data = convertObjectDataToArray(data);
  653. } else if (_data !== data) {
  654. if (_data) {
  655. helpers_segment.unlistenArrayEvents(_data, this);
  656. const meta = this._cachedMeta;
  657. clearStacks(meta);
  658. meta._parsed = [];
  659. }
  660. if (data && Object.isExtensible(data)) {
  661. helpers_segment.listenArrayEvents(data, this);
  662. }
  663. this._syncList = [];
  664. this._data = data;
  665. }
  666. }
  667. addElements() {
  668. const meta = this._cachedMeta;
  669. this._dataCheck();
  670. if (this.datasetElementType) {
  671. meta.dataset = new this.datasetElementType();
  672. }
  673. }
  674. buildOrUpdateElements(resetNewElements) {
  675. const meta = this._cachedMeta;
  676. const dataset = this.getDataset();
  677. let stackChanged = false;
  678. this._dataCheck();
  679. const oldStacked = meta._stacked;
  680. meta._stacked = isStacked(meta.vScale, meta);
  681. if (meta.stack !== dataset.stack) {
  682. stackChanged = true;
  683. clearStacks(meta);
  684. meta.stack = dataset.stack;
  685. }
  686. this._resyncElements(resetNewElements);
  687. if (stackChanged || oldStacked !== meta._stacked) {
  688. updateStacks(this, meta._parsed);
  689. }
  690. }
  691. configure() {
  692. const config = this.chart.config;
  693. const scopeKeys = config.datasetScopeKeys(this._type);
  694. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);
  695. this.options = config.createResolver(scopes, this.getContext());
  696. this._parsing = this.options.parsing;
  697. this._cachedDataOpts = {};
  698. }
  699. parse(start, count) {
  700. const { _cachedMeta: meta , _data: data } = this;
  701. const { iScale , _stacked } = meta;
  702. const iAxis = iScale.axis;
  703. let sorted = start === 0 && count === data.length ? true : meta._sorted;
  704. let prev = start > 0 && meta._parsed[start - 1];
  705. let i, cur, parsed;
  706. if (this._parsing === false) {
  707. meta._parsed = data;
  708. meta._sorted = true;
  709. parsed = data;
  710. } else {
  711. if (helpers_segment.isArray(data[start])) {
  712. parsed = this.parseArrayData(meta, data, start, count);
  713. } else if (helpers_segment.isObject(data[start])) {
  714. parsed = this.parseObjectData(meta, data, start, count);
  715. } else {
  716. parsed = this.parsePrimitiveData(meta, data, start, count);
  717. }
  718. const isNotInOrderComparedToPrev = ()=>cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis];
  719. for(i = 0; i < count; ++i){
  720. meta._parsed[i + start] = cur = parsed[i];
  721. if (sorted) {
  722. if (isNotInOrderComparedToPrev()) {
  723. sorted = false;
  724. }
  725. prev = cur;
  726. }
  727. }
  728. meta._sorted = sorted;
  729. }
  730. if (_stacked) {
  731. updateStacks(this, parsed);
  732. }
  733. }
  734. parsePrimitiveData(meta, data, start, count) {
  735. const { iScale , vScale } = meta;
  736. const iAxis = iScale.axis;
  737. const vAxis = vScale.axis;
  738. const labels = iScale.getLabels();
  739. const singleScale = iScale === vScale;
  740. const parsed = new Array(count);
  741. let i, ilen, index;
  742. for(i = 0, ilen = count; i < ilen; ++i){
  743. index = i + start;
  744. parsed[i] = {
  745. [iAxis]: singleScale || iScale.parse(labels[index], index),
  746. [vAxis]: vScale.parse(data[index], index)
  747. };
  748. }
  749. return parsed;
  750. }
  751. parseArrayData(meta, data, start, count) {
  752. const { xScale , yScale } = meta;
  753. const parsed = new Array(count);
  754. let i, ilen, index, item;
  755. for(i = 0, ilen = count; i < ilen; ++i){
  756. index = i + start;
  757. item = data[index];
  758. parsed[i] = {
  759. x: xScale.parse(item[0], index),
  760. y: yScale.parse(item[1], index)
  761. };
  762. }
  763. return parsed;
  764. }
  765. parseObjectData(meta, data, start, count) {
  766. const { xScale , yScale } = meta;
  767. const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing;
  768. const parsed = new Array(count);
  769. let i, ilen, index, item;
  770. for(i = 0, ilen = count; i < ilen; ++i){
  771. index = i + start;
  772. item = data[index];
  773. parsed[i] = {
  774. x: xScale.parse(helpers_segment.resolveObjectKey(item, xAxisKey), index),
  775. y: yScale.parse(helpers_segment.resolveObjectKey(item, yAxisKey), index)
  776. };
  777. }
  778. return parsed;
  779. }
  780. getParsed(index) {
  781. return this._cachedMeta._parsed[index];
  782. }
  783. getDataElement(index) {
  784. return this._cachedMeta.data[index];
  785. }
  786. applyStack(scale, parsed, mode) {
  787. const chart = this.chart;
  788. const meta = this._cachedMeta;
  789. const value = parsed[scale.axis];
  790. const stack = {
  791. keys: getSortedDatasetIndices(chart, true),
  792. values: parsed._stacks[scale.axis]._visualValues
  793. };
  794. return applyStack(stack, value, meta.index, {
  795. mode
  796. });
  797. }
  798. updateRangeFromParsed(range, scale, parsed, stack) {
  799. const parsedValue = parsed[scale.axis];
  800. let value = parsedValue === null ? NaN : parsedValue;
  801. const values = stack && parsed._stacks[scale.axis];
  802. if (stack && values) {
  803. stack.values = values;
  804. value = applyStack(stack, parsedValue, this._cachedMeta.index);
  805. }
  806. range.min = Math.min(range.min, value);
  807. range.max = Math.max(range.max, value);
  808. }
  809. getMinMax(scale, canStack) {
  810. const meta = this._cachedMeta;
  811. const _parsed = meta._parsed;
  812. const sorted = meta._sorted && scale === meta.iScale;
  813. const ilen = _parsed.length;
  814. const otherScale = this._getOtherScale(scale);
  815. const stack = createStack(canStack, meta, this.chart);
  816. const range = {
  817. min: Number.POSITIVE_INFINITY,
  818. max: Number.NEGATIVE_INFINITY
  819. };
  820. const { min: otherMin , max: otherMax } = getUserBounds(otherScale);
  821. let i, parsed;
  822. function _skip() {
  823. parsed = _parsed[i];
  824. const otherValue = parsed[otherScale.axis];
  825. return !helpers_segment.isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;
  826. }
  827. for(i = 0; i < ilen; ++i){
  828. if (_skip()) {
  829. continue;
  830. }
  831. this.updateRangeFromParsed(range, scale, parsed, stack);
  832. if (sorted) {
  833. break;
  834. }
  835. }
  836. if (sorted) {
  837. for(i = ilen - 1; i >= 0; --i){
  838. if (_skip()) {
  839. continue;
  840. }
  841. this.updateRangeFromParsed(range, scale, parsed, stack);
  842. break;
  843. }
  844. }
  845. return range;
  846. }
  847. getAllParsedValues(scale) {
  848. const parsed = this._cachedMeta._parsed;
  849. const values = [];
  850. let i, ilen, value;
  851. for(i = 0, ilen = parsed.length; i < ilen; ++i){
  852. value = parsed[i][scale.axis];
  853. if (helpers_segment.isNumberFinite(value)) {
  854. values.push(value);
  855. }
  856. }
  857. return values;
  858. }
  859. getMaxOverflow() {
  860. return false;
  861. }
  862. getLabelAndValue(index) {
  863. const meta = this._cachedMeta;
  864. const iScale = meta.iScale;
  865. const vScale = meta.vScale;
  866. const parsed = this.getParsed(index);
  867. return {
  868. label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
  869. value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
  870. };
  871. }
  872. _update(mode) {
  873. const meta = this._cachedMeta;
  874. this.update(mode || 'default');
  875. meta._clip = toClip(helpers_segment.valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));
  876. }
  877. update(mode) {}
  878. draw() {
  879. const ctx = this._ctx;
  880. const chart = this.chart;
  881. const meta = this._cachedMeta;
  882. const elements = meta.data || [];
  883. const area = chart.chartArea;
  884. const active = [];
  885. const start = this._drawStart || 0;
  886. const count = this._drawCount || elements.length - start;
  887. const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;
  888. let i;
  889. if (meta.dataset) {
  890. meta.dataset.draw(ctx, area, start, count);
  891. }
  892. for(i = start; i < start + count; ++i){
  893. const element = elements[i];
  894. if (element.hidden) {
  895. continue;
  896. }
  897. if (element.active && drawActiveElementsOnTop) {
  898. active.push(element);
  899. } else {
  900. element.draw(ctx, area);
  901. }
  902. }
  903. for(i = 0; i < active.length; ++i){
  904. active[i].draw(ctx, area);
  905. }
  906. }
  907. getStyle(index, active) {
  908. const mode = active ? 'active' : 'default';
  909. return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode);
  910. }
  911. getContext(index, active, mode) {
  912. const dataset = this.getDataset();
  913. let context;
  914. if (index >= 0 && index < this._cachedMeta.data.length) {
  915. const element = this._cachedMeta.data[index];
  916. context = element.$context || (element.$context = createDataContext(this.getContext(), index, element));
  917. context.parsed = this.getParsed(index);
  918. context.raw = dataset.data[index];
  919. context.index = context.dataIndex = index;
  920. } else {
  921. context = this.$context || (this.$context = createDatasetContext(this.chart.getContext(), this.index));
  922. context.dataset = dataset;
  923. context.index = context.datasetIndex = this.index;
  924. }
  925. context.active = !!active;
  926. context.mode = mode;
  927. return context;
  928. }
  929. resolveDatasetElementOptions(mode) {
  930. return this._resolveElementOptions(this.datasetElementType.id, mode);
  931. }
  932. resolveDataElementOptions(index, mode) {
  933. return this._resolveElementOptions(this.dataElementType.id, mode, index);
  934. }
  935. _resolveElementOptions(elementType, mode = 'default', index) {
  936. const active = mode === 'active';
  937. const cache = this._cachedDataOpts;
  938. const cacheKey = elementType + '-' + mode;
  939. const cached = cache[cacheKey];
  940. const sharing = this.enableOptionSharing && helpers_segment.defined(index);
  941. if (cached) {
  942. return cloneIfNotShared(cached, sharing);
  943. }
  944. const config = this.chart.config;
  945. const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);
  946. const prefixes = active ? [
  947. `${elementType}Hover`,
  948. 'hover',
  949. elementType,
  950. ''
  951. ] : [
  952. elementType,
  953. ''
  954. ];
  955. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  956. const names = Object.keys(helpers_segment.defaults.elements[elementType]);
  957. const context = ()=>this.getContext(index, active, mode);
  958. const values = config.resolveNamedOptions(scopes, names, context, prefixes);
  959. if (values.$shared) {
  960. values.$shared = sharing;
  961. cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
  962. }
  963. return values;
  964. }
  965. _resolveAnimations(index, transition, active) {
  966. const chart = this.chart;
  967. const cache = this._cachedDataOpts;
  968. const cacheKey = `animation-${transition}`;
  969. const cached = cache[cacheKey];
  970. if (cached) {
  971. return cached;
  972. }
  973. let options;
  974. if (chart.options.animation !== false) {
  975. const config = this.chart.config;
  976. const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);
  977. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  978. options = config.createResolver(scopes, this.getContext(index, active, transition));
  979. }
  980. const animations = new Animations(chart, options && options.animations);
  981. if (options && options._cacheable) {
  982. cache[cacheKey] = Object.freeze(animations);
  983. }
  984. return animations;
  985. }
  986. getSharedOptions(options) {
  987. if (!options.$shared) {
  988. return;
  989. }
  990. return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
  991. }
  992. includeOptions(mode, sharedOptions) {
  993. return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
  994. }
  995. _getSharedOptions(start, mode) {
  996. const firstOpts = this.resolveDataElementOptions(start, mode);
  997. const previouslySharedOptions = this._sharedOptions;
  998. const sharedOptions = this.getSharedOptions(firstOpts);
  999. const includeOptions = this.includeOptions(mode, sharedOptions) || sharedOptions !== previouslySharedOptions;
  1000. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  1001. return {
  1002. sharedOptions,
  1003. includeOptions
  1004. };
  1005. }
  1006. updateElement(element, index, properties, mode) {
  1007. if (isDirectUpdateMode(mode)) {
  1008. Object.assign(element, properties);
  1009. } else {
  1010. this._resolveAnimations(index, mode).update(element, properties);
  1011. }
  1012. }
  1013. updateSharedOptions(sharedOptions, mode, newOptions) {
  1014. if (sharedOptions && !isDirectUpdateMode(mode)) {
  1015. this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
  1016. }
  1017. }
  1018. _setStyle(element, index, mode, active) {
  1019. element.active = active;
  1020. const options = this.getStyle(index, active);
  1021. this._resolveAnimations(index, mode, active).update(element, {
  1022. options: !active && this.getSharedOptions(options) || options
  1023. });
  1024. }
  1025. removeHoverStyle(element, datasetIndex, index) {
  1026. this._setStyle(element, index, 'active', false);
  1027. }
  1028. setHoverStyle(element, datasetIndex, index) {
  1029. this._setStyle(element, index, 'active', true);
  1030. }
  1031. _removeDatasetHoverStyle() {
  1032. const element = this._cachedMeta.dataset;
  1033. if (element) {
  1034. this._setStyle(element, undefined, 'active', false);
  1035. }
  1036. }
  1037. _setDatasetHoverStyle() {
  1038. const element = this._cachedMeta.dataset;
  1039. if (element) {
  1040. this._setStyle(element, undefined, 'active', true);
  1041. }
  1042. }
  1043. _resyncElements(resetNewElements) {
  1044. const data = this._data;
  1045. const elements = this._cachedMeta.data;
  1046. for (const [method, arg1, arg2] of this._syncList){
  1047. this[method](arg1, arg2);
  1048. }
  1049. this._syncList = [];
  1050. const numMeta = elements.length;
  1051. const numData = data.length;
  1052. const count = Math.min(numData, numMeta);
  1053. if (count) {
  1054. this.parse(0, count);
  1055. }
  1056. if (numData > numMeta) {
  1057. this._insertElements(numMeta, numData - numMeta, resetNewElements);
  1058. } else if (numData < numMeta) {
  1059. this._removeElements(numData, numMeta - numData);
  1060. }
  1061. }
  1062. _insertElements(start, count, resetNewElements = true) {
  1063. const meta = this._cachedMeta;
  1064. const data = meta.data;
  1065. const end = start + count;
  1066. let i;
  1067. const move = (arr)=>{
  1068. arr.length += count;
  1069. for(i = arr.length - 1; i >= end; i--){
  1070. arr[i] = arr[i - count];
  1071. }
  1072. };
  1073. move(data);
  1074. for(i = start; i < end; ++i){
  1075. data[i] = new this.dataElementType();
  1076. }
  1077. if (this._parsing) {
  1078. move(meta._parsed);
  1079. }
  1080. this.parse(start, count);
  1081. if (resetNewElements) {
  1082. this.updateElements(data, start, count, 'reset');
  1083. }
  1084. }
  1085. updateElements(element, start, count, mode) {}
  1086. _removeElements(start, count) {
  1087. const meta = this._cachedMeta;
  1088. if (this._parsing) {
  1089. const removed = meta._parsed.splice(start, count);
  1090. if (meta._stacked) {
  1091. clearStacks(meta, removed);
  1092. }
  1093. }
  1094. meta.data.splice(start, count);
  1095. }
  1096. _sync(args) {
  1097. if (this._parsing) {
  1098. this._syncList.push(args);
  1099. } else {
  1100. const [method, arg1, arg2] = args;
  1101. this[method](arg1, arg2);
  1102. }
  1103. this.chart._dataChanges.push([
  1104. this.index,
  1105. ...args
  1106. ]);
  1107. }
  1108. _onDataPush() {
  1109. const count = arguments.length;
  1110. this._sync([
  1111. '_insertElements',
  1112. this.getDataset().data.length - count,
  1113. count
  1114. ]);
  1115. }
  1116. _onDataPop() {
  1117. this._sync([
  1118. '_removeElements',
  1119. this._cachedMeta.data.length - 1,
  1120. 1
  1121. ]);
  1122. }
  1123. _onDataShift() {
  1124. this._sync([
  1125. '_removeElements',
  1126. 0,
  1127. 1
  1128. ]);
  1129. }
  1130. _onDataSplice(start, count) {
  1131. if (count) {
  1132. this._sync([
  1133. '_removeElements',
  1134. start,
  1135. count
  1136. ]);
  1137. }
  1138. const newCount = arguments.length - 2;
  1139. if (newCount) {
  1140. this._sync([
  1141. '_insertElements',
  1142. start,
  1143. newCount
  1144. ]);
  1145. }
  1146. }
  1147. _onDataUnshift() {
  1148. this._sync([
  1149. '_insertElements',
  1150. 0,
  1151. arguments.length
  1152. ]);
  1153. }
  1154. }
  1155. function getAllScaleValues(scale, type) {
  1156. if (!scale._cache.$bar) {
  1157. const visibleMetas = scale.getMatchingVisibleMetas(type);
  1158. let values = [];
  1159. for(let i = 0, ilen = visibleMetas.length; i < ilen; i++){
  1160. values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));
  1161. }
  1162. scale._cache.$bar = helpers_segment._arrayUnique(values.sort((a, b)=>a - b));
  1163. }
  1164. return scale._cache.$bar;
  1165. }
  1166. function computeMinSampleSize(meta) {
  1167. const scale = meta.iScale;
  1168. const values = getAllScaleValues(scale, meta.type);
  1169. let min = scale._length;
  1170. let i, ilen, curr, prev;
  1171. const updateMinAndPrev = ()=>{
  1172. if (curr === 32767 || curr === -32768) {
  1173. return;
  1174. }
  1175. if (helpers_segment.defined(prev)) {
  1176. min = Math.min(min, Math.abs(curr - prev) || min);
  1177. }
  1178. prev = curr;
  1179. };
  1180. for(i = 0, ilen = values.length; i < ilen; ++i){
  1181. curr = scale.getPixelForValue(values[i]);
  1182. updateMinAndPrev();
  1183. }
  1184. prev = undefined;
  1185. for(i = 0, ilen = scale.ticks.length; i < ilen; ++i){
  1186. curr = scale.getPixelForTick(i);
  1187. updateMinAndPrev();
  1188. }
  1189. return min;
  1190. }
  1191. function computeFitCategoryTraits(index, ruler, options, stackCount) {
  1192. const thickness = options.barThickness;
  1193. let size, ratio;
  1194. if (helpers_segment.isNullOrUndef(thickness)) {
  1195. size = ruler.min * options.categoryPercentage;
  1196. ratio = options.barPercentage;
  1197. } else {
  1198. size = thickness * stackCount;
  1199. ratio = 1;
  1200. }
  1201. return {
  1202. chunk: size / stackCount,
  1203. ratio,
  1204. start: ruler.pixels[index] - size / 2
  1205. };
  1206. }
  1207. function computeFlexCategoryTraits(index, ruler, options, stackCount) {
  1208. const pixels = ruler.pixels;
  1209. const curr = pixels[index];
  1210. let prev = index > 0 ? pixels[index - 1] : null;
  1211. let next = index < pixels.length - 1 ? pixels[index + 1] : null;
  1212. const percent = options.categoryPercentage;
  1213. if (prev === null) {
  1214. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  1215. }
  1216. if (next === null) {
  1217. next = curr + curr - prev;
  1218. }
  1219. const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  1220. const size = Math.abs(next - prev) / 2 * percent;
  1221. return {
  1222. chunk: size / stackCount,
  1223. ratio: options.barPercentage,
  1224. start
  1225. };
  1226. }
  1227. function parseFloatBar(entry, item, vScale, i) {
  1228. const startValue = vScale.parse(entry[0], i);
  1229. const endValue = vScale.parse(entry[1], i);
  1230. const min = Math.min(startValue, endValue);
  1231. const max = Math.max(startValue, endValue);
  1232. let barStart = min;
  1233. let barEnd = max;
  1234. if (Math.abs(min) > Math.abs(max)) {
  1235. barStart = max;
  1236. barEnd = min;
  1237. }
  1238. item[vScale.axis] = barEnd;
  1239. item._custom = {
  1240. barStart,
  1241. barEnd,
  1242. start: startValue,
  1243. end: endValue,
  1244. min,
  1245. max
  1246. };
  1247. }
  1248. function parseValue(entry, item, vScale, i) {
  1249. if (helpers_segment.isArray(entry)) {
  1250. parseFloatBar(entry, item, vScale, i);
  1251. } else {
  1252. item[vScale.axis] = vScale.parse(entry, i);
  1253. }
  1254. return item;
  1255. }
  1256. function parseArrayOrPrimitive(meta, data, start, count) {
  1257. const iScale = meta.iScale;
  1258. const vScale = meta.vScale;
  1259. const labels = iScale.getLabels();
  1260. const singleScale = iScale === vScale;
  1261. const parsed = [];
  1262. let i, ilen, item, entry;
  1263. for(i = start, ilen = start + count; i < ilen; ++i){
  1264. entry = data[i];
  1265. item = {};
  1266. item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
  1267. parsed.push(parseValue(entry, item, vScale, i));
  1268. }
  1269. return parsed;
  1270. }
  1271. function isFloatBar(custom) {
  1272. return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
  1273. }
  1274. function barSign(size, vScale, actualBase) {
  1275. if (size !== 0) {
  1276. return helpers_segment.sign(size);
  1277. }
  1278. return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);
  1279. }
  1280. function borderProps(properties) {
  1281. let reverse, start, end, top, bottom;
  1282. if (properties.horizontal) {
  1283. reverse = properties.base > properties.x;
  1284. start = 'left';
  1285. end = 'right';
  1286. } else {
  1287. reverse = properties.base < properties.y;
  1288. start = 'bottom';
  1289. end = 'top';
  1290. }
  1291. if (reverse) {
  1292. top = 'end';
  1293. bottom = 'start';
  1294. } else {
  1295. top = 'start';
  1296. bottom = 'end';
  1297. }
  1298. return {
  1299. start,
  1300. end,
  1301. reverse,
  1302. top,
  1303. bottom
  1304. };
  1305. }
  1306. function setBorderSkipped(properties, options, stack, index) {
  1307. let edge = options.borderSkipped;
  1308. const res = {};
  1309. if (!edge) {
  1310. properties.borderSkipped = res;
  1311. return;
  1312. }
  1313. if (edge === true) {
  1314. properties.borderSkipped = {
  1315. top: true,
  1316. right: true,
  1317. bottom: true,
  1318. left: true
  1319. };
  1320. return;
  1321. }
  1322. const { start , end , reverse , top , bottom } = borderProps(properties);
  1323. if (edge === 'middle' && stack) {
  1324. properties.enableBorderRadius = true;
  1325. if ((stack._top || 0) === index) {
  1326. edge = top;
  1327. } else if ((stack._bottom || 0) === index) {
  1328. edge = bottom;
  1329. } else {
  1330. res[parseEdge(bottom, start, end, reverse)] = true;
  1331. edge = top;
  1332. }
  1333. }
  1334. res[parseEdge(edge, start, end, reverse)] = true;
  1335. properties.borderSkipped = res;
  1336. }
  1337. function parseEdge(edge, a, b, reverse) {
  1338. if (reverse) {
  1339. edge = swap(edge, a, b);
  1340. edge = startEnd(edge, b, a);
  1341. } else {
  1342. edge = startEnd(edge, a, b);
  1343. }
  1344. return edge;
  1345. }
  1346. function swap(orig, v1, v2) {
  1347. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  1348. }
  1349. function startEnd(v, start, end) {
  1350. return v === 'start' ? start : v === 'end' ? end : v;
  1351. }
  1352. function setInflateAmount(properties, { inflateAmount }, ratio) {
  1353. properties.inflateAmount = inflateAmount === 'auto' ? ratio === 1 ? 0.33 : 0 : inflateAmount;
  1354. }
  1355. class BarController extends DatasetController {
  1356. static id = 'bar';
  1357. static defaults = {
  1358. datasetElementType: false,
  1359. dataElementType: 'bar',
  1360. categoryPercentage: 0.8,
  1361. barPercentage: 0.9,
  1362. grouped: true,
  1363. animations: {
  1364. numbers: {
  1365. type: 'number',
  1366. properties: [
  1367. 'x',
  1368. 'y',
  1369. 'base',
  1370. 'width',
  1371. 'height'
  1372. ]
  1373. }
  1374. }
  1375. };
  1376. static overrides = {
  1377. scales: {
  1378. _index_: {
  1379. type: 'category',
  1380. offset: true,
  1381. grid: {
  1382. offset: true
  1383. }
  1384. },
  1385. _value_: {
  1386. type: 'linear',
  1387. beginAtZero: true
  1388. }
  1389. }
  1390. };
  1391. parsePrimitiveData(meta, data, start, count) {
  1392. return parseArrayOrPrimitive(meta, data, start, count);
  1393. }
  1394. parseArrayData(meta, data, start, count) {
  1395. return parseArrayOrPrimitive(meta, data, start, count);
  1396. }
  1397. parseObjectData(meta, data, start, count) {
  1398. const { iScale , vScale } = meta;
  1399. const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing;
  1400. const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
  1401. const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
  1402. const parsed = [];
  1403. let i, ilen, item, obj;
  1404. for(i = start, ilen = start + count; i < ilen; ++i){
  1405. obj = data[i];
  1406. item = {};
  1407. item[iScale.axis] = iScale.parse(helpers_segment.resolveObjectKey(obj, iAxisKey), i);
  1408. parsed.push(parseValue(helpers_segment.resolveObjectKey(obj, vAxisKey), item, vScale, i));
  1409. }
  1410. return parsed;
  1411. }
  1412. updateRangeFromParsed(range, scale, parsed, stack) {
  1413. super.updateRangeFromParsed(range, scale, parsed, stack);
  1414. const custom = parsed._custom;
  1415. if (custom && scale === this._cachedMeta.vScale) {
  1416. range.min = Math.min(range.min, custom.min);
  1417. range.max = Math.max(range.max, custom.max);
  1418. }
  1419. }
  1420. getMaxOverflow() {
  1421. return 0;
  1422. }
  1423. getLabelAndValue(index) {
  1424. const meta = this._cachedMeta;
  1425. const { iScale , vScale } = meta;
  1426. const parsed = this.getParsed(index);
  1427. const custom = parsed._custom;
  1428. const value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]);
  1429. return {
  1430. label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
  1431. value
  1432. };
  1433. }
  1434. initialize() {
  1435. this.enableOptionSharing = true;
  1436. super.initialize();
  1437. const meta = this._cachedMeta;
  1438. meta.stack = this.getDataset().stack;
  1439. }
  1440. update(mode) {
  1441. const meta = this._cachedMeta;
  1442. this.updateElements(meta.data, 0, meta.data.length, mode);
  1443. }
  1444. updateElements(bars, start, count, mode) {
  1445. const reset = mode === 'reset';
  1446. const { index , _cachedMeta: { vScale } } = this;
  1447. const base = vScale.getBasePixel();
  1448. const horizontal = vScale.isHorizontal();
  1449. const ruler = this._getRuler();
  1450. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1451. for(let i = start; i < start + count; i++){
  1452. const parsed = this.getParsed(i);
  1453. const vpixels = reset || helpers_segment.isNullOrUndef(parsed[vScale.axis]) ? {
  1454. base,
  1455. head: base
  1456. } : this._calculateBarValuePixels(i);
  1457. const ipixels = this._calculateBarIndexPixels(i, ruler);
  1458. const stack = (parsed._stacks || {})[vScale.axis];
  1459. const properties = {
  1460. horizontal,
  1461. base: vpixels.base,
  1462. enableBorderRadius: !stack || isFloatBar(parsed._custom) || index === stack._top || index === stack._bottom,
  1463. x: horizontal ? vpixels.head : ipixels.center,
  1464. y: horizontal ? ipixels.center : vpixels.head,
  1465. height: horizontal ? ipixels.size : Math.abs(vpixels.size),
  1466. width: horizontal ? Math.abs(vpixels.size) : ipixels.size
  1467. };
  1468. if (includeOptions) {
  1469. properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);
  1470. }
  1471. const options = properties.options || bars[i].options;
  1472. setBorderSkipped(properties, options, stack, index);
  1473. setInflateAmount(properties, options, ruler.ratio);
  1474. this.updateElement(bars[i], i, properties, mode);
  1475. }
  1476. }
  1477. _getStacks(last, dataIndex) {
  1478. const { iScale } = this._cachedMeta;
  1479. const metasets = iScale.getMatchingVisibleMetas(this._type).filter((meta)=>meta.controller.options.grouped);
  1480. const stacked = iScale.options.stacked;
  1481. const stacks = [];
  1482. const skipNull = (meta)=>{
  1483. const parsed = meta.controller.getParsed(dataIndex);
  1484. const val = parsed && parsed[meta.vScale.axis];
  1485. if (helpers_segment.isNullOrUndef(val) || isNaN(val)) {
  1486. return true;
  1487. }
  1488. };
  1489. for (const meta of metasets){
  1490. if (dataIndex !== undefined && skipNull(meta)) {
  1491. continue;
  1492. }
  1493. if (stacked === false || stacks.indexOf(meta.stack) === -1 || stacked === undefined && meta.stack === undefined) {
  1494. stacks.push(meta.stack);
  1495. }
  1496. if (meta.index === last) {
  1497. break;
  1498. }
  1499. }
  1500. if (!stacks.length) {
  1501. stacks.push(undefined);
  1502. }
  1503. return stacks;
  1504. }
  1505. _getStackCount(index) {
  1506. return this._getStacks(undefined, index).length;
  1507. }
  1508. _getStackIndex(datasetIndex, name, dataIndex) {
  1509. const stacks = this._getStacks(datasetIndex, dataIndex);
  1510. const index = name !== undefined ? stacks.indexOf(name) : -1;
  1511. return index === -1 ? stacks.length - 1 : index;
  1512. }
  1513. _getRuler() {
  1514. const opts = this.options;
  1515. const meta = this._cachedMeta;
  1516. const iScale = meta.iScale;
  1517. const pixels = [];
  1518. let i, ilen;
  1519. for(i = 0, ilen = meta.data.length; i < ilen; ++i){
  1520. pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));
  1521. }
  1522. const barThickness = opts.barThickness;
  1523. const min = barThickness || computeMinSampleSize(meta);
  1524. return {
  1525. min,
  1526. pixels,
  1527. start: iScale._startPixel,
  1528. end: iScale._endPixel,
  1529. stackCount: this._getStackCount(),
  1530. scale: iScale,
  1531. grouped: opts.grouped,
  1532. ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
  1533. };
  1534. }
  1535. _calculateBarValuePixels(index) {
  1536. const { _cachedMeta: { vScale , _stacked , index: datasetIndex } , options: { base: baseValue , minBarLength } } = this;
  1537. const actualBase = baseValue || 0;
  1538. const parsed = this.getParsed(index);
  1539. const custom = parsed._custom;
  1540. const floating = isFloatBar(custom);
  1541. let value = parsed[vScale.axis];
  1542. let start = 0;
  1543. let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;
  1544. let head, size;
  1545. if (length !== value) {
  1546. start = length - value;
  1547. length = value;
  1548. }
  1549. if (floating) {
  1550. value = custom.barStart;
  1551. length = custom.barEnd - custom.barStart;
  1552. if (value !== 0 && helpers_segment.sign(value) !== helpers_segment.sign(custom.barEnd)) {
  1553. start = 0;
  1554. }
  1555. start += value;
  1556. }
  1557. const startValue = !helpers_segment.isNullOrUndef(baseValue) && !floating ? baseValue : start;
  1558. let base = vScale.getPixelForValue(startValue);
  1559. if (this.chart.getDataVisibility(index)) {
  1560. head = vScale.getPixelForValue(start + length);
  1561. } else {
  1562. head = base;
  1563. }
  1564. size = head - base;
  1565. if (Math.abs(size) < minBarLength) {
  1566. size = barSign(size, vScale, actualBase) * minBarLength;
  1567. if (value === actualBase) {
  1568. base -= size / 2;
  1569. }
  1570. const startPixel = vScale.getPixelForDecimal(0);
  1571. const endPixel = vScale.getPixelForDecimal(1);
  1572. const min = Math.min(startPixel, endPixel);
  1573. const max = Math.max(startPixel, endPixel);
  1574. base = Math.max(Math.min(base, max), min);
  1575. head = base + size;
  1576. if (_stacked && !floating) {
  1577. parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);
  1578. }
  1579. }
  1580. if (base === vScale.getPixelForValue(actualBase)) {
  1581. const halfGrid = helpers_segment.sign(size) * vScale.getLineWidthForValue(actualBase) / 2;
  1582. base += halfGrid;
  1583. size -= halfGrid;
  1584. }
  1585. return {
  1586. size,
  1587. base,
  1588. head,
  1589. center: head + size / 2
  1590. };
  1591. }
  1592. _calculateBarIndexPixels(index, ruler) {
  1593. const scale = ruler.scale;
  1594. const options = this.options;
  1595. const skipNull = options.skipNull;
  1596. const maxBarThickness = helpers_segment.valueOrDefault(options.maxBarThickness, Infinity);
  1597. let center, size;
  1598. if (ruler.grouped) {
  1599. const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;
  1600. const range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount) : computeFitCategoryTraits(index, ruler, options, stackCount);
  1601. const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined);
  1602. center = range.start + range.chunk * stackIndex + range.chunk / 2;
  1603. size = Math.min(maxBarThickness, range.chunk * range.ratio);
  1604. } else {
  1605. center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);
  1606. size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
  1607. }
  1608. return {
  1609. base: center - size / 2,
  1610. head: center + size / 2,
  1611. center,
  1612. size
  1613. };
  1614. }
  1615. draw() {
  1616. const meta = this._cachedMeta;
  1617. const vScale = meta.vScale;
  1618. const rects = meta.data;
  1619. const ilen = rects.length;
  1620. let i = 0;
  1621. for(; i < ilen; ++i){
  1622. if (this.getParsed(i)[vScale.axis] !== null) {
  1623. rects[i].draw(this._ctx);
  1624. }
  1625. }
  1626. }
  1627. }
  1628. class BubbleController extends DatasetController {
  1629. static id = 'bubble';
  1630. static defaults = {
  1631. datasetElementType: false,
  1632. dataElementType: 'point',
  1633. animations: {
  1634. numbers: {
  1635. type: 'number',
  1636. properties: [
  1637. 'x',
  1638. 'y',
  1639. 'borderWidth',
  1640. 'radius'
  1641. ]
  1642. }
  1643. }
  1644. };
  1645. static overrides = {
  1646. scales: {
  1647. x: {
  1648. type: 'linear'
  1649. },
  1650. y: {
  1651. type: 'linear'
  1652. }
  1653. }
  1654. };
  1655. initialize() {
  1656. this.enableOptionSharing = true;
  1657. super.initialize();
  1658. }
  1659. parsePrimitiveData(meta, data, start, count) {
  1660. const parsed = super.parsePrimitiveData(meta, data, start, count);
  1661. for(let i = 0; i < parsed.length; i++){
  1662. parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;
  1663. }
  1664. return parsed;
  1665. }
  1666. parseArrayData(meta, data, start, count) {
  1667. const parsed = super.parseArrayData(meta, data, start, count);
  1668. for(let i = 0; i < parsed.length; i++){
  1669. const item = data[start + i];
  1670. parsed[i]._custom = helpers_segment.valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);
  1671. }
  1672. return parsed;
  1673. }
  1674. parseObjectData(meta, data, start, count) {
  1675. const parsed = super.parseObjectData(meta, data, start, count);
  1676. for(let i = 0; i < parsed.length; i++){
  1677. const item = data[start + i];
  1678. parsed[i]._custom = helpers_segment.valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);
  1679. }
  1680. return parsed;
  1681. }
  1682. getMaxOverflow() {
  1683. const data = this._cachedMeta.data;
  1684. let max = 0;
  1685. for(let i = data.length - 1; i >= 0; --i){
  1686. max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
  1687. }
  1688. return max > 0 && max;
  1689. }
  1690. getLabelAndValue(index) {
  1691. const meta = this._cachedMeta;
  1692. const labels = this.chart.data.labels || [];
  1693. const { xScale , yScale } = meta;
  1694. const parsed = this.getParsed(index);
  1695. const x = xScale.getLabelForValue(parsed.x);
  1696. const y = yScale.getLabelForValue(parsed.y);
  1697. const r = parsed._custom;
  1698. return {
  1699. label: labels[index] || '',
  1700. value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
  1701. };
  1702. }
  1703. update(mode) {
  1704. const points = this._cachedMeta.data;
  1705. this.updateElements(points, 0, points.length, mode);
  1706. }
  1707. updateElements(points, start, count, mode) {
  1708. const reset = mode === 'reset';
  1709. const { iScale , vScale } = this._cachedMeta;
  1710. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1711. const iAxis = iScale.axis;
  1712. const vAxis = vScale.axis;
  1713. for(let i = start; i < start + count; i++){
  1714. const point = points[i];
  1715. const parsed = !reset && this.getParsed(i);
  1716. const properties = {};
  1717. const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);
  1718. const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);
  1719. properties.skip = isNaN(iPixel) || isNaN(vPixel);
  1720. if (includeOptions) {
  1721. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  1722. if (reset) {
  1723. properties.options.radius = 0;
  1724. }
  1725. }
  1726. this.updateElement(point, i, properties, mode);
  1727. }
  1728. }
  1729. resolveDataElementOptions(index, mode) {
  1730. const parsed = this.getParsed(index);
  1731. let values = super.resolveDataElementOptions(index, mode);
  1732. if (values.$shared) {
  1733. values = Object.assign({}, values, {
  1734. $shared: false
  1735. });
  1736. }
  1737. const radius = values.radius;
  1738. if (mode !== 'active') {
  1739. values.radius = 0;
  1740. }
  1741. values.radius += helpers_segment.valueOrDefault(parsed && parsed._custom, radius);
  1742. return values;
  1743. }
  1744. }
  1745. function getRatioAndOffset(rotation, circumference, cutout) {
  1746. let ratioX = 1;
  1747. let ratioY = 1;
  1748. let offsetX = 0;
  1749. let offsetY = 0;
  1750. if (circumference < helpers_segment.TAU) {
  1751. const startAngle = rotation;
  1752. const endAngle = startAngle + circumference;
  1753. const startX = Math.cos(startAngle);
  1754. const startY = Math.sin(startAngle);
  1755. const endX = Math.cos(endAngle);
  1756. const endY = Math.sin(endAngle);
  1757. const calcMax = (angle, a, b)=>helpers_segment._angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);
  1758. const calcMin = (angle, a, b)=>helpers_segment._angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);
  1759. const maxX = calcMax(0, startX, endX);
  1760. const maxY = calcMax(helpers_segment.HALF_PI, startY, endY);
  1761. const minX = calcMin(helpers_segment.PI, startX, endX);
  1762. const minY = calcMin(helpers_segment.PI + helpers_segment.HALF_PI, startY, endY);
  1763. ratioX = (maxX - minX) / 2;
  1764. ratioY = (maxY - minY) / 2;
  1765. offsetX = -(maxX + minX) / 2;
  1766. offsetY = -(maxY + minY) / 2;
  1767. }
  1768. return {
  1769. ratioX,
  1770. ratioY,
  1771. offsetX,
  1772. offsetY
  1773. };
  1774. }
  1775. class DoughnutController extends DatasetController {
  1776. static id = 'doughnut';
  1777. static defaults = {
  1778. datasetElementType: false,
  1779. dataElementType: 'arc',
  1780. animation: {
  1781. animateRotate: true,
  1782. animateScale: false
  1783. },
  1784. animations: {
  1785. numbers: {
  1786. type: 'number',
  1787. properties: [
  1788. 'circumference',
  1789. 'endAngle',
  1790. 'innerRadius',
  1791. 'outerRadius',
  1792. 'startAngle',
  1793. 'x',
  1794. 'y',
  1795. 'offset',
  1796. 'borderWidth',
  1797. 'spacing'
  1798. ]
  1799. }
  1800. },
  1801. cutout: '50%',
  1802. rotation: 0,
  1803. circumference: 360,
  1804. radius: '100%',
  1805. spacing: 0,
  1806. indexAxis: 'r'
  1807. };
  1808. static descriptors = {
  1809. _scriptable: (name)=>name !== 'spacing',
  1810. _indexable: (name)=>name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash')
  1811. };
  1812. static overrides = {
  1813. aspectRatio: 1,
  1814. plugins: {
  1815. legend: {
  1816. labels: {
  1817. generateLabels (chart) {
  1818. const data = chart.data;
  1819. if (data.labels.length && data.datasets.length) {
  1820. const { labels: { pointStyle , color } } = chart.legend.options;
  1821. return data.labels.map((label, i)=>{
  1822. const meta = chart.getDatasetMeta(0);
  1823. const style = meta.controller.getStyle(i);
  1824. return {
  1825. text: label,
  1826. fillStyle: style.backgroundColor,
  1827. strokeStyle: style.borderColor,
  1828. fontColor: color,
  1829. lineWidth: style.borderWidth,
  1830. pointStyle: pointStyle,
  1831. hidden: !chart.getDataVisibility(i),
  1832. index: i
  1833. };
  1834. });
  1835. }
  1836. return [];
  1837. }
  1838. },
  1839. onClick (e, legendItem, legend) {
  1840. legend.chart.toggleDataVisibility(legendItem.index);
  1841. legend.chart.update();
  1842. }
  1843. }
  1844. }
  1845. };
  1846. constructor(chart, datasetIndex){
  1847. super(chart, datasetIndex);
  1848. this.enableOptionSharing = true;
  1849. this.innerRadius = undefined;
  1850. this.outerRadius = undefined;
  1851. this.offsetX = undefined;
  1852. this.offsetY = undefined;
  1853. }
  1854. linkScales() {}
  1855. parse(start, count) {
  1856. const data = this.getDataset().data;
  1857. const meta = this._cachedMeta;
  1858. if (this._parsing === false) {
  1859. meta._parsed = data;
  1860. } else {
  1861. let getter = (i)=>+data[i];
  1862. if (helpers_segment.isObject(data[start])) {
  1863. const { key ='value' } = this._parsing;
  1864. getter = (i)=>+helpers_segment.resolveObjectKey(data[i], key);
  1865. }
  1866. let i, ilen;
  1867. for(i = start, ilen = start + count; i < ilen; ++i){
  1868. meta._parsed[i] = getter(i);
  1869. }
  1870. }
  1871. }
  1872. _getRotation() {
  1873. return helpers_segment.toRadians(this.options.rotation - 90);
  1874. }
  1875. _getCircumference() {
  1876. return helpers_segment.toRadians(this.options.circumference);
  1877. }
  1878. _getRotationExtents() {
  1879. let min = helpers_segment.TAU;
  1880. let max = -helpers_segment.TAU;
  1881. for(let i = 0; i < this.chart.data.datasets.length; ++i){
  1882. if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {
  1883. const controller = this.chart.getDatasetMeta(i).controller;
  1884. const rotation = controller._getRotation();
  1885. const circumference = controller._getCircumference();
  1886. min = Math.min(min, rotation);
  1887. max = Math.max(max, rotation + circumference);
  1888. }
  1889. }
  1890. return {
  1891. rotation: min,
  1892. circumference: max - min
  1893. };
  1894. }
  1895. update(mode) {
  1896. const chart = this.chart;
  1897. const { chartArea } = chart;
  1898. const meta = this._cachedMeta;
  1899. const arcs = meta.data;
  1900. const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;
  1901. const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
  1902. const cutout = Math.min(helpers_segment.toPercentage(this.options.cutout, maxSize), 1);
  1903. const chartWeight = this._getRingWeight(this.index);
  1904. const { circumference , rotation } = this._getRotationExtents();
  1905. const { ratioX , ratioY , offsetX , offsetY } = getRatioAndOffset(rotation, circumference, cutout);
  1906. const maxWidth = (chartArea.width - spacing) / ratioX;
  1907. const maxHeight = (chartArea.height - spacing) / ratioY;
  1908. const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  1909. const outerRadius = helpers_segment.toDimension(this.options.radius, maxRadius);
  1910. const innerRadius = Math.max(outerRadius * cutout, 0);
  1911. const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();
  1912. this.offsetX = offsetX * outerRadius;
  1913. this.offsetY = offsetY * outerRadius;
  1914. meta.total = this.calculateTotal();
  1915. this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);
  1916. this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);
  1917. this.updateElements(arcs, 0, arcs.length, mode);
  1918. }
  1919. _circumference(i, reset) {
  1920. const opts = this.options;
  1921. const meta = this._cachedMeta;
  1922. const circumference = this._getCircumference();
  1923. if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {
  1924. return 0;
  1925. }
  1926. return this.calculateCircumference(meta._parsed[i] * circumference / helpers_segment.TAU);
  1927. }
  1928. updateElements(arcs, start, count, mode) {
  1929. const reset = mode === 'reset';
  1930. const chart = this.chart;
  1931. const chartArea = chart.chartArea;
  1932. const opts = chart.options;
  1933. const animationOpts = opts.animation;
  1934. const centerX = (chartArea.left + chartArea.right) / 2;
  1935. const centerY = (chartArea.top + chartArea.bottom) / 2;
  1936. const animateScale = reset && animationOpts.animateScale;
  1937. const innerRadius = animateScale ? 0 : this.innerRadius;
  1938. const outerRadius = animateScale ? 0 : this.outerRadius;
  1939. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1940. let startAngle = this._getRotation();
  1941. let i;
  1942. for(i = 0; i < start; ++i){
  1943. startAngle += this._circumference(i, reset);
  1944. }
  1945. for(i = start; i < start + count; ++i){
  1946. const circumference = this._circumference(i, reset);
  1947. const arc = arcs[i];
  1948. const properties = {
  1949. x: centerX + this.offsetX,
  1950. y: centerY + this.offsetY,
  1951. startAngle,
  1952. endAngle: startAngle + circumference,
  1953. circumference,
  1954. outerRadius,
  1955. innerRadius
  1956. };
  1957. if (includeOptions) {
  1958. properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);
  1959. }
  1960. startAngle += circumference;
  1961. this.updateElement(arc, i, properties, mode);
  1962. }
  1963. }
  1964. calculateTotal() {
  1965. const meta = this._cachedMeta;
  1966. const metaData = meta.data;
  1967. let total = 0;
  1968. let i;
  1969. for(i = 0; i < metaData.length; i++){
  1970. const value = meta._parsed[i];
  1971. if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {
  1972. total += Math.abs(value);
  1973. }
  1974. }
  1975. return total;
  1976. }
  1977. calculateCircumference(value) {
  1978. const total = this._cachedMeta.total;
  1979. if (total > 0 && !isNaN(value)) {
  1980. return helpers_segment.TAU * (Math.abs(value) / total);
  1981. }
  1982. return 0;
  1983. }
  1984. getLabelAndValue(index) {
  1985. const meta = this._cachedMeta;
  1986. const chart = this.chart;
  1987. const labels = chart.data.labels || [];
  1988. const value = helpers_segment.formatNumber(meta._parsed[index], chart.options.locale);
  1989. return {
  1990. label: labels[index] || '',
  1991. value
  1992. };
  1993. }
  1994. getMaxBorderWidth(arcs) {
  1995. let max = 0;
  1996. const chart = this.chart;
  1997. let i, ilen, meta, controller, options;
  1998. if (!arcs) {
  1999. for(i = 0, ilen = chart.data.datasets.length; i < ilen; ++i){
  2000. if (chart.isDatasetVisible(i)) {
  2001. meta = chart.getDatasetMeta(i);
  2002. arcs = meta.data;
  2003. controller = meta.controller;
  2004. break;
  2005. }
  2006. }
  2007. }
  2008. if (!arcs) {
  2009. return 0;
  2010. }
  2011. for(i = 0, ilen = arcs.length; i < ilen; ++i){
  2012. options = controller.resolveDataElementOptions(i);
  2013. if (options.borderAlign !== 'inner') {
  2014. max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
  2015. }
  2016. }
  2017. return max;
  2018. }
  2019. getMaxOffset(arcs) {
  2020. let max = 0;
  2021. for(let i = 0, ilen = arcs.length; i < ilen; ++i){
  2022. const options = this.resolveDataElementOptions(i);
  2023. max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
  2024. }
  2025. return max;
  2026. }
  2027. _getRingWeightOffset(datasetIndex) {
  2028. let ringWeightOffset = 0;
  2029. for(let i = 0; i < datasetIndex; ++i){
  2030. if (this.chart.isDatasetVisible(i)) {
  2031. ringWeightOffset += this._getRingWeight(i);
  2032. }
  2033. }
  2034. return ringWeightOffset;
  2035. }
  2036. _getRingWeight(datasetIndex) {
  2037. return Math.max(helpers_segment.valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
  2038. }
  2039. _getVisibleDatasetWeightTotal() {
  2040. return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
  2041. }
  2042. }
  2043. class LineController extends DatasetController {
  2044. static id = 'line';
  2045. static defaults = {
  2046. datasetElementType: 'line',
  2047. dataElementType: 'point',
  2048. showLine: true,
  2049. spanGaps: false
  2050. };
  2051. static overrides = {
  2052. scales: {
  2053. _index_: {
  2054. type: 'category'
  2055. },
  2056. _value_: {
  2057. type: 'linear'
  2058. }
  2059. }
  2060. };
  2061. initialize() {
  2062. this.enableOptionSharing = true;
  2063. this.supportsDecimation = true;
  2064. super.initialize();
  2065. }
  2066. update(mode) {
  2067. const meta = this._cachedMeta;
  2068. const { dataset: line , data: points = [] , _dataset } = meta;
  2069. const animationsDisabled = this.chart._animationsDisabled;
  2070. let { start , count } = helpers_segment._getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  2071. this._drawStart = start;
  2072. this._drawCount = count;
  2073. if (helpers_segment._scaleRangesChanged(meta)) {
  2074. start = 0;
  2075. count = points.length;
  2076. }
  2077. line._chart = this.chart;
  2078. line._datasetIndex = this.index;
  2079. line._decimated = !!_dataset._decimated;
  2080. line.points = points;
  2081. const options = this.resolveDatasetElementOptions(mode);
  2082. if (!this.options.showLine) {
  2083. options.borderWidth = 0;
  2084. }
  2085. options.segment = this.options.segment;
  2086. this.updateElement(line, undefined, {
  2087. animated: !animationsDisabled,
  2088. options
  2089. }, mode);
  2090. this.updateElements(points, start, count, mode);
  2091. }
  2092. updateElements(points, start, count, mode) {
  2093. const reset = mode === 'reset';
  2094. const { iScale , vScale , _stacked , _dataset } = this._cachedMeta;
  2095. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  2096. const iAxis = iScale.axis;
  2097. const vAxis = vScale.axis;
  2098. const { spanGaps , segment } = this.options;
  2099. const maxGapLength = helpers_segment.isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  2100. const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
  2101. const end = start + count;
  2102. const pointsCount = points.length;
  2103. let prevParsed = start > 0 && this.getParsed(start - 1);
  2104. for(let i = 0; i < pointsCount; ++i){
  2105. const point = points[i];
  2106. const properties = directUpdate ? point : {};
  2107. if (i < start || i >= end) {
  2108. properties.skip = true;
  2109. continue;
  2110. }
  2111. const parsed = this.getParsed(i);
  2112. const nullData = helpers_segment.isNullOrUndef(parsed[vAxis]);
  2113. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  2114. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  2115. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  2116. properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  2117. if (segment) {
  2118. properties.parsed = parsed;
  2119. properties.raw = _dataset.data[i];
  2120. }
  2121. if (includeOptions) {
  2122. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2123. }
  2124. if (!directUpdate) {
  2125. this.updateElement(point, i, properties, mode);
  2126. }
  2127. prevParsed = parsed;
  2128. }
  2129. }
  2130. getMaxOverflow() {
  2131. const meta = this._cachedMeta;
  2132. const dataset = meta.dataset;
  2133. const border = dataset.options && dataset.options.borderWidth || 0;
  2134. const data = meta.data || [];
  2135. if (!data.length) {
  2136. return border;
  2137. }
  2138. const firstPoint = data[0].size(this.resolveDataElementOptions(0));
  2139. const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
  2140. return Math.max(border, firstPoint, lastPoint) / 2;
  2141. }
  2142. draw() {
  2143. const meta = this._cachedMeta;
  2144. meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);
  2145. super.draw();
  2146. }
  2147. }
  2148. class PolarAreaController extends DatasetController {
  2149. static id = 'polarArea';
  2150. static defaults = {
  2151. dataElementType: 'arc',
  2152. animation: {
  2153. animateRotate: true,
  2154. animateScale: true
  2155. },
  2156. animations: {
  2157. numbers: {
  2158. type: 'number',
  2159. properties: [
  2160. 'x',
  2161. 'y',
  2162. 'startAngle',
  2163. 'endAngle',
  2164. 'innerRadius',
  2165. 'outerRadius'
  2166. ]
  2167. }
  2168. },
  2169. indexAxis: 'r',
  2170. startAngle: 0
  2171. };
  2172. static overrides = {
  2173. aspectRatio: 1,
  2174. plugins: {
  2175. legend: {
  2176. labels: {
  2177. generateLabels (chart) {
  2178. const data = chart.data;
  2179. if (data.labels.length && data.datasets.length) {
  2180. const { labels: { pointStyle , color } } = chart.legend.options;
  2181. return data.labels.map((label, i)=>{
  2182. const meta = chart.getDatasetMeta(0);
  2183. const style = meta.controller.getStyle(i);
  2184. return {
  2185. text: label,
  2186. fillStyle: style.backgroundColor,
  2187. strokeStyle: style.borderColor,
  2188. fontColor: color,
  2189. lineWidth: style.borderWidth,
  2190. pointStyle: pointStyle,
  2191. hidden: !chart.getDataVisibility(i),
  2192. index: i
  2193. };
  2194. });
  2195. }
  2196. return [];
  2197. }
  2198. },
  2199. onClick (e, legendItem, legend) {
  2200. legend.chart.toggleDataVisibility(legendItem.index);
  2201. legend.chart.update();
  2202. }
  2203. }
  2204. },
  2205. scales: {
  2206. r: {
  2207. type: 'radialLinear',
  2208. angleLines: {
  2209. display: false
  2210. },
  2211. beginAtZero: true,
  2212. grid: {
  2213. circular: true
  2214. },
  2215. pointLabels: {
  2216. display: false
  2217. },
  2218. startAngle: 0
  2219. }
  2220. }
  2221. };
  2222. constructor(chart, datasetIndex){
  2223. super(chart, datasetIndex);
  2224. this.innerRadius = undefined;
  2225. this.outerRadius = undefined;
  2226. }
  2227. getLabelAndValue(index) {
  2228. const meta = this._cachedMeta;
  2229. const chart = this.chart;
  2230. const labels = chart.data.labels || [];
  2231. const value = helpers_segment.formatNumber(meta._parsed[index].r, chart.options.locale);
  2232. return {
  2233. label: labels[index] || '',
  2234. value
  2235. };
  2236. }
  2237. parseObjectData(meta, data, start, count) {
  2238. return helpers_segment._parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2239. }
  2240. update(mode) {
  2241. const arcs = this._cachedMeta.data;
  2242. this._updateRadius();
  2243. this.updateElements(arcs, 0, arcs.length, mode);
  2244. }
  2245. getMinMax() {
  2246. const meta = this._cachedMeta;
  2247. const range = {
  2248. min: Number.POSITIVE_INFINITY,
  2249. max: Number.NEGATIVE_INFINITY
  2250. };
  2251. meta.data.forEach((element, index)=>{
  2252. const parsed = this.getParsed(index).r;
  2253. if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {
  2254. if (parsed < range.min) {
  2255. range.min = parsed;
  2256. }
  2257. if (parsed > range.max) {
  2258. range.max = parsed;
  2259. }
  2260. }
  2261. });
  2262. return range;
  2263. }
  2264. _updateRadius() {
  2265. const chart = this.chart;
  2266. const chartArea = chart.chartArea;
  2267. const opts = chart.options;
  2268. const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  2269. const outerRadius = Math.max(minSize / 2, 0);
  2270. const innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0);
  2271. const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
  2272. this.outerRadius = outerRadius - radiusLength * this.index;
  2273. this.innerRadius = this.outerRadius - radiusLength;
  2274. }
  2275. updateElements(arcs, start, count, mode) {
  2276. const reset = mode === 'reset';
  2277. const chart = this.chart;
  2278. const opts = chart.options;
  2279. const animationOpts = opts.animation;
  2280. const scale = this._cachedMeta.rScale;
  2281. const centerX = scale.xCenter;
  2282. const centerY = scale.yCenter;
  2283. const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * helpers_segment.PI;
  2284. let angle = datasetStartAngle;
  2285. let i;
  2286. const defaultAngle = 360 / this.countVisibleElements();
  2287. for(i = 0; i < start; ++i){
  2288. angle += this._computeAngle(i, mode, defaultAngle);
  2289. }
  2290. for(i = start; i < start + count; i++){
  2291. const arc = arcs[i];
  2292. let startAngle = angle;
  2293. let endAngle = angle + this._computeAngle(i, mode, defaultAngle);
  2294. let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;
  2295. angle = endAngle;
  2296. if (reset) {
  2297. if (animationOpts.animateScale) {
  2298. outerRadius = 0;
  2299. }
  2300. if (animationOpts.animateRotate) {
  2301. startAngle = endAngle = datasetStartAngle;
  2302. }
  2303. }
  2304. const properties = {
  2305. x: centerX,
  2306. y: centerY,
  2307. innerRadius: 0,
  2308. outerRadius,
  2309. startAngle,
  2310. endAngle,
  2311. options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)
  2312. };
  2313. this.updateElement(arc, i, properties, mode);
  2314. }
  2315. }
  2316. countVisibleElements() {
  2317. const meta = this._cachedMeta;
  2318. let count = 0;
  2319. meta.data.forEach((element, index)=>{
  2320. if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {
  2321. count++;
  2322. }
  2323. });
  2324. return count;
  2325. }
  2326. _computeAngle(index, mode, defaultAngle) {
  2327. return this.chart.getDataVisibility(index) ? helpers_segment.toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0;
  2328. }
  2329. }
  2330. class PieController extends DoughnutController {
  2331. static id = 'pie';
  2332. static defaults = {
  2333. cutout: 0,
  2334. rotation: 0,
  2335. circumference: 360,
  2336. radius: '100%'
  2337. };
  2338. }
  2339. class RadarController extends DatasetController {
  2340. static id = 'radar';
  2341. static defaults = {
  2342. datasetElementType: 'line',
  2343. dataElementType: 'point',
  2344. indexAxis: 'r',
  2345. showLine: true,
  2346. elements: {
  2347. line: {
  2348. fill: 'start'
  2349. }
  2350. }
  2351. };
  2352. static overrides = {
  2353. aspectRatio: 1,
  2354. scales: {
  2355. r: {
  2356. type: 'radialLinear'
  2357. }
  2358. }
  2359. };
  2360. getLabelAndValue(index) {
  2361. const vScale = this._cachedMeta.vScale;
  2362. const parsed = this.getParsed(index);
  2363. return {
  2364. label: vScale.getLabels()[index],
  2365. value: '' + vScale.getLabelForValue(parsed[vScale.axis])
  2366. };
  2367. }
  2368. parseObjectData(meta, data, start, count) {
  2369. return helpers_segment._parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2370. }
  2371. update(mode) {
  2372. const meta = this._cachedMeta;
  2373. const line = meta.dataset;
  2374. const points = meta.data || [];
  2375. const labels = meta.iScale.getLabels();
  2376. line.points = points;
  2377. if (mode !== 'resize') {
  2378. const options = this.resolveDatasetElementOptions(mode);
  2379. if (!this.options.showLine) {
  2380. options.borderWidth = 0;
  2381. }
  2382. const properties = {
  2383. _loop: true,
  2384. _fullLoop: labels.length === points.length,
  2385. options
  2386. };
  2387. this.updateElement(line, undefined, properties, mode);
  2388. }
  2389. this.updateElements(points, 0, points.length, mode);
  2390. }
  2391. updateElements(points, start, count, mode) {
  2392. const scale = this._cachedMeta.rScale;
  2393. const reset = mode === 'reset';
  2394. for(let i = start; i < start + count; i++){
  2395. const point = points[i];
  2396. const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2397. const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);
  2398. const x = reset ? scale.xCenter : pointPosition.x;
  2399. const y = reset ? scale.yCenter : pointPosition.y;
  2400. const properties = {
  2401. x,
  2402. y,
  2403. angle: pointPosition.angle,
  2404. skip: isNaN(x) || isNaN(y),
  2405. options
  2406. };
  2407. this.updateElement(point, i, properties, mode);
  2408. }
  2409. }
  2410. }
  2411. class ScatterController extends DatasetController {
  2412. static id = 'scatter';
  2413. static defaults = {
  2414. datasetElementType: false,
  2415. dataElementType: 'point',
  2416. showLine: false,
  2417. fill: false
  2418. };
  2419. static overrides = {
  2420. interaction: {
  2421. mode: 'point'
  2422. },
  2423. scales: {
  2424. x: {
  2425. type: 'linear'
  2426. },
  2427. y: {
  2428. type: 'linear'
  2429. }
  2430. }
  2431. };
  2432. getLabelAndValue(index) {
  2433. const meta = this._cachedMeta;
  2434. const labels = this.chart.data.labels || [];
  2435. const { xScale , yScale } = meta;
  2436. const parsed = this.getParsed(index);
  2437. const x = xScale.getLabelForValue(parsed.x);
  2438. const y = yScale.getLabelForValue(parsed.y);
  2439. return {
  2440. label: labels[index] || '',
  2441. value: '(' + x + ', ' + y + ')'
  2442. };
  2443. }
  2444. update(mode) {
  2445. const meta = this._cachedMeta;
  2446. const { data: points = [] } = meta;
  2447. const animationsDisabled = this.chart._animationsDisabled;
  2448. let { start , count } = helpers_segment._getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  2449. this._drawStart = start;
  2450. this._drawCount = count;
  2451. if (helpers_segment._scaleRangesChanged(meta)) {
  2452. start = 0;
  2453. count = points.length;
  2454. }
  2455. if (this.options.showLine) {
  2456. if (!this.datasetElementType) {
  2457. this.addElements();
  2458. }
  2459. const { dataset: line , _dataset } = meta;
  2460. line._chart = this.chart;
  2461. line._datasetIndex = this.index;
  2462. line._decimated = !!_dataset._decimated;
  2463. line.points = points;
  2464. const options = this.resolveDatasetElementOptions(mode);
  2465. options.segment = this.options.segment;
  2466. this.updateElement(line, undefined, {
  2467. animated: !animationsDisabled,
  2468. options
  2469. }, mode);
  2470. } else if (this.datasetElementType) {
  2471. delete meta.dataset;
  2472. this.datasetElementType = false;
  2473. }
  2474. this.updateElements(points, start, count, mode);
  2475. }
  2476. addElements() {
  2477. const { showLine } = this.options;
  2478. if (!this.datasetElementType && showLine) {
  2479. this.datasetElementType = this.chart.registry.getElement('line');
  2480. }
  2481. super.addElements();
  2482. }
  2483. updateElements(points, start, count, mode) {
  2484. const reset = mode === 'reset';
  2485. const { iScale , vScale , _stacked , _dataset } = this._cachedMeta;
  2486. const firstOpts = this.resolveDataElementOptions(start, mode);
  2487. const sharedOptions = this.getSharedOptions(firstOpts);
  2488. const includeOptions = this.includeOptions(mode, sharedOptions);
  2489. const iAxis = iScale.axis;
  2490. const vAxis = vScale.axis;
  2491. const { spanGaps , segment } = this.options;
  2492. const maxGapLength = helpers_segment.isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  2493. const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
  2494. let prevParsed = start > 0 && this.getParsed(start - 1);
  2495. for(let i = start; i < start + count; ++i){
  2496. const point = points[i];
  2497. const parsed = this.getParsed(i);
  2498. const properties = directUpdate ? point : {};
  2499. const nullData = helpers_segment.isNullOrUndef(parsed[vAxis]);
  2500. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  2501. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  2502. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  2503. properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  2504. if (segment) {
  2505. properties.parsed = parsed;
  2506. properties.raw = _dataset.data[i];
  2507. }
  2508. if (includeOptions) {
  2509. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2510. }
  2511. if (!directUpdate) {
  2512. this.updateElement(point, i, properties, mode);
  2513. }
  2514. prevParsed = parsed;
  2515. }
  2516. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  2517. }
  2518. getMaxOverflow() {
  2519. const meta = this._cachedMeta;
  2520. const data = meta.data || [];
  2521. if (!this.options.showLine) {
  2522. let max = 0;
  2523. for(let i = data.length - 1; i >= 0; --i){
  2524. max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
  2525. }
  2526. return max > 0 && max;
  2527. }
  2528. const dataset = meta.dataset;
  2529. const border = dataset.options && dataset.options.borderWidth || 0;
  2530. if (!data.length) {
  2531. return border;
  2532. }
  2533. const firstPoint = data[0].size(this.resolveDataElementOptions(0));
  2534. const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
  2535. return Math.max(border, firstPoint, lastPoint) / 2;
  2536. }
  2537. }
  2538. var controllers = /*#__PURE__*/Object.freeze({
  2539. __proto__: null,
  2540. BarController: BarController,
  2541. BubbleController: BubbleController,
  2542. DoughnutController: DoughnutController,
  2543. LineController: LineController,
  2544. PieController: PieController,
  2545. PolarAreaController: PolarAreaController,
  2546. RadarController: RadarController,
  2547. ScatterController: ScatterController
  2548. });
  2549. /**
  2550. * @namespace Chart._adapters
  2551. * @since 2.8.0
  2552. * @private
  2553. */ function abstract() {
  2554. throw new Error('This method is not implemented: Check that a complete date adapter is provided.');
  2555. }
  2556. /**
  2557. * Date adapter (current used by the time scale)
  2558. * @namespace Chart._adapters._date
  2559. * @memberof Chart._adapters
  2560. * @private
  2561. */ class DateAdapterBase {
  2562. /**
  2563. * Override default date adapter methods.
  2564. * Accepts type parameter to define options type.
  2565. * @example
  2566. * Chart._adapters._date.override<{myAdapterOption: string}>({
  2567. * init() {
  2568. * console.log(this.options.myAdapterOption);
  2569. * }
  2570. * })
  2571. */ static override(members) {
  2572. Object.assign(DateAdapterBase.prototype, members);
  2573. }
  2574. options;
  2575. constructor(options){
  2576. this.options = options || {};
  2577. }
  2578. // eslint-disable-next-line @typescript-eslint/no-empty-function
  2579. init() {}
  2580. formats() {
  2581. return abstract();
  2582. }
  2583. parse() {
  2584. return abstract();
  2585. }
  2586. format() {
  2587. return abstract();
  2588. }
  2589. add() {
  2590. return abstract();
  2591. }
  2592. diff() {
  2593. return abstract();
  2594. }
  2595. startOf() {
  2596. return abstract();
  2597. }
  2598. endOf() {
  2599. return abstract();
  2600. }
  2601. }
  2602. var adapters = {
  2603. _date: DateAdapterBase
  2604. };
  2605. function binarySearch(metaset, axis, value, intersect) {
  2606. const { controller , data , _sorted } = metaset;
  2607. const iScale = controller._cachedMeta.iScale;
  2608. if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {
  2609. const lookupMethod = iScale._reversePixels ? helpers_segment._rlookupByKey : helpers_segment._lookupByKey;
  2610. if (!intersect) {
  2611. return lookupMethod(data, axis, value);
  2612. } else if (controller._sharedOptions) {
  2613. const el = data[0];
  2614. const range = typeof el.getRange === 'function' && el.getRange(axis);
  2615. if (range) {
  2616. const start = lookupMethod(data, axis, value - range);
  2617. const end = lookupMethod(data, axis, value + range);
  2618. return {
  2619. lo: start.lo,
  2620. hi: end.hi
  2621. };
  2622. }
  2623. }
  2624. }
  2625. return {
  2626. lo: 0,
  2627. hi: data.length - 1
  2628. };
  2629. }
  2630. function evaluateInteractionItems(chart, axis, position, handler, intersect) {
  2631. const metasets = chart.getSortedVisibleDatasetMetas();
  2632. const value = position[axis];
  2633. for(let i = 0, ilen = metasets.length; i < ilen; ++i){
  2634. const { index , data } = metasets[i];
  2635. const { lo , hi } = binarySearch(metasets[i], axis, value, intersect);
  2636. for(let j = lo; j <= hi; ++j){
  2637. const element = data[j];
  2638. if (!element.skip) {
  2639. handler(element, index, j);
  2640. }
  2641. }
  2642. }
  2643. }
  2644. function getDistanceMetricForAxis(axis) {
  2645. const useX = axis.indexOf('x') !== -1;
  2646. const useY = axis.indexOf('y') !== -1;
  2647. return function(pt1, pt2) {
  2648. const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  2649. const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  2650. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  2651. };
  2652. }
  2653. function getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {
  2654. const items = [];
  2655. if (!includeInvisible && !chart.isPointInArea(position)) {
  2656. return items;
  2657. }
  2658. const evaluationFunc = function(element, datasetIndex, index) {
  2659. if (!includeInvisible && !helpers_segment._isPointInArea(element, chart.chartArea, 0)) {
  2660. return;
  2661. }
  2662. if (element.inRange(position.x, position.y, useFinalPosition)) {
  2663. items.push({
  2664. element,
  2665. datasetIndex,
  2666. index
  2667. });
  2668. }
  2669. };
  2670. evaluateInteractionItems(chart, axis, position, evaluationFunc, true);
  2671. return items;
  2672. }
  2673. function getNearestRadialItems(chart, position, axis, useFinalPosition) {
  2674. let items = [];
  2675. function evaluationFunc(element, datasetIndex, index) {
  2676. const { startAngle , endAngle } = element.getProps([
  2677. 'startAngle',
  2678. 'endAngle'
  2679. ], useFinalPosition);
  2680. const { angle } = helpers_segment.getAngleFromPoint(element, {
  2681. x: position.x,
  2682. y: position.y
  2683. });
  2684. if (helpers_segment._angleBetween(angle, startAngle, endAngle)) {
  2685. items.push({
  2686. element,
  2687. datasetIndex,
  2688. index
  2689. });
  2690. }
  2691. }
  2692. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2693. return items;
  2694. }
  2695. function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
  2696. let items = [];
  2697. const distanceMetric = getDistanceMetricForAxis(axis);
  2698. let minDistance = Number.POSITIVE_INFINITY;
  2699. function evaluationFunc(element, datasetIndex, index) {
  2700. const inRange = element.inRange(position.x, position.y, useFinalPosition);
  2701. if (intersect && !inRange) {
  2702. return;
  2703. }
  2704. const center = element.getCenterPoint(useFinalPosition);
  2705. const pointInArea = !!includeInvisible || chart.isPointInArea(center);
  2706. if (!pointInArea && !inRange) {
  2707. return;
  2708. }
  2709. const distance = distanceMetric(position, center);
  2710. if (distance < minDistance) {
  2711. items = [
  2712. {
  2713. element,
  2714. datasetIndex,
  2715. index
  2716. }
  2717. ];
  2718. minDistance = distance;
  2719. } else if (distance === minDistance) {
  2720. items.push({
  2721. element,
  2722. datasetIndex,
  2723. index
  2724. });
  2725. }
  2726. }
  2727. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2728. return items;
  2729. }
  2730. function getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
  2731. if (!includeInvisible && !chart.isPointInArea(position)) {
  2732. return [];
  2733. }
  2734. return axis === 'r' && !intersect ? getNearestRadialItems(chart, position, axis, useFinalPosition) : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);
  2735. }
  2736. function getAxisItems(chart, position, axis, intersect, useFinalPosition) {
  2737. const items = [];
  2738. const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
  2739. let intersectsItem = false;
  2740. evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index)=>{
  2741. if (element[rangeMethod](position[axis], useFinalPosition)) {
  2742. items.push({
  2743. element,
  2744. datasetIndex,
  2745. index
  2746. });
  2747. intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);
  2748. }
  2749. });
  2750. if (intersect && !intersectsItem) {
  2751. return [];
  2752. }
  2753. return items;
  2754. }
  2755. var Interaction = {
  2756. evaluateInteractionItems,
  2757. modes: {
  2758. index (chart, e, options, useFinalPosition) {
  2759. const position = helpers_segment.getRelativePosition(e, chart);
  2760. const axis = options.axis || 'x';
  2761. const includeInvisible = options.includeInvisible || false;
  2762. const items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
  2763. const elements = [];
  2764. if (!items.length) {
  2765. return [];
  2766. }
  2767. chart.getSortedVisibleDatasetMetas().forEach((meta)=>{
  2768. const index = items[0].index;
  2769. const element = meta.data[index];
  2770. if (element && !element.skip) {
  2771. elements.push({
  2772. element,
  2773. datasetIndex: meta.index,
  2774. index
  2775. });
  2776. }
  2777. });
  2778. return elements;
  2779. },
  2780. dataset (chart, e, options, useFinalPosition) {
  2781. const position = helpers_segment.getRelativePosition(e, chart);
  2782. const axis = options.axis || 'xy';
  2783. const includeInvisible = options.includeInvisible || false;
  2784. let items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
  2785. if (items.length > 0) {
  2786. const datasetIndex = items[0].datasetIndex;
  2787. const data = chart.getDatasetMeta(datasetIndex).data;
  2788. items = [];
  2789. for(let i = 0; i < data.length; ++i){
  2790. items.push({
  2791. element: data[i],
  2792. datasetIndex,
  2793. index: i
  2794. });
  2795. }
  2796. }
  2797. return items;
  2798. },
  2799. point (chart, e, options, useFinalPosition) {
  2800. const position = helpers_segment.getRelativePosition(e, chart);
  2801. const axis = options.axis || 'xy';
  2802. const includeInvisible = options.includeInvisible || false;
  2803. return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);
  2804. },
  2805. nearest (chart, e, options, useFinalPosition) {
  2806. const position = helpers_segment.getRelativePosition(e, chart);
  2807. const axis = options.axis || 'xy';
  2808. const includeInvisible = options.includeInvisible || false;
  2809. return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);
  2810. },
  2811. x (chart, e, options, useFinalPosition) {
  2812. const position = helpers_segment.getRelativePosition(e, chart);
  2813. return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);
  2814. },
  2815. y (chart, e, options, useFinalPosition) {
  2816. const position = helpers_segment.getRelativePosition(e, chart);
  2817. return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);
  2818. }
  2819. }
  2820. };
  2821. const STATIC_POSITIONS = [
  2822. 'left',
  2823. 'top',
  2824. 'right',
  2825. 'bottom'
  2826. ];
  2827. function filterByPosition(array, position) {
  2828. return array.filter((v)=>v.pos === position);
  2829. }
  2830. function filterDynamicPositionByAxis(array, axis) {
  2831. return array.filter((v)=>STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);
  2832. }
  2833. function sortByWeight(array, reverse) {
  2834. return array.sort((a, b)=>{
  2835. const v0 = reverse ? b : a;
  2836. const v1 = reverse ? a : b;
  2837. return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight;
  2838. });
  2839. }
  2840. function wrapBoxes(boxes) {
  2841. const layoutBoxes = [];
  2842. let i, ilen, box, pos, stack, stackWeight;
  2843. for(i = 0, ilen = (boxes || []).length; i < ilen; ++i){
  2844. box = boxes[i];
  2845. ({ position: pos , options: { stack , stackWeight =1 } } = box);
  2846. layoutBoxes.push({
  2847. index: i,
  2848. box,
  2849. pos,
  2850. horizontal: box.isHorizontal(),
  2851. weight: box.weight,
  2852. stack: stack && pos + stack,
  2853. stackWeight
  2854. });
  2855. }
  2856. return layoutBoxes;
  2857. }
  2858. function buildStacks(layouts) {
  2859. const stacks = {};
  2860. for (const wrap of layouts){
  2861. const { stack , pos , stackWeight } = wrap;
  2862. if (!stack || !STATIC_POSITIONS.includes(pos)) {
  2863. continue;
  2864. }
  2865. const _stack = stacks[stack] || (stacks[stack] = {
  2866. count: 0,
  2867. placed: 0,
  2868. weight: 0,
  2869. size: 0
  2870. });
  2871. _stack.count++;
  2872. _stack.weight += stackWeight;
  2873. }
  2874. return stacks;
  2875. }
  2876. function setLayoutDims(layouts, params) {
  2877. const stacks = buildStacks(layouts);
  2878. const { vBoxMaxWidth , hBoxMaxHeight } = params;
  2879. let i, ilen, layout;
  2880. for(i = 0, ilen = layouts.length; i < ilen; ++i){
  2881. layout = layouts[i];
  2882. const { fullSize } = layout.box;
  2883. const stack = stacks[layout.stack];
  2884. const factor = stack && layout.stackWeight / stack.weight;
  2885. if (layout.horizontal) {
  2886. layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;
  2887. layout.height = hBoxMaxHeight;
  2888. } else {
  2889. layout.width = vBoxMaxWidth;
  2890. layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;
  2891. }
  2892. }
  2893. return stacks;
  2894. }
  2895. function buildLayoutBoxes(boxes) {
  2896. const layoutBoxes = wrapBoxes(boxes);
  2897. const fullSize = sortByWeight(layoutBoxes.filter((wrap)=>wrap.box.fullSize), true);
  2898. const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  2899. const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  2900. const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  2901. const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  2902. const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
  2903. const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
  2904. return {
  2905. fullSize,
  2906. leftAndTop: left.concat(top),
  2907. rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
  2908. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  2909. vertical: left.concat(right).concat(centerVertical),
  2910. horizontal: top.concat(bottom).concat(centerHorizontal)
  2911. };
  2912. }
  2913. function getCombinedMax(maxPadding, chartArea, a, b) {
  2914. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  2915. }
  2916. function updateMaxPadding(maxPadding, boxPadding) {
  2917. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  2918. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  2919. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  2920. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  2921. }
  2922. function updateDims(chartArea, params, layout, stacks) {
  2923. const { pos , box } = layout;
  2924. const maxPadding = chartArea.maxPadding;
  2925. if (!helpers_segment.isObject(pos)) {
  2926. if (layout.size) {
  2927. chartArea[pos] -= layout.size;
  2928. }
  2929. const stack = stacks[layout.stack] || {
  2930. size: 0,
  2931. count: 1
  2932. };
  2933. stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);
  2934. layout.size = stack.size / stack.count;
  2935. chartArea[pos] += layout.size;
  2936. }
  2937. if (box.getPadding) {
  2938. updateMaxPadding(maxPadding, box.getPadding());
  2939. }
  2940. const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
  2941. const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
  2942. const widthChanged = newWidth !== chartArea.w;
  2943. const heightChanged = newHeight !== chartArea.h;
  2944. chartArea.w = newWidth;
  2945. chartArea.h = newHeight;
  2946. return layout.horizontal ? {
  2947. same: widthChanged,
  2948. other: heightChanged
  2949. } : {
  2950. same: heightChanged,
  2951. other: widthChanged
  2952. };
  2953. }
  2954. function handleMaxPadding(chartArea) {
  2955. const maxPadding = chartArea.maxPadding;
  2956. function updatePos(pos) {
  2957. const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  2958. chartArea[pos] += change;
  2959. return change;
  2960. }
  2961. chartArea.y += updatePos('top');
  2962. chartArea.x += updatePos('left');
  2963. updatePos('right');
  2964. updatePos('bottom');
  2965. }
  2966. function getMargins(horizontal, chartArea) {
  2967. const maxPadding = chartArea.maxPadding;
  2968. function marginForPositions(positions) {
  2969. const margin = {
  2970. left: 0,
  2971. top: 0,
  2972. right: 0,
  2973. bottom: 0
  2974. };
  2975. positions.forEach((pos)=>{
  2976. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  2977. });
  2978. return margin;
  2979. }
  2980. return horizontal ? marginForPositions([
  2981. 'left',
  2982. 'right'
  2983. ]) : marginForPositions([
  2984. 'top',
  2985. 'bottom'
  2986. ]);
  2987. }
  2988. function fitBoxes(boxes, chartArea, params, stacks) {
  2989. const refitBoxes = [];
  2990. let i, ilen, layout, box, refit, changed;
  2991. for(i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i){
  2992. layout = boxes[i];
  2993. box = layout.box;
  2994. box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea));
  2995. const { same , other } = updateDims(chartArea, params, layout, stacks);
  2996. refit |= same && refitBoxes.length;
  2997. changed = changed || other;
  2998. if (!box.fullSize) {
  2999. refitBoxes.push(layout);
  3000. }
  3001. }
  3002. return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;
  3003. }
  3004. function setBoxDims(box, left, top, width, height) {
  3005. box.top = top;
  3006. box.left = left;
  3007. box.right = left + width;
  3008. box.bottom = top + height;
  3009. box.width = width;
  3010. box.height = height;
  3011. }
  3012. function placeBoxes(boxes, chartArea, params, stacks) {
  3013. const userPadding = params.padding;
  3014. let { x , y } = chartArea;
  3015. for (const layout of boxes){
  3016. const box = layout.box;
  3017. const stack = stacks[layout.stack] || {
  3018. count: 1,
  3019. placed: 0,
  3020. weight: 1
  3021. };
  3022. const weight = layout.stackWeight / stack.weight || 1;
  3023. if (layout.horizontal) {
  3024. const width = chartArea.w * weight;
  3025. const height = stack.size || box.height;
  3026. if (helpers_segment.defined(stack.start)) {
  3027. y = stack.start;
  3028. }
  3029. if (box.fullSize) {
  3030. setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);
  3031. } else {
  3032. setBoxDims(box, chartArea.left + stack.placed, y, width, height);
  3033. }
  3034. stack.start = y;
  3035. stack.placed += width;
  3036. y = box.bottom;
  3037. } else {
  3038. const height = chartArea.h * weight;
  3039. const width = stack.size || box.width;
  3040. if (helpers_segment.defined(stack.start)) {
  3041. x = stack.start;
  3042. }
  3043. if (box.fullSize) {
  3044. setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);
  3045. } else {
  3046. setBoxDims(box, x, chartArea.top + stack.placed, width, height);
  3047. }
  3048. stack.start = x;
  3049. stack.placed += height;
  3050. x = box.right;
  3051. }
  3052. }
  3053. chartArea.x = x;
  3054. chartArea.y = y;
  3055. }
  3056. var layouts = {
  3057. addBox (chart, item) {
  3058. if (!chart.boxes) {
  3059. chart.boxes = [];
  3060. }
  3061. item.fullSize = item.fullSize || false;
  3062. item.position = item.position || 'top';
  3063. item.weight = item.weight || 0;
  3064. item._layers = item._layers || function() {
  3065. return [
  3066. {
  3067. z: 0,
  3068. draw (chartArea) {
  3069. item.draw(chartArea);
  3070. }
  3071. }
  3072. ];
  3073. };
  3074. chart.boxes.push(item);
  3075. },
  3076. removeBox (chart, layoutItem) {
  3077. const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  3078. if (index !== -1) {
  3079. chart.boxes.splice(index, 1);
  3080. }
  3081. },
  3082. configure (chart, item, options) {
  3083. item.fullSize = options.fullSize;
  3084. item.position = options.position;
  3085. item.weight = options.weight;
  3086. },
  3087. update (chart, width, height, minPadding) {
  3088. if (!chart) {
  3089. return;
  3090. }
  3091. const padding = helpers_segment.toPadding(chart.options.layout.padding);
  3092. const availableWidth = Math.max(width - padding.width, 0);
  3093. const availableHeight = Math.max(height - padding.height, 0);
  3094. const boxes = buildLayoutBoxes(chart.boxes);
  3095. const verticalBoxes = boxes.vertical;
  3096. const horizontalBoxes = boxes.horizontal;
  3097. helpers_segment.each(chart.boxes, (box)=>{
  3098. if (typeof box.beforeLayout === 'function') {
  3099. box.beforeLayout();
  3100. }
  3101. });
  3102. const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap)=>wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
  3103. const params = Object.freeze({
  3104. outerWidth: width,
  3105. outerHeight: height,
  3106. padding,
  3107. availableWidth,
  3108. availableHeight,
  3109. vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
  3110. hBoxMaxHeight: availableHeight / 2
  3111. });
  3112. const maxPadding = Object.assign({}, padding);
  3113. updateMaxPadding(maxPadding, helpers_segment.toPadding(minPadding));
  3114. const chartArea = Object.assign({
  3115. maxPadding,
  3116. w: availableWidth,
  3117. h: availableHeight,
  3118. x: padding.left,
  3119. y: padding.top
  3120. }, padding);
  3121. const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  3122. fitBoxes(boxes.fullSize, chartArea, params, stacks);
  3123. fitBoxes(verticalBoxes, chartArea, params, stacks);
  3124. if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {
  3125. fitBoxes(verticalBoxes, chartArea, params, stacks);
  3126. }
  3127. handleMaxPadding(chartArea);
  3128. placeBoxes(boxes.leftAndTop, chartArea, params, stacks);
  3129. chartArea.x += chartArea.w;
  3130. chartArea.y += chartArea.h;
  3131. placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);
  3132. chart.chartArea = {
  3133. left: chartArea.left,
  3134. top: chartArea.top,
  3135. right: chartArea.left + chartArea.w,
  3136. bottom: chartArea.top + chartArea.h,
  3137. height: chartArea.h,
  3138. width: chartArea.w
  3139. };
  3140. helpers_segment.each(boxes.chartArea, (layout)=>{
  3141. const box = layout.box;
  3142. Object.assign(box, chart.chartArea);
  3143. box.update(chartArea.w, chartArea.h, {
  3144. left: 0,
  3145. top: 0,
  3146. right: 0,
  3147. bottom: 0
  3148. });
  3149. });
  3150. }
  3151. };
  3152. class BasePlatform {
  3153. acquireContext(canvas, aspectRatio) {}
  3154. releaseContext(context) {
  3155. return false;
  3156. }
  3157. addEventListener(chart, type, listener) {}
  3158. removeEventListener(chart, type, listener) {}
  3159. getDevicePixelRatio() {
  3160. return 1;
  3161. }
  3162. getMaximumSize(element, width, height, aspectRatio) {
  3163. width = Math.max(0, width || element.width);
  3164. height = height || element.height;
  3165. return {
  3166. width,
  3167. height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
  3168. };
  3169. }
  3170. isAttached(canvas) {
  3171. return true;
  3172. }
  3173. updateConfig(config) {
  3174. }
  3175. }
  3176. class BasicPlatform extends BasePlatform {
  3177. acquireContext(item) {
  3178. return item && item.getContext && item.getContext('2d') || null;
  3179. }
  3180. updateConfig(config) {
  3181. config.options.animation = false;
  3182. }
  3183. }
  3184. const EXPANDO_KEY = '$chartjs';
  3185. const EVENT_TYPES = {
  3186. touchstart: 'mousedown',
  3187. touchmove: 'mousemove',
  3188. touchend: 'mouseup',
  3189. pointerenter: 'mouseenter',
  3190. pointerdown: 'mousedown',
  3191. pointermove: 'mousemove',
  3192. pointerup: 'mouseup',
  3193. pointerleave: 'mouseout',
  3194. pointerout: 'mouseout'
  3195. };
  3196. const isNullOrEmpty = (value)=>value === null || value === '';
  3197. function initCanvas(canvas, aspectRatio) {
  3198. const style = canvas.style;
  3199. const renderHeight = canvas.getAttribute('height');
  3200. const renderWidth = canvas.getAttribute('width');
  3201. canvas[EXPANDO_KEY] = {
  3202. initial: {
  3203. height: renderHeight,
  3204. width: renderWidth,
  3205. style: {
  3206. display: style.display,
  3207. height: style.height,
  3208. width: style.width
  3209. }
  3210. }
  3211. };
  3212. style.display = style.display || 'block';
  3213. style.boxSizing = style.boxSizing || 'border-box';
  3214. if (isNullOrEmpty(renderWidth)) {
  3215. const displayWidth = helpers_segment.readUsedSize(canvas, 'width');
  3216. if (displayWidth !== undefined) {
  3217. canvas.width = displayWidth;
  3218. }
  3219. }
  3220. if (isNullOrEmpty(renderHeight)) {
  3221. if (canvas.style.height === '') {
  3222. canvas.height = canvas.width / (aspectRatio || 2);
  3223. } else {
  3224. const displayHeight = helpers_segment.readUsedSize(canvas, 'height');
  3225. if (displayHeight !== undefined) {
  3226. canvas.height = displayHeight;
  3227. }
  3228. }
  3229. }
  3230. return canvas;
  3231. }
  3232. const eventListenerOptions = helpers_segment.supportsEventListenerOptions ? {
  3233. passive: true
  3234. } : false;
  3235. function addListener(node, type, listener) {
  3236. if (node) {
  3237. node.addEventListener(type, listener, eventListenerOptions);
  3238. }
  3239. }
  3240. function removeListener(chart, type, listener) {
  3241. if (chart && chart.canvas) {
  3242. chart.canvas.removeEventListener(type, listener, eventListenerOptions);
  3243. }
  3244. }
  3245. function fromNativeEvent(event, chart) {
  3246. const type = EVENT_TYPES[event.type] || event.type;
  3247. const { x , y } = helpers_segment.getRelativePosition(event, chart);
  3248. return {
  3249. type,
  3250. chart,
  3251. native: event,
  3252. x: x !== undefined ? x : null,
  3253. y: y !== undefined ? y : null
  3254. };
  3255. }
  3256. function nodeListContains(nodeList, canvas) {
  3257. for (const node of nodeList){
  3258. if (node === canvas || node.contains(canvas)) {
  3259. return true;
  3260. }
  3261. }
  3262. }
  3263. function createAttachObserver(chart, type, listener) {
  3264. const canvas = chart.canvas;
  3265. const observer = new MutationObserver((entries)=>{
  3266. let trigger = false;
  3267. for (const entry of entries){
  3268. trigger = trigger || nodeListContains(entry.addedNodes, canvas);
  3269. trigger = trigger && !nodeListContains(entry.removedNodes, canvas);
  3270. }
  3271. if (trigger) {
  3272. listener();
  3273. }
  3274. });
  3275. observer.observe(document, {
  3276. childList: true,
  3277. subtree: true
  3278. });
  3279. return observer;
  3280. }
  3281. function createDetachObserver(chart, type, listener) {
  3282. const canvas = chart.canvas;
  3283. const observer = new MutationObserver((entries)=>{
  3284. let trigger = false;
  3285. for (const entry of entries){
  3286. trigger = trigger || nodeListContains(entry.removedNodes, canvas);
  3287. trigger = trigger && !nodeListContains(entry.addedNodes, canvas);
  3288. }
  3289. if (trigger) {
  3290. listener();
  3291. }
  3292. });
  3293. observer.observe(document, {
  3294. childList: true,
  3295. subtree: true
  3296. });
  3297. return observer;
  3298. }
  3299. const drpListeningCharts = new Map();
  3300. let oldDevicePixelRatio = 0;
  3301. function onWindowResize() {
  3302. const dpr = window.devicePixelRatio;
  3303. if (dpr === oldDevicePixelRatio) {
  3304. return;
  3305. }
  3306. oldDevicePixelRatio = dpr;
  3307. drpListeningCharts.forEach((resize, chart)=>{
  3308. if (chart.currentDevicePixelRatio !== dpr) {
  3309. resize();
  3310. }
  3311. });
  3312. }
  3313. function listenDevicePixelRatioChanges(chart, resize) {
  3314. if (!drpListeningCharts.size) {
  3315. window.addEventListener('resize', onWindowResize);
  3316. }
  3317. drpListeningCharts.set(chart, resize);
  3318. }
  3319. function unlistenDevicePixelRatioChanges(chart) {
  3320. drpListeningCharts.delete(chart);
  3321. if (!drpListeningCharts.size) {
  3322. window.removeEventListener('resize', onWindowResize);
  3323. }
  3324. }
  3325. function createResizeObserver(chart, type, listener) {
  3326. const canvas = chart.canvas;
  3327. const container = canvas && helpers_segment._getParentNode(canvas);
  3328. if (!container) {
  3329. return;
  3330. }
  3331. const resize = helpers_segment.throttled((width, height)=>{
  3332. const w = container.clientWidth;
  3333. listener(width, height);
  3334. if (w < container.clientWidth) {
  3335. listener();
  3336. }
  3337. }, window);
  3338. const observer = new ResizeObserver((entries)=>{
  3339. const entry = entries[0];
  3340. const width = entry.contentRect.width;
  3341. const height = entry.contentRect.height;
  3342. if (width === 0 && height === 0) {
  3343. return;
  3344. }
  3345. resize(width, height);
  3346. });
  3347. observer.observe(container);
  3348. listenDevicePixelRatioChanges(chart, resize);
  3349. return observer;
  3350. }
  3351. function releaseObserver(chart, type, observer) {
  3352. if (observer) {
  3353. observer.disconnect();
  3354. }
  3355. if (type === 'resize') {
  3356. unlistenDevicePixelRatioChanges(chart);
  3357. }
  3358. }
  3359. function createProxyAndListen(chart, type, listener) {
  3360. const canvas = chart.canvas;
  3361. const proxy = helpers_segment.throttled((event)=>{
  3362. if (chart.ctx !== null) {
  3363. listener(fromNativeEvent(event, chart));
  3364. }
  3365. }, chart);
  3366. addListener(canvas, type, proxy);
  3367. return proxy;
  3368. }
  3369. class DomPlatform extends BasePlatform {
  3370. acquireContext(canvas, aspectRatio) {
  3371. const context = canvas && canvas.getContext && canvas.getContext('2d');
  3372. if (context && context.canvas === canvas) {
  3373. initCanvas(canvas, aspectRatio);
  3374. return context;
  3375. }
  3376. return null;
  3377. }
  3378. releaseContext(context) {
  3379. const canvas = context.canvas;
  3380. if (!canvas[EXPANDO_KEY]) {
  3381. return false;
  3382. }
  3383. const initial = canvas[EXPANDO_KEY].initial;
  3384. [
  3385. 'height',
  3386. 'width'
  3387. ].forEach((prop)=>{
  3388. const value = initial[prop];
  3389. if (helpers_segment.isNullOrUndef(value)) {
  3390. canvas.removeAttribute(prop);
  3391. } else {
  3392. canvas.setAttribute(prop, value);
  3393. }
  3394. });
  3395. const style = initial.style || {};
  3396. Object.keys(style).forEach((key)=>{
  3397. canvas.style[key] = style[key];
  3398. });
  3399. canvas.width = canvas.width;
  3400. delete canvas[EXPANDO_KEY];
  3401. return true;
  3402. }
  3403. addEventListener(chart, type, listener) {
  3404. this.removeEventListener(chart, type);
  3405. const proxies = chart.$proxies || (chart.$proxies = {});
  3406. const handlers = {
  3407. attach: createAttachObserver,
  3408. detach: createDetachObserver,
  3409. resize: createResizeObserver
  3410. };
  3411. const handler = handlers[type] || createProxyAndListen;
  3412. proxies[type] = handler(chart, type, listener);
  3413. }
  3414. removeEventListener(chart, type) {
  3415. const proxies = chart.$proxies || (chart.$proxies = {});
  3416. const proxy = proxies[type];
  3417. if (!proxy) {
  3418. return;
  3419. }
  3420. const handlers = {
  3421. attach: releaseObserver,
  3422. detach: releaseObserver,
  3423. resize: releaseObserver
  3424. };
  3425. const handler = handlers[type] || removeListener;
  3426. handler(chart, type, proxy);
  3427. proxies[type] = undefined;
  3428. }
  3429. getDevicePixelRatio() {
  3430. return window.devicePixelRatio;
  3431. }
  3432. getMaximumSize(canvas, width, height, aspectRatio) {
  3433. return helpers_segment.getMaximumSize(canvas, width, height, aspectRatio);
  3434. }
  3435. isAttached(canvas) {
  3436. const container = helpers_segment._getParentNode(canvas);
  3437. return !!(container && container.isConnected);
  3438. }
  3439. }
  3440. function _detectPlatform(canvas) {
  3441. if (!helpers_segment._isDomSupported() || typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
  3442. return BasicPlatform;
  3443. }
  3444. return DomPlatform;
  3445. }
  3446. class Element {
  3447. static defaults = {};
  3448. static defaultRoutes = undefined;
  3449. x;
  3450. y;
  3451. active = false;
  3452. options;
  3453. $animations;
  3454. tooltipPosition(useFinalPosition) {
  3455. const { x , y } = this.getProps([
  3456. 'x',
  3457. 'y'
  3458. ], useFinalPosition);
  3459. return {
  3460. x,
  3461. y
  3462. };
  3463. }
  3464. hasValue() {
  3465. return helpers_segment.isNumber(this.x) && helpers_segment.isNumber(this.y);
  3466. }
  3467. getProps(props, final) {
  3468. const anims = this.$animations;
  3469. if (!final || !anims) {
  3470. // let's not create an object, if not needed
  3471. return this;
  3472. }
  3473. const ret = {};
  3474. props.forEach((prop)=>{
  3475. ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop];
  3476. });
  3477. return ret;
  3478. }
  3479. }
  3480. function autoSkip(scale, ticks) {
  3481. const tickOpts = scale.options.ticks;
  3482. const determinedMaxTicks = determineMaxTicks(scale);
  3483. const ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks);
  3484. const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  3485. const numMajorIndices = majorIndices.length;
  3486. const first = majorIndices[0];
  3487. const last = majorIndices[numMajorIndices - 1];
  3488. const newTicks = [];
  3489. if (numMajorIndices > ticksLimit) {
  3490. skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
  3491. return newTicks;
  3492. }
  3493. const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
  3494. if (numMajorIndices > 0) {
  3495. let i, ilen;
  3496. const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
  3497. skip(ticks, newTicks, spacing, helpers_segment.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  3498. for(i = 0, ilen = numMajorIndices - 1; i < ilen; i++){
  3499. skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
  3500. }
  3501. skip(ticks, newTicks, spacing, last, helpers_segment.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  3502. return newTicks;
  3503. }
  3504. skip(ticks, newTicks, spacing);
  3505. return newTicks;
  3506. }
  3507. function determineMaxTicks(scale) {
  3508. const offset = scale.options.offset;
  3509. const tickLength = scale._tickSize();
  3510. const maxScale = scale._length / tickLength + (offset ? 0 : 1);
  3511. const maxChart = scale._maxLength / tickLength;
  3512. return Math.floor(Math.min(maxScale, maxChart));
  3513. }
  3514. function calculateSpacing(majorIndices, ticks, ticksLimit) {
  3515. const evenMajorSpacing = getEvenSpacing(majorIndices);
  3516. const spacing = ticks.length / ticksLimit;
  3517. if (!evenMajorSpacing) {
  3518. return Math.max(spacing, 1);
  3519. }
  3520. const factors = helpers_segment._factorize(evenMajorSpacing);
  3521. for(let i = 0, ilen = factors.length - 1; i < ilen; i++){
  3522. const factor = factors[i];
  3523. if (factor > spacing) {
  3524. return factor;
  3525. }
  3526. }
  3527. return Math.max(spacing, 1);
  3528. }
  3529. function getMajorIndices(ticks) {
  3530. const result = [];
  3531. let i, ilen;
  3532. for(i = 0, ilen = ticks.length; i < ilen; i++){
  3533. if (ticks[i].major) {
  3534. result.push(i);
  3535. }
  3536. }
  3537. return result;
  3538. }
  3539. function skipMajors(ticks, newTicks, majorIndices, spacing) {
  3540. let count = 0;
  3541. let next = majorIndices[0];
  3542. let i;
  3543. spacing = Math.ceil(spacing);
  3544. for(i = 0; i < ticks.length; i++){
  3545. if (i === next) {
  3546. newTicks.push(ticks[i]);
  3547. count++;
  3548. next = majorIndices[count * spacing];
  3549. }
  3550. }
  3551. }
  3552. function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
  3553. const start = helpers_segment.valueOrDefault(majorStart, 0);
  3554. const end = Math.min(helpers_segment.valueOrDefault(majorEnd, ticks.length), ticks.length);
  3555. let count = 0;
  3556. let length, i, next;
  3557. spacing = Math.ceil(spacing);
  3558. if (majorEnd) {
  3559. length = majorEnd - majorStart;
  3560. spacing = length / Math.floor(length / spacing);
  3561. }
  3562. next = start;
  3563. while(next < 0){
  3564. count++;
  3565. next = Math.round(start + count * spacing);
  3566. }
  3567. for(i = Math.max(start, 0); i < end; i++){
  3568. if (i === next) {
  3569. newTicks.push(ticks[i]);
  3570. count++;
  3571. next = Math.round(start + count * spacing);
  3572. }
  3573. }
  3574. }
  3575. function getEvenSpacing(arr) {
  3576. const len = arr.length;
  3577. let i, diff;
  3578. if (len < 2) {
  3579. return false;
  3580. }
  3581. for(diff = arr[0], i = 1; i < len; ++i){
  3582. if (arr[i] - arr[i - 1] !== diff) {
  3583. return false;
  3584. }
  3585. }
  3586. return diff;
  3587. }
  3588. const reverseAlign = (align)=>align === 'left' ? 'right' : align === 'right' ? 'left' : align;
  3589. const offsetFromEdge = (scale, edge, offset)=>edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
  3590. const getTicksLimit = (ticksLength, maxTicksLimit)=>Math.min(maxTicksLimit || ticksLength, ticksLength);
  3591. function sample(arr, numItems) {
  3592. const result = [];
  3593. const increment = arr.length / numItems;
  3594. const len = arr.length;
  3595. let i = 0;
  3596. for(; i < len; i += increment){
  3597. result.push(arr[Math.floor(i)]);
  3598. }
  3599. return result;
  3600. }
  3601. function getPixelForGridLine(scale, index, offsetGridLines) {
  3602. const length = scale.ticks.length;
  3603. const validIndex = Math.min(index, length - 1);
  3604. const start = scale._startPixel;
  3605. const end = scale._endPixel;
  3606. const epsilon = 1e-6;
  3607. let lineValue = scale.getPixelForTick(validIndex);
  3608. let offset;
  3609. if (offsetGridLines) {
  3610. if (length === 1) {
  3611. offset = Math.max(lineValue - start, end - lineValue);
  3612. } else if (index === 0) {
  3613. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  3614. } else {
  3615. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  3616. }
  3617. lineValue += validIndex < index ? offset : -offset;
  3618. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  3619. return;
  3620. }
  3621. }
  3622. return lineValue;
  3623. }
  3624. function garbageCollect(caches, length) {
  3625. helpers_segment.each(caches, (cache)=>{
  3626. const gc = cache.gc;
  3627. const gcLen = gc.length / 2;
  3628. let i;
  3629. if (gcLen > length) {
  3630. for(i = 0; i < gcLen; ++i){
  3631. delete cache.data[gc[i]];
  3632. }
  3633. gc.splice(0, gcLen);
  3634. }
  3635. });
  3636. }
  3637. function getTickMarkLength(options) {
  3638. return options.drawTicks ? options.tickLength : 0;
  3639. }
  3640. function getTitleHeight(options, fallback) {
  3641. if (!options.display) {
  3642. return 0;
  3643. }
  3644. const font = helpers_segment.toFont(options.font, fallback);
  3645. const padding = helpers_segment.toPadding(options.padding);
  3646. const lines = helpers_segment.isArray(options.text) ? options.text.length : 1;
  3647. return lines * font.lineHeight + padding.height;
  3648. }
  3649. function createScaleContext(parent, scale) {
  3650. return helpers_segment.createContext(parent, {
  3651. scale,
  3652. type: 'scale'
  3653. });
  3654. }
  3655. function createTickContext(parent, index, tick) {
  3656. return helpers_segment.createContext(parent, {
  3657. tick,
  3658. index,
  3659. type: 'tick'
  3660. });
  3661. }
  3662. function titleAlign(align, position, reverse) {
  3663. let ret = helpers_segment._toLeftRightCenter(align);
  3664. if (reverse && position !== 'right' || !reverse && position === 'right') {
  3665. ret = reverseAlign(ret);
  3666. }
  3667. return ret;
  3668. }
  3669. function titleArgs(scale, offset, position, align) {
  3670. const { top , left , bottom , right , chart } = scale;
  3671. const { chartArea , scales } = chart;
  3672. let rotation = 0;
  3673. let maxWidth, titleX, titleY;
  3674. const height = bottom - top;
  3675. const width = right - left;
  3676. if (scale.isHorizontal()) {
  3677. titleX = helpers_segment._alignStartEnd(align, left, right);
  3678. if (helpers_segment.isObject(position)) {
  3679. const positionAxisID = Object.keys(position)[0];
  3680. const value = position[positionAxisID];
  3681. titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;
  3682. } else if (position === 'center') {
  3683. titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;
  3684. } else {
  3685. titleY = offsetFromEdge(scale, position, offset);
  3686. }
  3687. maxWidth = right - left;
  3688. } else {
  3689. if (helpers_segment.isObject(position)) {
  3690. const positionAxisID = Object.keys(position)[0];
  3691. const value = position[positionAxisID];
  3692. titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;
  3693. } else if (position === 'center') {
  3694. titleX = (chartArea.left + chartArea.right) / 2 - width + offset;
  3695. } else {
  3696. titleX = offsetFromEdge(scale, position, offset);
  3697. }
  3698. titleY = helpers_segment._alignStartEnd(align, bottom, top);
  3699. rotation = position === 'left' ? -helpers_segment.HALF_PI : helpers_segment.HALF_PI;
  3700. }
  3701. return {
  3702. titleX,
  3703. titleY,
  3704. maxWidth,
  3705. rotation
  3706. };
  3707. }
  3708. class Scale extends Element {
  3709. constructor(cfg){
  3710. super();
  3711. this.id = cfg.id;
  3712. this.type = cfg.type;
  3713. this.options = undefined;
  3714. this.ctx = cfg.ctx;
  3715. this.chart = cfg.chart;
  3716. this.top = undefined;
  3717. this.bottom = undefined;
  3718. this.left = undefined;
  3719. this.right = undefined;
  3720. this.width = undefined;
  3721. this.height = undefined;
  3722. this._margins = {
  3723. left: 0,
  3724. right: 0,
  3725. top: 0,
  3726. bottom: 0
  3727. };
  3728. this.maxWidth = undefined;
  3729. this.maxHeight = undefined;
  3730. this.paddingTop = undefined;
  3731. this.paddingBottom = undefined;
  3732. this.paddingLeft = undefined;
  3733. this.paddingRight = undefined;
  3734. this.axis = undefined;
  3735. this.labelRotation = undefined;
  3736. this.min = undefined;
  3737. this.max = undefined;
  3738. this._range = undefined;
  3739. this.ticks = [];
  3740. this._gridLineItems = null;
  3741. this._labelItems = null;
  3742. this._labelSizes = null;
  3743. this._length = 0;
  3744. this._maxLength = 0;
  3745. this._longestTextCache = {};
  3746. this._startPixel = undefined;
  3747. this._endPixel = undefined;
  3748. this._reversePixels = false;
  3749. this._userMax = undefined;
  3750. this._userMin = undefined;
  3751. this._suggestedMax = undefined;
  3752. this._suggestedMin = undefined;
  3753. this._ticksLength = 0;
  3754. this._borderValue = 0;
  3755. this._cache = {};
  3756. this._dataLimitsCached = false;
  3757. this.$context = undefined;
  3758. }
  3759. init(options) {
  3760. this.options = options.setContext(this.getContext());
  3761. this.axis = options.axis;
  3762. this._userMin = this.parse(options.min);
  3763. this._userMax = this.parse(options.max);
  3764. this._suggestedMin = this.parse(options.suggestedMin);
  3765. this._suggestedMax = this.parse(options.suggestedMax);
  3766. }
  3767. parse(raw, index) {
  3768. return raw;
  3769. }
  3770. getUserBounds() {
  3771. let { _userMin , _userMax , _suggestedMin , _suggestedMax } = this;
  3772. _userMin = helpers_segment.finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
  3773. _userMax = helpers_segment.finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
  3774. _suggestedMin = helpers_segment.finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
  3775. _suggestedMax = helpers_segment.finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
  3776. return {
  3777. min: helpers_segment.finiteOrDefault(_userMin, _suggestedMin),
  3778. max: helpers_segment.finiteOrDefault(_userMax, _suggestedMax),
  3779. minDefined: helpers_segment.isNumberFinite(_userMin),
  3780. maxDefined: helpers_segment.isNumberFinite(_userMax)
  3781. };
  3782. }
  3783. getMinMax(canStack) {
  3784. let { min , max , minDefined , maxDefined } = this.getUserBounds();
  3785. let range;
  3786. if (minDefined && maxDefined) {
  3787. return {
  3788. min,
  3789. max
  3790. };
  3791. }
  3792. const metas = this.getMatchingVisibleMetas();
  3793. for(let i = 0, ilen = metas.length; i < ilen; ++i){
  3794. range = metas[i].controller.getMinMax(this, canStack);
  3795. if (!minDefined) {
  3796. min = Math.min(min, range.min);
  3797. }
  3798. if (!maxDefined) {
  3799. max = Math.max(max, range.max);
  3800. }
  3801. }
  3802. min = maxDefined && min > max ? max : min;
  3803. max = minDefined && min > max ? min : max;
  3804. return {
  3805. min: helpers_segment.finiteOrDefault(min, helpers_segment.finiteOrDefault(max, min)),
  3806. max: helpers_segment.finiteOrDefault(max, helpers_segment.finiteOrDefault(min, max))
  3807. };
  3808. }
  3809. getPadding() {
  3810. return {
  3811. left: this.paddingLeft || 0,
  3812. top: this.paddingTop || 0,
  3813. right: this.paddingRight || 0,
  3814. bottom: this.paddingBottom || 0
  3815. };
  3816. }
  3817. getTicks() {
  3818. return this.ticks;
  3819. }
  3820. getLabels() {
  3821. const data = this.chart.data;
  3822. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  3823. }
  3824. getLabelItems(chartArea = this.chart.chartArea) {
  3825. const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));
  3826. return items;
  3827. }
  3828. beforeLayout() {
  3829. this._cache = {};
  3830. this._dataLimitsCached = false;
  3831. }
  3832. beforeUpdate() {
  3833. helpers_segment.callback(this.options.beforeUpdate, [
  3834. this
  3835. ]);
  3836. }
  3837. update(maxWidth, maxHeight, margins) {
  3838. const { beginAtZero , grace , ticks: tickOpts } = this.options;
  3839. const sampleSize = tickOpts.sampleSize;
  3840. this.beforeUpdate();
  3841. this.maxWidth = maxWidth;
  3842. this.maxHeight = maxHeight;
  3843. this._margins = margins = Object.assign({
  3844. left: 0,
  3845. right: 0,
  3846. top: 0,
  3847. bottom: 0
  3848. }, margins);
  3849. this.ticks = null;
  3850. this._labelSizes = null;
  3851. this._gridLineItems = null;
  3852. this._labelItems = null;
  3853. this.beforeSetDimensions();
  3854. this.setDimensions();
  3855. this.afterSetDimensions();
  3856. this._maxLength = this.isHorizontal() ? this.width + margins.left + margins.right : this.height + margins.top + margins.bottom;
  3857. if (!this._dataLimitsCached) {
  3858. this.beforeDataLimits();
  3859. this.determineDataLimits();
  3860. this.afterDataLimits();
  3861. this._range = helpers_segment._addGrace(this, grace, beginAtZero);
  3862. this._dataLimitsCached = true;
  3863. }
  3864. this.beforeBuildTicks();
  3865. this.ticks = this.buildTicks() || [];
  3866. this.afterBuildTicks();
  3867. const samplingEnabled = sampleSize < this.ticks.length;
  3868. this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);
  3869. this.configure();
  3870. this.beforeCalculateLabelRotation();
  3871. this.calculateLabelRotation();
  3872. this.afterCalculateLabelRotation();
  3873. if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
  3874. this.ticks = autoSkip(this, this.ticks);
  3875. this._labelSizes = null;
  3876. this.afterAutoSkip();
  3877. }
  3878. if (samplingEnabled) {
  3879. this._convertTicksToLabels(this.ticks);
  3880. }
  3881. this.beforeFit();
  3882. this.fit();
  3883. this.afterFit();
  3884. this.afterUpdate();
  3885. }
  3886. configure() {
  3887. let reversePixels = this.options.reverse;
  3888. let startPixel, endPixel;
  3889. if (this.isHorizontal()) {
  3890. startPixel = this.left;
  3891. endPixel = this.right;
  3892. } else {
  3893. startPixel = this.top;
  3894. endPixel = this.bottom;
  3895. reversePixels = !reversePixels;
  3896. }
  3897. this._startPixel = startPixel;
  3898. this._endPixel = endPixel;
  3899. this._reversePixels = reversePixels;
  3900. this._length = endPixel - startPixel;
  3901. this._alignToPixels = this.options.alignToPixels;
  3902. }
  3903. afterUpdate() {
  3904. helpers_segment.callback(this.options.afterUpdate, [
  3905. this
  3906. ]);
  3907. }
  3908. beforeSetDimensions() {
  3909. helpers_segment.callback(this.options.beforeSetDimensions, [
  3910. this
  3911. ]);
  3912. }
  3913. setDimensions() {
  3914. if (this.isHorizontal()) {
  3915. this.width = this.maxWidth;
  3916. this.left = 0;
  3917. this.right = this.width;
  3918. } else {
  3919. this.height = this.maxHeight;
  3920. this.top = 0;
  3921. this.bottom = this.height;
  3922. }
  3923. this.paddingLeft = 0;
  3924. this.paddingTop = 0;
  3925. this.paddingRight = 0;
  3926. this.paddingBottom = 0;
  3927. }
  3928. afterSetDimensions() {
  3929. helpers_segment.callback(this.options.afterSetDimensions, [
  3930. this
  3931. ]);
  3932. }
  3933. _callHooks(name) {
  3934. this.chart.notifyPlugins(name, this.getContext());
  3935. helpers_segment.callback(this.options[name], [
  3936. this
  3937. ]);
  3938. }
  3939. beforeDataLimits() {
  3940. this._callHooks('beforeDataLimits');
  3941. }
  3942. determineDataLimits() {}
  3943. afterDataLimits() {
  3944. this._callHooks('afterDataLimits');
  3945. }
  3946. beforeBuildTicks() {
  3947. this._callHooks('beforeBuildTicks');
  3948. }
  3949. buildTicks() {
  3950. return [];
  3951. }
  3952. afterBuildTicks() {
  3953. this._callHooks('afterBuildTicks');
  3954. }
  3955. beforeTickToLabelConversion() {
  3956. helpers_segment.callback(this.options.beforeTickToLabelConversion, [
  3957. this
  3958. ]);
  3959. }
  3960. generateTickLabels(ticks) {
  3961. const tickOpts = this.options.ticks;
  3962. let i, ilen, tick;
  3963. for(i = 0, ilen = ticks.length; i < ilen; i++){
  3964. tick = ticks[i];
  3965. tick.label = helpers_segment.callback(tickOpts.callback, [
  3966. tick.value,
  3967. i,
  3968. ticks
  3969. ], this);
  3970. }
  3971. }
  3972. afterTickToLabelConversion() {
  3973. helpers_segment.callback(this.options.afterTickToLabelConversion, [
  3974. this
  3975. ]);
  3976. }
  3977. beforeCalculateLabelRotation() {
  3978. helpers_segment.callback(this.options.beforeCalculateLabelRotation, [
  3979. this
  3980. ]);
  3981. }
  3982. calculateLabelRotation() {
  3983. const options = this.options;
  3984. const tickOpts = options.ticks;
  3985. const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit);
  3986. const minRotation = tickOpts.minRotation || 0;
  3987. const maxRotation = tickOpts.maxRotation;
  3988. let labelRotation = minRotation;
  3989. let tickWidth, maxHeight, maxLabelDiagonal;
  3990. if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {
  3991. this.labelRotation = minRotation;
  3992. return;
  3993. }
  3994. const labelSizes = this._getLabelSizes();
  3995. const maxLabelWidth = labelSizes.widest.width;
  3996. const maxLabelHeight = labelSizes.highest.height;
  3997. const maxWidth = helpers_segment._limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);
  3998. tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);
  3999. if (maxLabelWidth + 6 > tickWidth) {
  4000. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  4001. maxHeight = this.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);
  4002. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  4003. labelRotation = helpers_segment.toDegrees(Math.min(Math.asin(helpers_segment._limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(helpers_segment._limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(helpers_segment._limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))));
  4004. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  4005. }
  4006. this.labelRotation = labelRotation;
  4007. }
  4008. afterCalculateLabelRotation() {
  4009. helpers_segment.callback(this.options.afterCalculateLabelRotation, [
  4010. this
  4011. ]);
  4012. }
  4013. afterAutoSkip() {}
  4014. beforeFit() {
  4015. helpers_segment.callback(this.options.beforeFit, [
  4016. this
  4017. ]);
  4018. }
  4019. fit() {
  4020. const minSize = {
  4021. width: 0,
  4022. height: 0
  4023. };
  4024. const { chart , options: { ticks: tickOpts , title: titleOpts , grid: gridOpts } } = this;
  4025. const display = this._isVisible();
  4026. const isHorizontal = this.isHorizontal();
  4027. if (display) {
  4028. const titleHeight = getTitleHeight(titleOpts, chart.options.font);
  4029. if (isHorizontal) {
  4030. minSize.width = this.maxWidth;
  4031. minSize.height = getTickMarkLength(gridOpts) + titleHeight;
  4032. } else {
  4033. minSize.height = this.maxHeight;
  4034. minSize.width = getTickMarkLength(gridOpts) + titleHeight;
  4035. }
  4036. if (tickOpts.display && this.ticks.length) {
  4037. const { first , last , widest , highest } = this._getLabelSizes();
  4038. const tickPadding = tickOpts.padding * 2;
  4039. const angleRadians = helpers_segment.toRadians(this.labelRotation);
  4040. const cos = Math.cos(angleRadians);
  4041. const sin = Math.sin(angleRadians);
  4042. if (isHorizontal) {
  4043. const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
  4044. minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);
  4045. } else {
  4046. const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
  4047. minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);
  4048. }
  4049. this._calculatePadding(first, last, sin, cos);
  4050. }
  4051. }
  4052. this._handleMargins();
  4053. if (isHorizontal) {
  4054. this.width = this._length = chart.width - this._margins.left - this._margins.right;
  4055. this.height = minSize.height;
  4056. } else {
  4057. this.width = minSize.width;
  4058. this.height = this._length = chart.height - this._margins.top - this._margins.bottom;
  4059. }
  4060. }
  4061. _calculatePadding(first, last, sin, cos) {
  4062. const { ticks: { align , padding } , position } = this.options;
  4063. const isRotated = this.labelRotation !== 0;
  4064. const labelsBelowTicks = position !== 'top' && this.axis === 'x';
  4065. if (this.isHorizontal()) {
  4066. const offsetLeft = this.getPixelForTick(0) - this.left;
  4067. const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);
  4068. let paddingLeft = 0;
  4069. let paddingRight = 0;
  4070. if (isRotated) {
  4071. if (labelsBelowTicks) {
  4072. paddingLeft = cos * first.width;
  4073. paddingRight = sin * last.height;
  4074. } else {
  4075. paddingLeft = sin * first.height;
  4076. paddingRight = cos * last.width;
  4077. }
  4078. } else if (align === 'start') {
  4079. paddingRight = last.width;
  4080. } else if (align === 'end') {
  4081. paddingLeft = first.width;
  4082. } else if (align !== 'inner') {
  4083. paddingLeft = first.width / 2;
  4084. paddingRight = last.width / 2;
  4085. }
  4086. this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);
  4087. this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);
  4088. } else {
  4089. let paddingTop = last.height / 2;
  4090. let paddingBottom = first.height / 2;
  4091. if (align === 'start') {
  4092. paddingTop = 0;
  4093. paddingBottom = first.height;
  4094. } else if (align === 'end') {
  4095. paddingTop = last.height;
  4096. paddingBottom = 0;
  4097. }
  4098. this.paddingTop = paddingTop + padding;
  4099. this.paddingBottom = paddingBottom + padding;
  4100. }
  4101. }
  4102. _handleMargins() {
  4103. if (this._margins) {
  4104. this._margins.left = Math.max(this.paddingLeft, this._margins.left);
  4105. this._margins.top = Math.max(this.paddingTop, this._margins.top);
  4106. this._margins.right = Math.max(this.paddingRight, this._margins.right);
  4107. this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);
  4108. }
  4109. }
  4110. afterFit() {
  4111. helpers_segment.callback(this.options.afterFit, [
  4112. this
  4113. ]);
  4114. }
  4115. isHorizontal() {
  4116. const { axis , position } = this.options;
  4117. return position === 'top' || position === 'bottom' || axis === 'x';
  4118. }
  4119. isFullSize() {
  4120. return this.options.fullSize;
  4121. }
  4122. _convertTicksToLabels(ticks) {
  4123. this.beforeTickToLabelConversion();
  4124. this.generateTickLabels(ticks);
  4125. let i, ilen;
  4126. for(i = 0, ilen = ticks.length; i < ilen; i++){
  4127. if (helpers_segment.isNullOrUndef(ticks[i].label)) {
  4128. ticks.splice(i, 1);
  4129. ilen--;
  4130. i--;
  4131. }
  4132. }
  4133. this.afterTickToLabelConversion();
  4134. }
  4135. _getLabelSizes() {
  4136. let labelSizes = this._labelSizes;
  4137. if (!labelSizes) {
  4138. const sampleSize = this.options.ticks.sampleSize;
  4139. let ticks = this.ticks;
  4140. if (sampleSize < ticks.length) {
  4141. ticks = sample(ticks, sampleSize);
  4142. }
  4143. this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit);
  4144. }
  4145. return labelSizes;
  4146. }
  4147. _computeLabelSizes(ticks, length, maxTicksLimit) {
  4148. const { ctx , _longestTextCache: caches } = this;
  4149. const widths = [];
  4150. const heights = [];
  4151. const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit));
  4152. let widestLabelSize = 0;
  4153. let highestLabelSize = 0;
  4154. let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
  4155. for(i = 0; i < length; i += increment){
  4156. label = ticks[i].label;
  4157. tickFont = this._resolveTickFontOptions(i);
  4158. ctx.font = fontString = tickFont.string;
  4159. cache = caches[fontString] = caches[fontString] || {
  4160. data: {},
  4161. gc: []
  4162. };
  4163. lineHeight = tickFont.lineHeight;
  4164. width = height = 0;
  4165. if (!helpers_segment.isNullOrUndef(label) && !helpers_segment.isArray(label)) {
  4166. width = helpers_segment._measureText(ctx, cache.data, cache.gc, width, label);
  4167. height = lineHeight;
  4168. } else if (helpers_segment.isArray(label)) {
  4169. for(j = 0, jlen = label.length; j < jlen; ++j){
  4170. nestedLabel = label[j];
  4171. if (!helpers_segment.isNullOrUndef(nestedLabel) && !helpers_segment.isArray(nestedLabel)) {
  4172. width = helpers_segment._measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  4173. height += lineHeight;
  4174. }
  4175. }
  4176. }
  4177. widths.push(width);
  4178. heights.push(height);
  4179. widestLabelSize = Math.max(width, widestLabelSize);
  4180. highestLabelSize = Math.max(height, highestLabelSize);
  4181. }
  4182. garbageCollect(caches, length);
  4183. const widest = widths.indexOf(widestLabelSize);
  4184. const highest = heights.indexOf(highestLabelSize);
  4185. const valueAt = (idx)=>({
  4186. width: widths[idx] || 0,
  4187. height: heights[idx] || 0
  4188. });
  4189. return {
  4190. first: valueAt(0),
  4191. last: valueAt(length - 1),
  4192. widest: valueAt(widest),
  4193. highest: valueAt(highest),
  4194. widths,
  4195. heights
  4196. };
  4197. }
  4198. getLabelForValue(value) {
  4199. return value;
  4200. }
  4201. getPixelForValue(value, index) {
  4202. return NaN;
  4203. }
  4204. getValueForPixel(pixel) {}
  4205. getPixelForTick(index) {
  4206. const ticks = this.ticks;
  4207. if (index < 0 || index > ticks.length - 1) {
  4208. return null;
  4209. }
  4210. return this.getPixelForValue(ticks[index].value);
  4211. }
  4212. getPixelForDecimal(decimal) {
  4213. if (this._reversePixels) {
  4214. decimal = 1 - decimal;
  4215. }
  4216. const pixel = this._startPixel + decimal * this._length;
  4217. return helpers_segment._int16Range(this._alignToPixels ? helpers_segment._alignPixel(this.chart, pixel, 0) : pixel);
  4218. }
  4219. getDecimalForPixel(pixel) {
  4220. const decimal = (pixel - this._startPixel) / this._length;
  4221. return this._reversePixels ? 1 - decimal : decimal;
  4222. }
  4223. getBasePixel() {
  4224. return this.getPixelForValue(this.getBaseValue());
  4225. }
  4226. getBaseValue() {
  4227. const { min , max } = this;
  4228. return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0;
  4229. }
  4230. getContext(index) {
  4231. const ticks = this.ticks || [];
  4232. if (index >= 0 && index < ticks.length) {
  4233. const tick = ticks[index];
  4234. return tick.$context || (tick.$context = createTickContext(this.getContext(), index, tick));
  4235. }
  4236. return this.$context || (this.$context = createScaleContext(this.chart.getContext(), this));
  4237. }
  4238. _tickSize() {
  4239. const optionTicks = this.options.ticks;
  4240. const rot = helpers_segment.toRadians(this.labelRotation);
  4241. const cos = Math.abs(Math.cos(rot));
  4242. const sin = Math.abs(Math.sin(rot));
  4243. const labelSizes = this._getLabelSizes();
  4244. const padding = optionTicks.autoSkipPadding || 0;
  4245. const w = labelSizes ? labelSizes.widest.width + padding : 0;
  4246. const h = labelSizes ? labelSizes.highest.height + padding : 0;
  4247. return this.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin;
  4248. }
  4249. _isVisible() {
  4250. const display = this.options.display;
  4251. if (display !== 'auto') {
  4252. return !!display;
  4253. }
  4254. return this.getMatchingVisibleMetas().length > 0;
  4255. }
  4256. _computeGridLineItems(chartArea) {
  4257. const axis = this.axis;
  4258. const chart = this.chart;
  4259. const options = this.options;
  4260. const { grid , position , border } = options;
  4261. const offset = grid.offset;
  4262. const isHorizontal = this.isHorizontal();
  4263. const ticks = this.ticks;
  4264. const ticksLength = ticks.length + (offset ? 1 : 0);
  4265. const tl = getTickMarkLength(grid);
  4266. const items = [];
  4267. const borderOpts = border.setContext(this.getContext());
  4268. const axisWidth = borderOpts.display ? borderOpts.width : 0;
  4269. const axisHalfWidth = axisWidth / 2;
  4270. const alignBorderValue = function(pixel) {
  4271. return helpers_segment._alignPixel(chart, pixel, axisWidth);
  4272. };
  4273. let borderValue, i, lineValue, alignedLineValue;
  4274. let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
  4275. if (position === 'top') {
  4276. borderValue = alignBorderValue(this.bottom);
  4277. ty1 = this.bottom - tl;
  4278. ty2 = borderValue - axisHalfWidth;
  4279. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  4280. y2 = chartArea.bottom;
  4281. } else if (position === 'bottom') {
  4282. borderValue = alignBorderValue(this.top);
  4283. y1 = chartArea.top;
  4284. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  4285. ty1 = borderValue + axisHalfWidth;
  4286. ty2 = this.top + tl;
  4287. } else if (position === 'left') {
  4288. borderValue = alignBorderValue(this.right);
  4289. tx1 = this.right - tl;
  4290. tx2 = borderValue - axisHalfWidth;
  4291. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  4292. x2 = chartArea.right;
  4293. } else if (position === 'right') {
  4294. borderValue = alignBorderValue(this.left);
  4295. x1 = chartArea.left;
  4296. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  4297. tx1 = borderValue + axisHalfWidth;
  4298. tx2 = this.left + tl;
  4299. } else if (axis === 'x') {
  4300. if (position === 'center') {
  4301. borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
  4302. } else if (helpers_segment.isObject(position)) {
  4303. const positionAxisID = Object.keys(position)[0];
  4304. const value = position[positionAxisID];
  4305. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4306. }
  4307. y1 = chartArea.top;
  4308. y2 = chartArea.bottom;
  4309. ty1 = borderValue + axisHalfWidth;
  4310. ty2 = ty1 + tl;
  4311. } else if (axis === 'y') {
  4312. if (position === 'center') {
  4313. borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
  4314. } else if (helpers_segment.isObject(position)) {
  4315. const positionAxisID = Object.keys(position)[0];
  4316. const value = position[positionAxisID];
  4317. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4318. }
  4319. tx1 = borderValue - axisHalfWidth;
  4320. tx2 = tx1 - tl;
  4321. x1 = chartArea.left;
  4322. x2 = chartArea.right;
  4323. }
  4324. const limit = helpers_segment.valueOrDefault(options.ticks.maxTicksLimit, ticksLength);
  4325. const step = Math.max(1, Math.ceil(ticksLength / limit));
  4326. for(i = 0; i < ticksLength; i += step){
  4327. const context = this.getContext(i);
  4328. const optsAtIndex = grid.setContext(context);
  4329. const optsAtIndexBorder = border.setContext(context);
  4330. const lineWidth = optsAtIndex.lineWidth;
  4331. const lineColor = optsAtIndex.color;
  4332. const borderDash = optsAtIndexBorder.dash || [];
  4333. const borderDashOffset = optsAtIndexBorder.dashOffset;
  4334. const tickWidth = optsAtIndex.tickWidth;
  4335. const tickColor = optsAtIndex.tickColor;
  4336. const tickBorderDash = optsAtIndex.tickBorderDash || [];
  4337. const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
  4338. lineValue = getPixelForGridLine(this, i, offset);
  4339. if (lineValue === undefined) {
  4340. continue;
  4341. }
  4342. alignedLineValue = helpers_segment._alignPixel(chart, lineValue, lineWidth);
  4343. if (isHorizontal) {
  4344. tx1 = tx2 = x1 = x2 = alignedLineValue;
  4345. } else {
  4346. ty1 = ty2 = y1 = y2 = alignedLineValue;
  4347. }
  4348. items.push({
  4349. tx1,
  4350. ty1,
  4351. tx2,
  4352. ty2,
  4353. x1,
  4354. y1,
  4355. x2,
  4356. y2,
  4357. width: lineWidth,
  4358. color: lineColor,
  4359. borderDash,
  4360. borderDashOffset,
  4361. tickWidth,
  4362. tickColor,
  4363. tickBorderDash,
  4364. tickBorderDashOffset
  4365. });
  4366. }
  4367. this._ticksLength = ticksLength;
  4368. this._borderValue = borderValue;
  4369. return items;
  4370. }
  4371. _computeLabelItems(chartArea) {
  4372. const axis = this.axis;
  4373. const options = this.options;
  4374. const { position , ticks: optionTicks } = options;
  4375. const isHorizontal = this.isHorizontal();
  4376. const ticks = this.ticks;
  4377. const { align , crossAlign , padding , mirror } = optionTicks;
  4378. const tl = getTickMarkLength(options.grid);
  4379. const tickAndPadding = tl + padding;
  4380. const hTickAndPadding = mirror ? -padding : tickAndPadding;
  4381. const rotation = -helpers_segment.toRadians(this.labelRotation);
  4382. const items = [];
  4383. let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  4384. let textBaseline = 'middle';
  4385. if (position === 'top') {
  4386. y = this.bottom - hTickAndPadding;
  4387. textAlign = this._getXAxisLabelAlignment();
  4388. } else if (position === 'bottom') {
  4389. y = this.top + hTickAndPadding;
  4390. textAlign = this._getXAxisLabelAlignment();
  4391. } else if (position === 'left') {
  4392. const ret = this._getYAxisLabelAlignment(tl);
  4393. textAlign = ret.textAlign;
  4394. x = ret.x;
  4395. } else if (position === 'right') {
  4396. const ret = this._getYAxisLabelAlignment(tl);
  4397. textAlign = ret.textAlign;
  4398. x = ret.x;
  4399. } else if (axis === 'x') {
  4400. if (position === 'center') {
  4401. y = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding;
  4402. } else if (helpers_segment.isObject(position)) {
  4403. const positionAxisID = Object.keys(position)[0];
  4404. const value = position[positionAxisID];
  4405. y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
  4406. }
  4407. textAlign = this._getXAxisLabelAlignment();
  4408. } else if (axis === 'y') {
  4409. if (position === 'center') {
  4410. x = (chartArea.left + chartArea.right) / 2 - tickAndPadding;
  4411. } else if (helpers_segment.isObject(position)) {
  4412. const positionAxisID = Object.keys(position)[0];
  4413. const value = position[positionAxisID];
  4414. x = this.chart.scales[positionAxisID].getPixelForValue(value);
  4415. }
  4416. textAlign = this._getYAxisLabelAlignment(tl).textAlign;
  4417. }
  4418. if (axis === 'y') {
  4419. if (align === 'start') {
  4420. textBaseline = 'top';
  4421. } else if (align === 'end') {
  4422. textBaseline = 'bottom';
  4423. }
  4424. }
  4425. const labelSizes = this._getLabelSizes();
  4426. for(i = 0, ilen = ticks.length; i < ilen; ++i){
  4427. tick = ticks[i];
  4428. label = tick.label;
  4429. const optsAtIndex = optionTicks.setContext(this.getContext(i));
  4430. pixel = this.getPixelForTick(i) + optionTicks.labelOffset;
  4431. font = this._resolveTickFontOptions(i);
  4432. lineHeight = font.lineHeight;
  4433. lineCount = helpers_segment.isArray(label) ? label.length : 1;
  4434. const halfCount = lineCount / 2;
  4435. const color = optsAtIndex.color;
  4436. const strokeColor = optsAtIndex.textStrokeColor;
  4437. const strokeWidth = optsAtIndex.textStrokeWidth;
  4438. let tickTextAlign = textAlign;
  4439. if (isHorizontal) {
  4440. x = pixel;
  4441. if (textAlign === 'inner') {
  4442. if (i === ilen - 1) {
  4443. tickTextAlign = !this.options.reverse ? 'right' : 'left';
  4444. } else if (i === 0) {
  4445. tickTextAlign = !this.options.reverse ? 'left' : 'right';
  4446. } else {
  4447. tickTextAlign = 'center';
  4448. }
  4449. }
  4450. if (position === 'top') {
  4451. if (crossAlign === 'near' || rotation !== 0) {
  4452. textOffset = -lineCount * lineHeight + lineHeight / 2;
  4453. } else if (crossAlign === 'center') {
  4454. textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
  4455. } else {
  4456. textOffset = -labelSizes.highest.height + lineHeight / 2;
  4457. }
  4458. } else {
  4459. if (crossAlign === 'near' || rotation !== 0) {
  4460. textOffset = lineHeight / 2;
  4461. } else if (crossAlign === 'center') {
  4462. textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
  4463. } else {
  4464. textOffset = labelSizes.highest.height - lineCount * lineHeight;
  4465. }
  4466. }
  4467. if (mirror) {
  4468. textOffset *= -1;
  4469. }
  4470. if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) {
  4471. x += lineHeight / 2 * Math.sin(rotation);
  4472. }
  4473. } else {
  4474. y = pixel;
  4475. textOffset = (1 - lineCount) * lineHeight / 2;
  4476. }
  4477. let backdrop;
  4478. if (optsAtIndex.showLabelBackdrop) {
  4479. const labelPadding = helpers_segment.toPadding(optsAtIndex.backdropPadding);
  4480. const height = labelSizes.heights[i];
  4481. const width = labelSizes.widths[i];
  4482. let top = textOffset - labelPadding.top;
  4483. let left = 0 - labelPadding.left;
  4484. switch(textBaseline){
  4485. case 'middle':
  4486. top -= height / 2;
  4487. break;
  4488. case 'bottom':
  4489. top -= height;
  4490. break;
  4491. }
  4492. switch(textAlign){
  4493. case 'center':
  4494. left -= width / 2;
  4495. break;
  4496. case 'right':
  4497. left -= width;
  4498. break;
  4499. case 'inner':
  4500. if (i === ilen - 1) {
  4501. left -= width;
  4502. } else if (i > 0) {
  4503. left -= width / 2;
  4504. }
  4505. break;
  4506. }
  4507. backdrop = {
  4508. left,
  4509. top,
  4510. width: width + labelPadding.width,
  4511. height: height + labelPadding.height,
  4512. color: optsAtIndex.backdropColor
  4513. };
  4514. }
  4515. items.push({
  4516. label,
  4517. font,
  4518. textOffset,
  4519. options: {
  4520. rotation,
  4521. color,
  4522. strokeColor,
  4523. strokeWidth,
  4524. textAlign: tickTextAlign,
  4525. textBaseline,
  4526. translation: [
  4527. x,
  4528. y
  4529. ],
  4530. backdrop
  4531. }
  4532. });
  4533. }
  4534. return items;
  4535. }
  4536. _getXAxisLabelAlignment() {
  4537. const { position , ticks } = this.options;
  4538. const rotation = -helpers_segment.toRadians(this.labelRotation);
  4539. if (rotation) {
  4540. return position === 'top' ? 'left' : 'right';
  4541. }
  4542. let align = 'center';
  4543. if (ticks.align === 'start') {
  4544. align = 'left';
  4545. } else if (ticks.align === 'end') {
  4546. align = 'right';
  4547. } else if (ticks.align === 'inner') {
  4548. align = 'inner';
  4549. }
  4550. return align;
  4551. }
  4552. _getYAxisLabelAlignment(tl) {
  4553. const { position , ticks: { crossAlign , mirror , padding } } = this.options;
  4554. const labelSizes = this._getLabelSizes();
  4555. const tickAndPadding = tl + padding;
  4556. const widest = labelSizes.widest.width;
  4557. let textAlign;
  4558. let x;
  4559. if (position === 'left') {
  4560. if (mirror) {
  4561. x = this.right + padding;
  4562. if (crossAlign === 'near') {
  4563. textAlign = 'left';
  4564. } else if (crossAlign === 'center') {
  4565. textAlign = 'center';
  4566. x += widest / 2;
  4567. } else {
  4568. textAlign = 'right';
  4569. x += widest;
  4570. }
  4571. } else {
  4572. x = this.right - tickAndPadding;
  4573. if (crossAlign === 'near') {
  4574. textAlign = 'right';
  4575. } else if (crossAlign === 'center') {
  4576. textAlign = 'center';
  4577. x -= widest / 2;
  4578. } else {
  4579. textAlign = 'left';
  4580. x = this.left;
  4581. }
  4582. }
  4583. } else if (position === 'right') {
  4584. if (mirror) {
  4585. x = this.left + padding;
  4586. if (crossAlign === 'near') {
  4587. textAlign = 'right';
  4588. } else if (crossAlign === 'center') {
  4589. textAlign = 'center';
  4590. x -= widest / 2;
  4591. } else {
  4592. textAlign = 'left';
  4593. x -= widest;
  4594. }
  4595. } else {
  4596. x = this.left + tickAndPadding;
  4597. if (crossAlign === 'near') {
  4598. textAlign = 'left';
  4599. } else if (crossAlign === 'center') {
  4600. textAlign = 'center';
  4601. x += widest / 2;
  4602. } else {
  4603. textAlign = 'right';
  4604. x = this.right;
  4605. }
  4606. }
  4607. } else {
  4608. textAlign = 'right';
  4609. }
  4610. return {
  4611. textAlign,
  4612. x
  4613. };
  4614. }
  4615. _computeLabelArea() {
  4616. if (this.options.ticks.mirror) {
  4617. return;
  4618. }
  4619. const chart = this.chart;
  4620. const position = this.options.position;
  4621. if (position === 'left' || position === 'right') {
  4622. return {
  4623. top: 0,
  4624. left: this.left,
  4625. bottom: chart.height,
  4626. right: this.right
  4627. };
  4628. }
  4629. if (position === 'top' || position === 'bottom') {
  4630. return {
  4631. top: this.top,
  4632. left: 0,
  4633. bottom: this.bottom,
  4634. right: chart.width
  4635. };
  4636. }
  4637. }
  4638. drawBackground() {
  4639. const { ctx , options: { backgroundColor } , left , top , width , height } = this;
  4640. if (backgroundColor) {
  4641. ctx.save();
  4642. ctx.fillStyle = backgroundColor;
  4643. ctx.fillRect(left, top, width, height);
  4644. ctx.restore();
  4645. }
  4646. }
  4647. getLineWidthForValue(value) {
  4648. const grid = this.options.grid;
  4649. if (!this._isVisible() || !grid.display) {
  4650. return 0;
  4651. }
  4652. const ticks = this.ticks;
  4653. const index = ticks.findIndex((t)=>t.value === value);
  4654. if (index >= 0) {
  4655. const opts = grid.setContext(this.getContext(index));
  4656. return opts.lineWidth;
  4657. }
  4658. return 0;
  4659. }
  4660. drawGrid(chartArea) {
  4661. const grid = this.options.grid;
  4662. const ctx = this.ctx;
  4663. const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea));
  4664. let i, ilen;
  4665. const drawLine = (p1, p2, style)=>{
  4666. if (!style.width || !style.color) {
  4667. return;
  4668. }
  4669. ctx.save();
  4670. ctx.lineWidth = style.width;
  4671. ctx.strokeStyle = style.color;
  4672. ctx.setLineDash(style.borderDash || []);
  4673. ctx.lineDashOffset = style.borderDashOffset;
  4674. ctx.beginPath();
  4675. ctx.moveTo(p1.x, p1.y);
  4676. ctx.lineTo(p2.x, p2.y);
  4677. ctx.stroke();
  4678. ctx.restore();
  4679. };
  4680. if (grid.display) {
  4681. for(i = 0, ilen = items.length; i < ilen; ++i){
  4682. const item = items[i];
  4683. if (grid.drawOnChartArea) {
  4684. drawLine({
  4685. x: item.x1,
  4686. y: item.y1
  4687. }, {
  4688. x: item.x2,
  4689. y: item.y2
  4690. }, item);
  4691. }
  4692. if (grid.drawTicks) {
  4693. drawLine({
  4694. x: item.tx1,
  4695. y: item.ty1
  4696. }, {
  4697. x: item.tx2,
  4698. y: item.ty2
  4699. }, {
  4700. color: item.tickColor,
  4701. width: item.tickWidth,
  4702. borderDash: item.tickBorderDash,
  4703. borderDashOffset: item.tickBorderDashOffset
  4704. });
  4705. }
  4706. }
  4707. }
  4708. }
  4709. drawBorder() {
  4710. const { chart , ctx , options: { border , grid } } = this;
  4711. const borderOpts = border.setContext(this.getContext());
  4712. const axisWidth = border.display ? borderOpts.width : 0;
  4713. if (!axisWidth) {
  4714. return;
  4715. }
  4716. const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth;
  4717. const borderValue = this._borderValue;
  4718. let x1, x2, y1, y2;
  4719. if (this.isHorizontal()) {
  4720. x1 = helpers_segment._alignPixel(chart, this.left, axisWidth) - axisWidth / 2;
  4721. x2 = helpers_segment._alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2;
  4722. y1 = y2 = borderValue;
  4723. } else {
  4724. y1 = helpers_segment._alignPixel(chart, this.top, axisWidth) - axisWidth / 2;
  4725. y2 = helpers_segment._alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2;
  4726. x1 = x2 = borderValue;
  4727. }
  4728. ctx.save();
  4729. ctx.lineWidth = borderOpts.width;
  4730. ctx.strokeStyle = borderOpts.color;
  4731. ctx.beginPath();
  4732. ctx.moveTo(x1, y1);
  4733. ctx.lineTo(x2, y2);
  4734. ctx.stroke();
  4735. ctx.restore();
  4736. }
  4737. drawLabels(chartArea) {
  4738. const optionTicks = this.options.ticks;
  4739. if (!optionTicks.display) {
  4740. return;
  4741. }
  4742. const ctx = this.ctx;
  4743. const area = this._computeLabelArea();
  4744. if (area) {
  4745. helpers_segment.clipArea(ctx, area);
  4746. }
  4747. const items = this.getLabelItems(chartArea);
  4748. for (const item of items){
  4749. const renderTextOptions = item.options;
  4750. const tickFont = item.font;
  4751. const label = item.label;
  4752. const y = item.textOffset;
  4753. helpers_segment.renderText(ctx, label, 0, y, tickFont, renderTextOptions);
  4754. }
  4755. if (area) {
  4756. helpers_segment.unclipArea(ctx);
  4757. }
  4758. }
  4759. drawTitle() {
  4760. const { ctx , options: { position , title , reverse } } = this;
  4761. if (!title.display) {
  4762. return;
  4763. }
  4764. const font = helpers_segment.toFont(title.font);
  4765. const padding = helpers_segment.toPadding(title.padding);
  4766. const align = title.align;
  4767. let offset = font.lineHeight / 2;
  4768. if (position === 'bottom' || position === 'center' || helpers_segment.isObject(position)) {
  4769. offset += padding.bottom;
  4770. if (helpers_segment.isArray(title.text)) {
  4771. offset += font.lineHeight * (title.text.length - 1);
  4772. }
  4773. } else {
  4774. offset += padding.top;
  4775. }
  4776. const { titleX , titleY , maxWidth , rotation } = titleArgs(this, offset, position, align);
  4777. helpers_segment.renderText(ctx, title.text, 0, 0, font, {
  4778. color: title.color,
  4779. maxWidth,
  4780. rotation,
  4781. textAlign: titleAlign(align, position, reverse),
  4782. textBaseline: 'middle',
  4783. translation: [
  4784. titleX,
  4785. titleY
  4786. ]
  4787. });
  4788. }
  4789. draw(chartArea) {
  4790. if (!this._isVisible()) {
  4791. return;
  4792. }
  4793. this.drawBackground();
  4794. this.drawGrid(chartArea);
  4795. this.drawBorder();
  4796. this.drawTitle();
  4797. this.drawLabels(chartArea);
  4798. }
  4799. _layers() {
  4800. const opts = this.options;
  4801. const tz = opts.ticks && opts.ticks.z || 0;
  4802. const gz = helpers_segment.valueOrDefault(opts.grid && opts.grid.z, -1);
  4803. const bz = helpers_segment.valueOrDefault(opts.border && opts.border.z, 0);
  4804. if (!this._isVisible() || this.draw !== Scale.prototype.draw) {
  4805. return [
  4806. {
  4807. z: tz,
  4808. draw: (chartArea)=>{
  4809. this.draw(chartArea);
  4810. }
  4811. }
  4812. ];
  4813. }
  4814. return [
  4815. {
  4816. z: gz,
  4817. draw: (chartArea)=>{
  4818. this.drawBackground();
  4819. this.drawGrid(chartArea);
  4820. this.drawTitle();
  4821. }
  4822. },
  4823. {
  4824. z: bz,
  4825. draw: ()=>{
  4826. this.drawBorder();
  4827. }
  4828. },
  4829. {
  4830. z: tz,
  4831. draw: (chartArea)=>{
  4832. this.drawLabels(chartArea);
  4833. }
  4834. }
  4835. ];
  4836. }
  4837. getMatchingVisibleMetas(type) {
  4838. const metas = this.chart.getSortedVisibleDatasetMetas();
  4839. const axisID = this.axis + 'AxisID';
  4840. const result = [];
  4841. let i, ilen;
  4842. for(i = 0, ilen = metas.length; i < ilen; ++i){
  4843. const meta = metas[i];
  4844. if (meta[axisID] === this.id && (!type || meta.type === type)) {
  4845. result.push(meta);
  4846. }
  4847. }
  4848. return result;
  4849. }
  4850. _resolveTickFontOptions(index) {
  4851. const opts = this.options.ticks.setContext(this.getContext(index));
  4852. return helpers_segment.toFont(opts.font);
  4853. }
  4854. _maxDigits() {
  4855. const fontSize = this._resolveTickFontOptions(0).lineHeight;
  4856. return (this.isHorizontal() ? this.width : this.height) / fontSize;
  4857. }
  4858. }
  4859. class TypedRegistry {
  4860. constructor(type, scope, override){
  4861. this.type = type;
  4862. this.scope = scope;
  4863. this.override = override;
  4864. this.items = Object.create(null);
  4865. }
  4866. isForType(type) {
  4867. return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
  4868. }
  4869. register(item) {
  4870. const proto = Object.getPrototypeOf(item);
  4871. let parentScope;
  4872. if (isIChartComponent(proto)) {
  4873. parentScope = this.register(proto);
  4874. }
  4875. const items = this.items;
  4876. const id = item.id;
  4877. const scope = this.scope + '.' + id;
  4878. if (!id) {
  4879. throw new Error('class does not have id: ' + item);
  4880. }
  4881. if (id in items) {
  4882. return scope;
  4883. }
  4884. items[id] = item;
  4885. registerDefaults(item, scope, parentScope);
  4886. if (this.override) {
  4887. helpers_segment.defaults.override(item.id, item.overrides);
  4888. }
  4889. return scope;
  4890. }
  4891. get(id) {
  4892. return this.items[id];
  4893. }
  4894. unregister(item) {
  4895. const items = this.items;
  4896. const id = item.id;
  4897. const scope = this.scope;
  4898. if (id in items) {
  4899. delete items[id];
  4900. }
  4901. if (scope && id in helpers_segment.defaults[scope]) {
  4902. delete helpers_segment.defaults[scope][id];
  4903. if (this.override) {
  4904. delete helpers_segment.overrides[id];
  4905. }
  4906. }
  4907. }
  4908. }
  4909. function registerDefaults(item, scope, parentScope) {
  4910. const itemDefaults = helpers_segment.merge(Object.create(null), [
  4911. parentScope ? helpers_segment.defaults.get(parentScope) : {},
  4912. helpers_segment.defaults.get(scope),
  4913. item.defaults
  4914. ]);
  4915. helpers_segment.defaults.set(scope, itemDefaults);
  4916. if (item.defaultRoutes) {
  4917. routeDefaults(scope, item.defaultRoutes);
  4918. }
  4919. if (item.descriptors) {
  4920. helpers_segment.defaults.describe(scope, item.descriptors);
  4921. }
  4922. }
  4923. function routeDefaults(scope, routes) {
  4924. Object.keys(routes).forEach((property)=>{
  4925. const propertyParts = property.split('.');
  4926. const sourceName = propertyParts.pop();
  4927. const sourceScope = [
  4928. scope
  4929. ].concat(propertyParts).join('.');
  4930. const parts = routes[property].split('.');
  4931. const targetName = parts.pop();
  4932. const targetScope = parts.join('.');
  4933. helpers_segment.defaults.route(sourceScope, sourceName, targetScope, targetName);
  4934. });
  4935. }
  4936. function isIChartComponent(proto) {
  4937. return 'id' in proto && 'defaults' in proto;
  4938. }
  4939. class Registry {
  4940. constructor(){
  4941. this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
  4942. this.elements = new TypedRegistry(Element, 'elements');
  4943. this.plugins = new TypedRegistry(Object, 'plugins');
  4944. this.scales = new TypedRegistry(Scale, 'scales');
  4945. this._typedRegistries = [
  4946. this.controllers,
  4947. this.scales,
  4948. this.elements
  4949. ];
  4950. }
  4951. add(...args) {
  4952. this._each('register', args);
  4953. }
  4954. remove(...args) {
  4955. this._each('unregister', args);
  4956. }
  4957. addControllers(...args) {
  4958. this._each('register', args, this.controllers);
  4959. }
  4960. addElements(...args) {
  4961. this._each('register', args, this.elements);
  4962. }
  4963. addPlugins(...args) {
  4964. this._each('register', args, this.plugins);
  4965. }
  4966. addScales(...args) {
  4967. this._each('register', args, this.scales);
  4968. }
  4969. getController(id) {
  4970. return this._get(id, this.controllers, 'controller');
  4971. }
  4972. getElement(id) {
  4973. return this._get(id, this.elements, 'element');
  4974. }
  4975. getPlugin(id) {
  4976. return this._get(id, this.plugins, 'plugin');
  4977. }
  4978. getScale(id) {
  4979. return this._get(id, this.scales, 'scale');
  4980. }
  4981. removeControllers(...args) {
  4982. this._each('unregister', args, this.controllers);
  4983. }
  4984. removeElements(...args) {
  4985. this._each('unregister', args, this.elements);
  4986. }
  4987. removePlugins(...args) {
  4988. this._each('unregister', args, this.plugins);
  4989. }
  4990. removeScales(...args) {
  4991. this._each('unregister', args, this.scales);
  4992. }
  4993. _each(method, args, typedRegistry) {
  4994. [
  4995. ...args
  4996. ].forEach((arg)=>{
  4997. const reg = typedRegistry || this._getRegistryForType(arg);
  4998. if (typedRegistry || reg.isForType(arg) || reg === this.plugins && arg.id) {
  4999. this._exec(method, reg, arg);
  5000. } else {
  5001. helpers_segment.each(arg, (item)=>{
  5002. const itemReg = typedRegistry || this._getRegistryForType(item);
  5003. this._exec(method, itemReg, item);
  5004. });
  5005. }
  5006. });
  5007. }
  5008. _exec(method, registry, component) {
  5009. const camelMethod = helpers_segment._capitalize(method);
  5010. helpers_segment.callback(component['before' + camelMethod], [], component);
  5011. registry[method](component);
  5012. helpers_segment.callback(component['after' + camelMethod], [], component);
  5013. }
  5014. _getRegistryForType(type) {
  5015. for(let i = 0; i < this._typedRegistries.length; i++){
  5016. const reg = this._typedRegistries[i];
  5017. if (reg.isForType(type)) {
  5018. return reg;
  5019. }
  5020. }
  5021. return this.plugins;
  5022. }
  5023. _get(id, typedRegistry, type) {
  5024. const item = typedRegistry.get(id);
  5025. if (item === undefined) {
  5026. throw new Error('"' + id + '" is not a registered ' + type + '.');
  5027. }
  5028. return item;
  5029. }
  5030. }
  5031. var registry = /* #__PURE__ */ new Registry();
  5032. class PluginService {
  5033. constructor(){
  5034. this._init = [];
  5035. }
  5036. notify(chart, hook, args, filter) {
  5037. if (hook === 'beforeInit') {
  5038. this._init = this._createDescriptors(chart, true);
  5039. this._notify(this._init, chart, 'install');
  5040. }
  5041. const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart);
  5042. const result = this._notify(descriptors, chart, hook, args);
  5043. if (hook === 'afterDestroy') {
  5044. this._notify(descriptors, chart, 'stop');
  5045. this._notify(this._init, chart, 'uninstall');
  5046. }
  5047. return result;
  5048. }
  5049. _notify(descriptors, chart, hook, args) {
  5050. args = args || {};
  5051. for (const descriptor of descriptors){
  5052. const plugin = descriptor.plugin;
  5053. const method = plugin[hook];
  5054. const params = [
  5055. chart,
  5056. args,
  5057. descriptor.options
  5058. ];
  5059. if (helpers_segment.callback(method, params, plugin) === false && args.cancelable) {
  5060. return false;
  5061. }
  5062. }
  5063. return true;
  5064. }
  5065. invalidate() {
  5066. if (!helpers_segment.isNullOrUndef(this._cache)) {
  5067. this._oldCache = this._cache;
  5068. this._cache = undefined;
  5069. }
  5070. }
  5071. _descriptors(chart) {
  5072. if (this._cache) {
  5073. return this._cache;
  5074. }
  5075. const descriptors = this._cache = this._createDescriptors(chart);
  5076. this._notifyStateChanges(chart);
  5077. return descriptors;
  5078. }
  5079. _createDescriptors(chart, all) {
  5080. const config = chart && chart.config;
  5081. const options = helpers_segment.valueOrDefault(config.options && config.options.plugins, {});
  5082. const plugins = allPlugins(config);
  5083. return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
  5084. }
  5085. _notifyStateChanges(chart) {
  5086. const previousDescriptors = this._oldCache || [];
  5087. const descriptors = this._cache;
  5088. const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.plugin.id === y.plugin.id));
  5089. this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
  5090. this._notify(diff(descriptors, previousDescriptors), chart, 'start');
  5091. }
  5092. }
  5093. function allPlugins(config) {
  5094. const localIds = {};
  5095. const plugins = [];
  5096. const keys = Object.keys(registry.plugins.items);
  5097. for(let i = 0; i < keys.length; i++){
  5098. plugins.push(registry.getPlugin(keys[i]));
  5099. }
  5100. const local = config.plugins || [];
  5101. for(let i = 0; i < local.length; i++){
  5102. const plugin = local[i];
  5103. if (plugins.indexOf(plugin) === -1) {
  5104. plugins.push(plugin);
  5105. localIds[plugin.id] = true;
  5106. }
  5107. }
  5108. return {
  5109. plugins,
  5110. localIds
  5111. };
  5112. }
  5113. function getOpts(options, all) {
  5114. if (!all && options === false) {
  5115. return null;
  5116. }
  5117. if (options === true) {
  5118. return {};
  5119. }
  5120. return options;
  5121. }
  5122. function createDescriptors(chart, { plugins , localIds }, options, all) {
  5123. const result = [];
  5124. const context = chart.getContext();
  5125. for (const plugin of plugins){
  5126. const id = plugin.id;
  5127. const opts = getOpts(options[id], all);
  5128. if (opts === null) {
  5129. continue;
  5130. }
  5131. result.push({
  5132. plugin,
  5133. options: pluginOpts(chart.config, {
  5134. plugin,
  5135. local: localIds[id]
  5136. }, opts, context)
  5137. });
  5138. }
  5139. return result;
  5140. }
  5141. function pluginOpts(config, { plugin , local }, opts, context) {
  5142. const keys = config.pluginScopeKeys(plugin);
  5143. const scopes = config.getOptionScopes(opts, keys);
  5144. if (local && plugin.defaults) {
  5145. scopes.push(plugin.defaults);
  5146. }
  5147. return config.createResolver(scopes, context, [
  5148. ''
  5149. ], {
  5150. scriptable: false,
  5151. indexable: false,
  5152. allKeys: true
  5153. });
  5154. }
  5155. function getIndexAxis(type, options) {
  5156. const datasetDefaults = helpers_segment.defaults.datasets[type] || {};
  5157. const datasetOptions = (options.datasets || {})[type] || {};
  5158. return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
  5159. }
  5160. function getAxisFromDefaultScaleID(id, indexAxis) {
  5161. let axis = id;
  5162. if (id === '_index_') {
  5163. axis = indexAxis;
  5164. } else if (id === '_value_') {
  5165. axis = indexAxis === 'x' ? 'y' : 'x';
  5166. }
  5167. return axis;
  5168. }
  5169. function getDefaultScaleIDFromAxis(axis, indexAxis) {
  5170. return axis === indexAxis ? '_index_' : '_value_';
  5171. }
  5172. function idMatchesAxis(id) {
  5173. if (id === 'x' || id === 'y' || id === 'r') {
  5174. return id;
  5175. }
  5176. }
  5177. function axisFromPosition(position) {
  5178. if (position === 'top' || position === 'bottom') {
  5179. return 'x';
  5180. }
  5181. if (position === 'left' || position === 'right') {
  5182. return 'y';
  5183. }
  5184. }
  5185. function determineAxis(id, ...scaleOptions) {
  5186. if (idMatchesAxis(id)) {
  5187. return id;
  5188. }
  5189. for (const opts of scaleOptions){
  5190. const axis = opts.axis || axisFromPosition(opts.position) || id.length > 1 && idMatchesAxis(id[0].toLowerCase());
  5191. if (axis) {
  5192. return axis;
  5193. }
  5194. }
  5195. throw new Error(`Cannot determine type of '${id}' axis. Please provide 'axis' or 'position' option.`);
  5196. }
  5197. function getAxisFromDataset(id, axis, dataset) {
  5198. if (dataset[axis + 'AxisID'] === id) {
  5199. return {
  5200. axis
  5201. };
  5202. }
  5203. }
  5204. function retrieveAxisFromDatasets(id, config) {
  5205. if (config.data && config.data.datasets) {
  5206. const boundDs = config.data.datasets.filter((d)=>d.xAxisID === id || d.yAxisID === id);
  5207. if (boundDs.length) {
  5208. return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]);
  5209. }
  5210. }
  5211. return {};
  5212. }
  5213. function mergeScaleConfig(config, options) {
  5214. const chartDefaults = helpers_segment.overrides[config.type] || {
  5215. scales: {}
  5216. };
  5217. const configScales = options.scales || {};
  5218. const chartIndexAxis = getIndexAxis(config.type, options);
  5219. const scales = Object.create(null);
  5220. Object.keys(configScales).forEach((id)=>{
  5221. const scaleConf = configScales[id];
  5222. if (!helpers_segment.isObject(scaleConf)) {
  5223. return console.error(`Invalid scale configuration for scale: ${id}`);
  5224. }
  5225. if (scaleConf._proxy) {
  5226. return console.warn(`Ignoring resolver passed as options for scale: ${id}`);
  5227. }
  5228. const axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), helpers_segment.defaults.scales[scaleConf.type]);
  5229. const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
  5230. const defaultScaleOptions = chartDefaults.scales || {};
  5231. scales[id] = helpers_segment.mergeIf(Object.create(null), [
  5232. {
  5233. axis
  5234. },
  5235. scaleConf,
  5236. defaultScaleOptions[axis],
  5237. defaultScaleOptions[defaultId]
  5238. ]);
  5239. });
  5240. config.data.datasets.forEach((dataset)=>{
  5241. const type = dataset.type || config.type;
  5242. const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
  5243. const datasetDefaults = helpers_segment.overrides[type] || {};
  5244. const defaultScaleOptions = datasetDefaults.scales || {};
  5245. Object.keys(defaultScaleOptions).forEach((defaultID)=>{
  5246. const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
  5247. const id = dataset[axis + 'AxisID'] || axis;
  5248. scales[id] = scales[id] || Object.create(null);
  5249. helpers_segment.mergeIf(scales[id], [
  5250. {
  5251. axis
  5252. },
  5253. configScales[id],
  5254. defaultScaleOptions[defaultID]
  5255. ]);
  5256. });
  5257. });
  5258. Object.keys(scales).forEach((key)=>{
  5259. const scale = scales[key];
  5260. helpers_segment.mergeIf(scale, [
  5261. helpers_segment.defaults.scales[scale.type],
  5262. helpers_segment.defaults.scale
  5263. ]);
  5264. });
  5265. return scales;
  5266. }
  5267. function initOptions(config) {
  5268. const options = config.options || (config.options = {});
  5269. options.plugins = helpers_segment.valueOrDefault(options.plugins, {});
  5270. options.scales = mergeScaleConfig(config, options);
  5271. }
  5272. function initData(data) {
  5273. data = data || {};
  5274. data.datasets = data.datasets || [];
  5275. data.labels = data.labels || [];
  5276. return data;
  5277. }
  5278. function initConfig(config) {
  5279. config = config || {};
  5280. config.data = initData(config.data);
  5281. initOptions(config);
  5282. return config;
  5283. }
  5284. const keyCache = new Map();
  5285. const keysCached = new Set();
  5286. function cachedKeys(cacheKey, generate) {
  5287. let keys = keyCache.get(cacheKey);
  5288. if (!keys) {
  5289. keys = generate();
  5290. keyCache.set(cacheKey, keys);
  5291. keysCached.add(keys);
  5292. }
  5293. return keys;
  5294. }
  5295. const addIfFound = (set, obj, key)=>{
  5296. const opts = helpers_segment.resolveObjectKey(obj, key);
  5297. if (opts !== undefined) {
  5298. set.add(opts);
  5299. }
  5300. };
  5301. class Config {
  5302. constructor(config){
  5303. this._config = initConfig(config);
  5304. this._scopeCache = new Map();
  5305. this._resolverCache = new Map();
  5306. }
  5307. get platform() {
  5308. return this._config.platform;
  5309. }
  5310. get type() {
  5311. return this._config.type;
  5312. }
  5313. set type(type) {
  5314. this._config.type = type;
  5315. }
  5316. get data() {
  5317. return this._config.data;
  5318. }
  5319. set data(data) {
  5320. this._config.data = initData(data);
  5321. }
  5322. get options() {
  5323. return this._config.options;
  5324. }
  5325. set options(options) {
  5326. this._config.options = options;
  5327. }
  5328. get plugins() {
  5329. return this._config.plugins;
  5330. }
  5331. update() {
  5332. const config = this._config;
  5333. this.clearCache();
  5334. initOptions(config);
  5335. }
  5336. clearCache() {
  5337. this._scopeCache.clear();
  5338. this._resolverCache.clear();
  5339. }
  5340. datasetScopeKeys(datasetType) {
  5341. return cachedKeys(datasetType, ()=>[
  5342. [
  5343. `datasets.${datasetType}`,
  5344. ''
  5345. ]
  5346. ]);
  5347. }
  5348. datasetAnimationScopeKeys(datasetType, transition) {
  5349. return cachedKeys(`${datasetType}.transition.${transition}`, ()=>[
  5350. [
  5351. `datasets.${datasetType}.transitions.${transition}`,
  5352. `transitions.${transition}`
  5353. ],
  5354. [
  5355. `datasets.${datasetType}`,
  5356. ''
  5357. ]
  5358. ]);
  5359. }
  5360. datasetElementScopeKeys(datasetType, elementType) {
  5361. return cachedKeys(`${datasetType}-${elementType}`, ()=>[
  5362. [
  5363. `datasets.${datasetType}.elements.${elementType}`,
  5364. `datasets.${datasetType}`,
  5365. `elements.${elementType}`,
  5366. ''
  5367. ]
  5368. ]);
  5369. }
  5370. pluginScopeKeys(plugin) {
  5371. const id = plugin.id;
  5372. const type = this.type;
  5373. return cachedKeys(`${type}-plugin-${id}`, ()=>[
  5374. [
  5375. `plugins.${id}`,
  5376. ...plugin.additionalOptionScopes || []
  5377. ]
  5378. ]);
  5379. }
  5380. _cachedScopes(mainScope, resetCache) {
  5381. const _scopeCache = this._scopeCache;
  5382. let cache = _scopeCache.get(mainScope);
  5383. if (!cache || resetCache) {
  5384. cache = new Map();
  5385. _scopeCache.set(mainScope, cache);
  5386. }
  5387. return cache;
  5388. }
  5389. getOptionScopes(mainScope, keyLists, resetCache) {
  5390. const { options , type } = this;
  5391. const cache = this._cachedScopes(mainScope, resetCache);
  5392. const cached = cache.get(keyLists);
  5393. if (cached) {
  5394. return cached;
  5395. }
  5396. const scopes = new Set();
  5397. keyLists.forEach((keys)=>{
  5398. if (mainScope) {
  5399. scopes.add(mainScope);
  5400. keys.forEach((key)=>addIfFound(scopes, mainScope, key));
  5401. }
  5402. keys.forEach((key)=>addIfFound(scopes, options, key));
  5403. keys.forEach((key)=>addIfFound(scopes, helpers_segment.overrides[type] || {}, key));
  5404. keys.forEach((key)=>addIfFound(scopes, helpers_segment.defaults, key));
  5405. keys.forEach((key)=>addIfFound(scopes, helpers_segment.descriptors, key));
  5406. });
  5407. const array = Array.from(scopes);
  5408. if (array.length === 0) {
  5409. array.push(Object.create(null));
  5410. }
  5411. if (keysCached.has(keyLists)) {
  5412. cache.set(keyLists, array);
  5413. }
  5414. return array;
  5415. }
  5416. chartOptionScopes() {
  5417. const { options , type } = this;
  5418. return [
  5419. options,
  5420. helpers_segment.overrides[type] || {},
  5421. helpers_segment.defaults.datasets[type] || {},
  5422. {
  5423. type
  5424. },
  5425. helpers_segment.defaults,
  5426. helpers_segment.descriptors
  5427. ];
  5428. }
  5429. resolveNamedOptions(scopes, names, context, prefixes = [
  5430. ''
  5431. ]) {
  5432. const result = {
  5433. $shared: true
  5434. };
  5435. const { resolver , subPrefixes } = getResolver(this._resolverCache, scopes, prefixes);
  5436. let options = resolver;
  5437. if (needContext(resolver, names)) {
  5438. result.$shared = false;
  5439. context = helpers_segment.isFunction(context) ? context() : context;
  5440. const subResolver = this.createResolver(scopes, context, subPrefixes);
  5441. options = helpers_segment._attachContext(resolver, context, subResolver);
  5442. }
  5443. for (const prop of names){
  5444. result[prop] = options[prop];
  5445. }
  5446. return result;
  5447. }
  5448. createResolver(scopes, context, prefixes = [
  5449. ''
  5450. ], descriptorDefaults) {
  5451. const { resolver } = getResolver(this._resolverCache, scopes, prefixes);
  5452. return helpers_segment.isObject(context) ? helpers_segment._attachContext(resolver, context, undefined, descriptorDefaults) : resolver;
  5453. }
  5454. }
  5455. function getResolver(resolverCache, scopes, prefixes) {
  5456. let cache = resolverCache.get(scopes);
  5457. if (!cache) {
  5458. cache = new Map();
  5459. resolverCache.set(scopes, cache);
  5460. }
  5461. const cacheKey = prefixes.join();
  5462. let cached = cache.get(cacheKey);
  5463. if (!cached) {
  5464. const resolver = helpers_segment._createResolver(scopes, prefixes);
  5465. cached = {
  5466. resolver,
  5467. subPrefixes: prefixes.filter((p)=>!p.toLowerCase().includes('hover'))
  5468. };
  5469. cache.set(cacheKey, cached);
  5470. }
  5471. return cached;
  5472. }
  5473. const hasFunction = (value)=>helpers_segment.isObject(value) && Object.getOwnPropertyNames(value).some((key)=>helpers_segment.isFunction(value[key]));
  5474. function needContext(proxy, names) {
  5475. const { isScriptable , isIndexable } = helpers_segment._descriptors(proxy);
  5476. for (const prop of names){
  5477. const scriptable = isScriptable(prop);
  5478. const indexable = isIndexable(prop);
  5479. const value = (indexable || scriptable) && proxy[prop];
  5480. if (scriptable && (helpers_segment.isFunction(value) || hasFunction(value)) || indexable && helpers_segment.isArray(value)) {
  5481. return true;
  5482. }
  5483. }
  5484. return false;
  5485. }
  5486. var version = "4.4.2";
  5487. const KNOWN_POSITIONS = [
  5488. 'top',
  5489. 'bottom',
  5490. 'left',
  5491. 'right',
  5492. 'chartArea'
  5493. ];
  5494. function positionIsHorizontal(position, axis) {
  5495. return position === 'top' || position === 'bottom' || KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x';
  5496. }
  5497. function compare2Level(l1, l2) {
  5498. return function(a, b) {
  5499. return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1];
  5500. };
  5501. }
  5502. function onAnimationsComplete(context) {
  5503. const chart = context.chart;
  5504. const animationOptions = chart.options.animation;
  5505. chart.notifyPlugins('afterRender');
  5506. helpers_segment.callback(animationOptions && animationOptions.onComplete, [
  5507. context
  5508. ], chart);
  5509. }
  5510. function onAnimationProgress(context) {
  5511. const chart = context.chart;
  5512. const animationOptions = chart.options.animation;
  5513. helpers_segment.callback(animationOptions && animationOptions.onProgress, [
  5514. context
  5515. ], chart);
  5516. }
  5517. function getCanvas(item) {
  5518. if (helpers_segment._isDomSupported() && typeof item === 'string') {
  5519. item = document.getElementById(item);
  5520. } else if (item && item.length) {
  5521. item = item[0];
  5522. }
  5523. if (item && item.canvas) {
  5524. item = item.canvas;
  5525. }
  5526. return item;
  5527. }
  5528. const instances = {};
  5529. const getChart = (key)=>{
  5530. const canvas = getCanvas(key);
  5531. return Object.values(instances).filter((c)=>c.canvas === canvas).pop();
  5532. };
  5533. function moveNumericKeys(obj, start, move) {
  5534. const keys = Object.keys(obj);
  5535. for (const key of keys){
  5536. const intKey = +key;
  5537. if (intKey >= start) {
  5538. const value = obj[key];
  5539. delete obj[key];
  5540. if (move > 0 || intKey > start) {
  5541. obj[intKey + move] = value;
  5542. }
  5543. }
  5544. }
  5545. }
  5546. function determineLastEvent(e, lastEvent, inChartArea, isClick) {
  5547. if (!inChartArea || e.type === 'mouseout') {
  5548. return null;
  5549. }
  5550. if (isClick) {
  5551. return lastEvent;
  5552. }
  5553. return e;
  5554. }
  5555. function getSizeForArea(scale, chartArea, field) {
  5556. return scale.options.clip ? scale[field] : chartArea[field];
  5557. }
  5558. function getDatasetArea(meta, chartArea) {
  5559. const { xScale , yScale } = meta;
  5560. if (xScale && yScale) {
  5561. return {
  5562. left: getSizeForArea(xScale, chartArea, 'left'),
  5563. right: getSizeForArea(xScale, chartArea, 'right'),
  5564. top: getSizeForArea(yScale, chartArea, 'top'),
  5565. bottom: getSizeForArea(yScale, chartArea, 'bottom')
  5566. };
  5567. }
  5568. return chartArea;
  5569. }
  5570. class Chart {
  5571. static defaults = helpers_segment.defaults;
  5572. static instances = instances;
  5573. static overrides = helpers_segment.overrides;
  5574. static registry = registry;
  5575. static version = version;
  5576. static getChart = getChart;
  5577. static register(...items) {
  5578. registry.add(...items);
  5579. invalidatePlugins();
  5580. }
  5581. static unregister(...items) {
  5582. registry.remove(...items);
  5583. invalidatePlugins();
  5584. }
  5585. constructor(item, userConfig){
  5586. const config = this.config = new Config(userConfig);
  5587. const initialCanvas = getCanvas(item);
  5588. const existingChart = getChart(initialCanvas);
  5589. if (existingChart) {
  5590. 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.');
  5591. }
  5592. const options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5593. this.platform = new (config.platform || _detectPlatform(initialCanvas))();
  5594. this.platform.updateConfig(config);
  5595. const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);
  5596. const canvas = context && context.canvas;
  5597. const height = canvas && canvas.height;
  5598. const width = canvas && canvas.width;
  5599. this.id = helpers_segment.uid();
  5600. this.ctx = context;
  5601. this.canvas = canvas;
  5602. this.width = width;
  5603. this.height = height;
  5604. this._options = options;
  5605. this._aspectRatio = this.aspectRatio;
  5606. this._layers = [];
  5607. this._metasets = [];
  5608. this._stacks = undefined;
  5609. this.boxes = [];
  5610. this.currentDevicePixelRatio = undefined;
  5611. this.chartArea = undefined;
  5612. this._active = [];
  5613. this._lastEvent = undefined;
  5614. this._listeners = {};
  5615. this._responsiveListeners = undefined;
  5616. this._sortedMetasets = [];
  5617. this.scales = {};
  5618. this._plugins = new PluginService();
  5619. this.$proxies = {};
  5620. this._hiddenIndices = {};
  5621. this.attached = false;
  5622. this._animationsDisabled = undefined;
  5623. this.$context = undefined;
  5624. this._doResize = helpers_segment.debounce((mode)=>this.update(mode), options.resizeDelay || 0);
  5625. this._dataChanges = [];
  5626. instances[this.id] = this;
  5627. if (!context || !canvas) {
  5628. console.error("Failed to create chart: can't acquire context from the given item");
  5629. return;
  5630. }
  5631. animator.listen(this, 'complete', onAnimationsComplete);
  5632. animator.listen(this, 'progress', onAnimationProgress);
  5633. this._initialize();
  5634. if (this.attached) {
  5635. this.update();
  5636. }
  5637. }
  5638. get aspectRatio() {
  5639. const { options: { aspectRatio , maintainAspectRatio } , width , height , _aspectRatio } = this;
  5640. if (!helpers_segment.isNullOrUndef(aspectRatio)) {
  5641. return aspectRatio;
  5642. }
  5643. if (maintainAspectRatio && _aspectRatio) {
  5644. return _aspectRatio;
  5645. }
  5646. return height ? width / height : null;
  5647. }
  5648. get data() {
  5649. return this.config.data;
  5650. }
  5651. set data(data) {
  5652. this.config.data = data;
  5653. }
  5654. get options() {
  5655. return this._options;
  5656. }
  5657. set options(options) {
  5658. this.config.options = options;
  5659. }
  5660. get registry() {
  5661. return registry;
  5662. }
  5663. _initialize() {
  5664. this.notifyPlugins('beforeInit');
  5665. if (this.options.responsive) {
  5666. this.resize();
  5667. } else {
  5668. helpers_segment.retinaScale(this, this.options.devicePixelRatio);
  5669. }
  5670. this.bindEvents();
  5671. this.notifyPlugins('afterInit');
  5672. return this;
  5673. }
  5674. clear() {
  5675. helpers_segment.clearCanvas(this.canvas, this.ctx);
  5676. return this;
  5677. }
  5678. stop() {
  5679. animator.stop(this);
  5680. return this;
  5681. }
  5682. resize(width, height) {
  5683. if (!animator.running(this)) {
  5684. this._resize(width, height);
  5685. } else {
  5686. this._resizeBeforeDraw = {
  5687. width,
  5688. height
  5689. };
  5690. }
  5691. }
  5692. _resize(width, height) {
  5693. const options = this.options;
  5694. const canvas = this.canvas;
  5695. const aspectRatio = options.maintainAspectRatio && this.aspectRatio;
  5696. const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);
  5697. const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();
  5698. const mode = this.width ? 'resize' : 'attach';
  5699. this.width = newSize.width;
  5700. this.height = newSize.height;
  5701. this._aspectRatio = this.aspectRatio;
  5702. if (!helpers_segment.retinaScale(this, newRatio, true)) {
  5703. return;
  5704. }
  5705. this.notifyPlugins('resize', {
  5706. size: newSize
  5707. });
  5708. helpers_segment.callback(options.onResize, [
  5709. this,
  5710. newSize
  5711. ], this);
  5712. if (this.attached) {
  5713. if (this._doResize(mode)) {
  5714. this.render();
  5715. }
  5716. }
  5717. }
  5718. ensureScalesHaveIDs() {
  5719. const options = this.options;
  5720. const scalesOptions = options.scales || {};
  5721. helpers_segment.each(scalesOptions, (axisOptions, axisID)=>{
  5722. axisOptions.id = axisID;
  5723. });
  5724. }
  5725. buildOrUpdateScales() {
  5726. const options = this.options;
  5727. const scaleOpts = options.scales;
  5728. const scales = this.scales;
  5729. const updated = Object.keys(scales).reduce((obj, id)=>{
  5730. obj[id] = false;
  5731. return obj;
  5732. }, {});
  5733. let items = [];
  5734. if (scaleOpts) {
  5735. items = items.concat(Object.keys(scaleOpts).map((id)=>{
  5736. const scaleOptions = scaleOpts[id];
  5737. const axis = determineAxis(id, scaleOptions);
  5738. const isRadial = axis === 'r';
  5739. const isHorizontal = axis === 'x';
  5740. return {
  5741. options: scaleOptions,
  5742. dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
  5743. dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
  5744. };
  5745. }));
  5746. }
  5747. helpers_segment.each(items, (item)=>{
  5748. const scaleOptions = item.options;
  5749. const id = scaleOptions.id;
  5750. const axis = determineAxis(id, scaleOptions);
  5751. const scaleType = helpers_segment.valueOrDefault(scaleOptions.type, item.dtype);
  5752. if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
  5753. scaleOptions.position = item.dposition;
  5754. }
  5755. updated[id] = true;
  5756. let scale = null;
  5757. if (id in scales && scales[id].type === scaleType) {
  5758. scale = scales[id];
  5759. } else {
  5760. const scaleClass = registry.getScale(scaleType);
  5761. scale = new scaleClass({
  5762. id,
  5763. type: scaleType,
  5764. ctx: this.ctx,
  5765. chart: this
  5766. });
  5767. scales[scale.id] = scale;
  5768. }
  5769. scale.init(scaleOptions, options);
  5770. });
  5771. helpers_segment.each(updated, (hasUpdated, id)=>{
  5772. if (!hasUpdated) {
  5773. delete scales[id];
  5774. }
  5775. });
  5776. helpers_segment.each(scales, (scale)=>{
  5777. layouts.configure(this, scale, scale.options);
  5778. layouts.addBox(this, scale);
  5779. });
  5780. }
  5781. _updateMetasets() {
  5782. const metasets = this._metasets;
  5783. const numData = this.data.datasets.length;
  5784. const numMeta = metasets.length;
  5785. metasets.sort((a, b)=>a.index - b.index);
  5786. if (numMeta > numData) {
  5787. for(let i = numData; i < numMeta; ++i){
  5788. this._destroyDatasetMeta(i);
  5789. }
  5790. metasets.splice(numData, numMeta - numData);
  5791. }
  5792. this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
  5793. }
  5794. _removeUnreferencedMetasets() {
  5795. const { _metasets: metasets , data: { datasets } } = this;
  5796. if (metasets.length > datasets.length) {
  5797. delete this._stacks;
  5798. }
  5799. metasets.forEach((meta, index)=>{
  5800. if (datasets.filter((x)=>x === meta._dataset).length === 0) {
  5801. this._destroyDatasetMeta(index);
  5802. }
  5803. });
  5804. }
  5805. buildOrUpdateControllers() {
  5806. const newControllers = [];
  5807. const datasets = this.data.datasets;
  5808. let i, ilen;
  5809. this._removeUnreferencedMetasets();
  5810. for(i = 0, ilen = datasets.length; i < ilen; i++){
  5811. const dataset = datasets[i];
  5812. let meta = this.getDatasetMeta(i);
  5813. const type = dataset.type || this.config.type;
  5814. if (meta.type && meta.type !== type) {
  5815. this._destroyDatasetMeta(i);
  5816. meta = this.getDatasetMeta(i);
  5817. }
  5818. meta.type = type;
  5819. meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);
  5820. meta.order = dataset.order || 0;
  5821. meta.index = i;
  5822. meta.label = '' + dataset.label;
  5823. meta.visible = this.isDatasetVisible(i);
  5824. if (meta.controller) {
  5825. meta.controller.updateIndex(i);
  5826. meta.controller.linkScales();
  5827. } else {
  5828. const ControllerClass = registry.getController(type);
  5829. const { datasetElementType , dataElementType } = helpers_segment.defaults.datasets[type];
  5830. Object.assign(ControllerClass, {
  5831. dataElementType: registry.getElement(dataElementType),
  5832. datasetElementType: datasetElementType && registry.getElement(datasetElementType)
  5833. });
  5834. meta.controller = new ControllerClass(this, i);
  5835. newControllers.push(meta.controller);
  5836. }
  5837. }
  5838. this._updateMetasets();
  5839. return newControllers;
  5840. }
  5841. _resetElements() {
  5842. helpers_segment.each(this.data.datasets, (dataset, datasetIndex)=>{
  5843. this.getDatasetMeta(datasetIndex).controller.reset();
  5844. }, this);
  5845. }
  5846. reset() {
  5847. this._resetElements();
  5848. this.notifyPlugins('reset');
  5849. }
  5850. update(mode) {
  5851. const config = this.config;
  5852. config.update();
  5853. const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5854. const animsDisabled = this._animationsDisabled = !options.animation;
  5855. this._updateScales();
  5856. this._checkEventBindings();
  5857. this._updateHiddenIndices();
  5858. this._plugins.invalidate();
  5859. if (this.notifyPlugins('beforeUpdate', {
  5860. mode,
  5861. cancelable: true
  5862. }) === false) {
  5863. return;
  5864. }
  5865. const newControllers = this.buildOrUpdateControllers();
  5866. this.notifyPlugins('beforeElementsUpdate');
  5867. let minPadding = 0;
  5868. for(let i = 0, ilen = this.data.datasets.length; i < ilen; i++){
  5869. const { controller } = this.getDatasetMeta(i);
  5870. const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
  5871. controller.buildOrUpdateElements(reset);
  5872. minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
  5873. }
  5874. minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;
  5875. this._updateLayout(minPadding);
  5876. if (!animsDisabled) {
  5877. helpers_segment.each(newControllers, (controller)=>{
  5878. controller.reset();
  5879. });
  5880. }
  5881. this._updateDatasets(mode);
  5882. this.notifyPlugins('afterUpdate', {
  5883. mode
  5884. });
  5885. this._layers.sort(compare2Level('z', '_idx'));
  5886. const { _active , _lastEvent } = this;
  5887. if (_lastEvent) {
  5888. this._eventHandler(_lastEvent, true);
  5889. } else if (_active.length) {
  5890. this._updateHoverStyles(_active, _active, true);
  5891. }
  5892. this.render();
  5893. }
  5894. _updateScales() {
  5895. helpers_segment.each(this.scales, (scale)=>{
  5896. layouts.removeBox(this, scale);
  5897. });
  5898. this.ensureScalesHaveIDs();
  5899. this.buildOrUpdateScales();
  5900. }
  5901. _checkEventBindings() {
  5902. const options = this.options;
  5903. const existingEvents = new Set(Object.keys(this._listeners));
  5904. const newEvents = new Set(options.events);
  5905. if (!helpers_segment.setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {
  5906. this.unbindEvents();
  5907. this.bindEvents();
  5908. }
  5909. }
  5910. _updateHiddenIndices() {
  5911. const { _hiddenIndices } = this;
  5912. const changes = this._getUniformDataChanges() || [];
  5913. for (const { method , start , count } of changes){
  5914. const move = method === '_removeElements' ? -count : count;
  5915. moveNumericKeys(_hiddenIndices, start, move);
  5916. }
  5917. }
  5918. _getUniformDataChanges() {
  5919. const _dataChanges = this._dataChanges;
  5920. if (!_dataChanges || !_dataChanges.length) {
  5921. return;
  5922. }
  5923. this._dataChanges = [];
  5924. const datasetCount = this.data.datasets.length;
  5925. const makeSet = (idx)=>new Set(_dataChanges.filter((c)=>c[0] === idx).map((c, i)=>i + ',' + c.splice(1).join(',')));
  5926. const changeSet = makeSet(0);
  5927. for(let i = 1; i < datasetCount; i++){
  5928. if (!helpers_segment.setsEqual(changeSet, makeSet(i))) {
  5929. return;
  5930. }
  5931. }
  5932. return Array.from(changeSet).map((c)=>c.split(',')).map((a)=>({
  5933. method: a[1],
  5934. start: +a[2],
  5935. count: +a[3]
  5936. }));
  5937. }
  5938. _updateLayout(minPadding) {
  5939. if (this.notifyPlugins('beforeLayout', {
  5940. cancelable: true
  5941. }) === false) {
  5942. return;
  5943. }
  5944. layouts.update(this, this.width, this.height, minPadding);
  5945. const area = this.chartArea;
  5946. const noArea = area.width <= 0 || area.height <= 0;
  5947. this._layers = [];
  5948. helpers_segment.each(this.boxes, (box)=>{
  5949. if (noArea && box.position === 'chartArea') {
  5950. return;
  5951. }
  5952. if (box.configure) {
  5953. box.configure();
  5954. }
  5955. this._layers.push(...box._layers());
  5956. }, this);
  5957. this._layers.forEach((item, index)=>{
  5958. item._idx = index;
  5959. });
  5960. this.notifyPlugins('afterLayout');
  5961. }
  5962. _updateDatasets(mode) {
  5963. if (this.notifyPlugins('beforeDatasetsUpdate', {
  5964. mode,
  5965. cancelable: true
  5966. }) === false) {
  5967. return;
  5968. }
  5969. for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  5970. this.getDatasetMeta(i).controller.configure();
  5971. }
  5972. for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  5973. this._updateDataset(i, helpers_segment.isFunction(mode) ? mode({
  5974. datasetIndex: i
  5975. }) : mode);
  5976. }
  5977. this.notifyPlugins('afterDatasetsUpdate', {
  5978. mode
  5979. });
  5980. }
  5981. _updateDataset(index, mode) {
  5982. const meta = this.getDatasetMeta(index);
  5983. const args = {
  5984. meta,
  5985. index,
  5986. mode,
  5987. cancelable: true
  5988. };
  5989. if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {
  5990. return;
  5991. }
  5992. meta.controller._update(mode);
  5993. args.cancelable = false;
  5994. this.notifyPlugins('afterDatasetUpdate', args);
  5995. }
  5996. render() {
  5997. if (this.notifyPlugins('beforeRender', {
  5998. cancelable: true
  5999. }) === false) {
  6000. return;
  6001. }
  6002. if (animator.has(this)) {
  6003. if (this.attached && !animator.running(this)) {
  6004. animator.start(this);
  6005. }
  6006. } else {
  6007. this.draw();
  6008. onAnimationsComplete({
  6009. chart: this
  6010. });
  6011. }
  6012. }
  6013. draw() {
  6014. let i;
  6015. if (this._resizeBeforeDraw) {
  6016. const { width , height } = this._resizeBeforeDraw;
  6017. this._resize(width, height);
  6018. this._resizeBeforeDraw = null;
  6019. }
  6020. this.clear();
  6021. if (this.width <= 0 || this.height <= 0) {
  6022. return;
  6023. }
  6024. if (this.notifyPlugins('beforeDraw', {
  6025. cancelable: true
  6026. }) === false) {
  6027. return;
  6028. }
  6029. const layers = this._layers;
  6030. for(i = 0; i < layers.length && layers[i].z <= 0; ++i){
  6031. layers[i].draw(this.chartArea);
  6032. }
  6033. this._drawDatasets();
  6034. for(; i < layers.length; ++i){
  6035. layers[i].draw(this.chartArea);
  6036. }
  6037. this.notifyPlugins('afterDraw');
  6038. }
  6039. _getSortedDatasetMetas(filterVisible) {
  6040. const metasets = this._sortedMetasets;
  6041. const result = [];
  6042. let i, ilen;
  6043. for(i = 0, ilen = metasets.length; i < ilen; ++i){
  6044. const meta = metasets[i];
  6045. if (!filterVisible || meta.visible) {
  6046. result.push(meta);
  6047. }
  6048. }
  6049. return result;
  6050. }
  6051. getSortedVisibleDatasetMetas() {
  6052. return this._getSortedDatasetMetas(true);
  6053. }
  6054. _drawDatasets() {
  6055. if (this.notifyPlugins('beforeDatasetsDraw', {
  6056. cancelable: true
  6057. }) === false) {
  6058. return;
  6059. }
  6060. const metasets = this.getSortedVisibleDatasetMetas();
  6061. for(let i = metasets.length - 1; i >= 0; --i){
  6062. this._drawDataset(metasets[i]);
  6063. }
  6064. this.notifyPlugins('afterDatasetsDraw');
  6065. }
  6066. _drawDataset(meta) {
  6067. const ctx = this.ctx;
  6068. const clip = meta._clip;
  6069. const useClip = !clip.disabled;
  6070. const area = getDatasetArea(meta, this.chartArea);
  6071. const args = {
  6072. meta,
  6073. index: meta.index,
  6074. cancelable: true
  6075. };
  6076. if (this.notifyPlugins('beforeDatasetDraw', args) === false) {
  6077. return;
  6078. }
  6079. if (useClip) {
  6080. helpers_segment.clipArea(ctx, {
  6081. left: clip.left === false ? 0 : area.left - clip.left,
  6082. right: clip.right === false ? this.width : area.right + clip.right,
  6083. top: clip.top === false ? 0 : area.top - clip.top,
  6084. bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom
  6085. });
  6086. }
  6087. meta.controller.draw();
  6088. if (useClip) {
  6089. helpers_segment.unclipArea(ctx);
  6090. }
  6091. args.cancelable = false;
  6092. this.notifyPlugins('afterDatasetDraw', args);
  6093. }
  6094. isPointInArea(point) {
  6095. return helpers_segment._isPointInArea(point, this.chartArea, this._minPadding);
  6096. }
  6097. getElementsAtEventForMode(e, mode, options, useFinalPosition) {
  6098. const method = Interaction.modes[mode];
  6099. if (typeof method === 'function') {
  6100. return method(this, e, options, useFinalPosition);
  6101. }
  6102. return [];
  6103. }
  6104. getDatasetMeta(datasetIndex) {
  6105. const dataset = this.data.datasets[datasetIndex];
  6106. const metasets = this._metasets;
  6107. let meta = metasets.filter((x)=>x && x._dataset === dataset).pop();
  6108. if (!meta) {
  6109. meta = {
  6110. type: null,
  6111. data: [],
  6112. dataset: null,
  6113. controller: null,
  6114. hidden: null,
  6115. xAxisID: null,
  6116. yAxisID: null,
  6117. order: dataset && dataset.order || 0,
  6118. index: datasetIndex,
  6119. _dataset: dataset,
  6120. _parsed: [],
  6121. _sorted: false
  6122. };
  6123. metasets.push(meta);
  6124. }
  6125. return meta;
  6126. }
  6127. getContext() {
  6128. return this.$context || (this.$context = helpers_segment.createContext(null, {
  6129. chart: this,
  6130. type: 'chart'
  6131. }));
  6132. }
  6133. getVisibleDatasetCount() {
  6134. return this.getSortedVisibleDatasetMetas().length;
  6135. }
  6136. isDatasetVisible(datasetIndex) {
  6137. const dataset = this.data.datasets[datasetIndex];
  6138. if (!dataset) {
  6139. return false;
  6140. }
  6141. const meta = this.getDatasetMeta(datasetIndex);
  6142. return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
  6143. }
  6144. setDatasetVisibility(datasetIndex, visible) {
  6145. const meta = this.getDatasetMeta(datasetIndex);
  6146. meta.hidden = !visible;
  6147. }
  6148. toggleDataVisibility(index) {
  6149. this._hiddenIndices[index] = !this._hiddenIndices[index];
  6150. }
  6151. getDataVisibility(index) {
  6152. return !this._hiddenIndices[index];
  6153. }
  6154. _updateVisibility(datasetIndex, dataIndex, visible) {
  6155. const mode = visible ? 'show' : 'hide';
  6156. const meta = this.getDatasetMeta(datasetIndex);
  6157. const anims = meta.controller._resolveAnimations(undefined, mode);
  6158. if (helpers_segment.defined(dataIndex)) {
  6159. meta.data[dataIndex].hidden = !visible;
  6160. this.update();
  6161. } else {
  6162. this.setDatasetVisibility(datasetIndex, visible);
  6163. anims.update(meta, {
  6164. visible
  6165. });
  6166. this.update((ctx)=>ctx.datasetIndex === datasetIndex ? mode : undefined);
  6167. }
  6168. }
  6169. hide(datasetIndex, dataIndex) {
  6170. this._updateVisibility(datasetIndex, dataIndex, false);
  6171. }
  6172. show(datasetIndex, dataIndex) {
  6173. this._updateVisibility(datasetIndex, dataIndex, true);
  6174. }
  6175. _destroyDatasetMeta(datasetIndex) {
  6176. const meta = this._metasets[datasetIndex];
  6177. if (meta && meta.controller) {
  6178. meta.controller._destroy();
  6179. }
  6180. delete this._metasets[datasetIndex];
  6181. }
  6182. _stop() {
  6183. let i, ilen;
  6184. this.stop();
  6185. animator.remove(this);
  6186. for(i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  6187. this._destroyDatasetMeta(i);
  6188. }
  6189. }
  6190. destroy() {
  6191. this.notifyPlugins('beforeDestroy');
  6192. const { canvas , ctx } = this;
  6193. this._stop();
  6194. this.config.clearCache();
  6195. if (canvas) {
  6196. this.unbindEvents();
  6197. helpers_segment.clearCanvas(canvas, ctx);
  6198. this.platform.releaseContext(ctx);
  6199. this.canvas = null;
  6200. this.ctx = null;
  6201. }
  6202. delete instances[this.id];
  6203. this.notifyPlugins('afterDestroy');
  6204. }
  6205. toBase64Image(...args) {
  6206. return this.canvas.toDataURL(...args);
  6207. }
  6208. bindEvents() {
  6209. this.bindUserEvents();
  6210. if (this.options.responsive) {
  6211. this.bindResponsiveEvents();
  6212. } else {
  6213. this.attached = true;
  6214. }
  6215. }
  6216. bindUserEvents() {
  6217. const listeners = this._listeners;
  6218. const platform = this.platform;
  6219. const _add = (type, listener)=>{
  6220. platform.addEventListener(this, type, listener);
  6221. listeners[type] = listener;
  6222. };
  6223. const listener = (e, x, y)=>{
  6224. e.offsetX = x;
  6225. e.offsetY = y;
  6226. this._eventHandler(e);
  6227. };
  6228. helpers_segment.each(this.options.events, (type)=>_add(type, listener));
  6229. }
  6230. bindResponsiveEvents() {
  6231. if (!this._responsiveListeners) {
  6232. this._responsiveListeners = {};
  6233. }
  6234. const listeners = this._responsiveListeners;
  6235. const platform = this.platform;
  6236. const _add = (type, listener)=>{
  6237. platform.addEventListener(this, type, listener);
  6238. listeners[type] = listener;
  6239. };
  6240. const _remove = (type, listener)=>{
  6241. if (listeners[type]) {
  6242. platform.removeEventListener(this, type, listener);
  6243. delete listeners[type];
  6244. }
  6245. };
  6246. const listener = (width, height)=>{
  6247. if (this.canvas) {
  6248. this.resize(width, height);
  6249. }
  6250. };
  6251. let detached;
  6252. const attached = ()=>{
  6253. _remove('attach', attached);
  6254. this.attached = true;
  6255. this.resize();
  6256. _add('resize', listener);
  6257. _add('detach', detached);
  6258. };
  6259. detached = ()=>{
  6260. this.attached = false;
  6261. _remove('resize', listener);
  6262. this._stop();
  6263. this._resize(0, 0);
  6264. _add('attach', attached);
  6265. };
  6266. if (platform.isAttached(this.canvas)) {
  6267. attached();
  6268. } else {
  6269. detached();
  6270. }
  6271. }
  6272. unbindEvents() {
  6273. helpers_segment.each(this._listeners, (listener, type)=>{
  6274. this.platform.removeEventListener(this, type, listener);
  6275. });
  6276. this._listeners = {};
  6277. helpers_segment.each(this._responsiveListeners, (listener, type)=>{
  6278. this.platform.removeEventListener(this, type, listener);
  6279. });
  6280. this._responsiveListeners = undefined;
  6281. }
  6282. updateHoverStyle(items, mode, enabled) {
  6283. const prefix = enabled ? 'set' : 'remove';
  6284. let meta, item, i, ilen;
  6285. if (mode === 'dataset') {
  6286. meta = this.getDatasetMeta(items[0].datasetIndex);
  6287. meta.controller['_' + prefix + 'DatasetHoverStyle']();
  6288. }
  6289. for(i = 0, ilen = items.length; i < ilen; ++i){
  6290. item = items[i];
  6291. const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
  6292. if (controller) {
  6293. controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
  6294. }
  6295. }
  6296. }
  6297. getActiveElements() {
  6298. return this._active || [];
  6299. }
  6300. setActiveElements(activeElements) {
  6301. const lastActive = this._active || [];
  6302. const active = activeElements.map(({ datasetIndex , index })=>{
  6303. const meta = this.getDatasetMeta(datasetIndex);
  6304. if (!meta) {
  6305. throw new Error('No dataset found at index ' + datasetIndex);
  6306. }
  6307. return {
  6308. datasetIndex,
  6309. element: meta.data[index],
  6310. index
  6311. };
  6312. });
  6313. const changed = !helpers_segment._elementsEqual(active, lastActive);
  6314. if (changed) {
  6315. this._active = active;
  6316. this._lastEvent = null;
  6317. this._updateHoverStyles(active, lastActive);
  6318. }
  6319. }
  6320. notifyPlugins(hook, args, filter) {
  6321. return this._plugins.notify(this, hook, args, filter);
  6322. }
  6323. isPluginEnabled(pluginId) {
  6324. return this._plugins._cache.filter((p)=>p.plugin.id === pluginId).length === 1;
  6325. }
  6326. _updateHoverStyles(active, lastActive, replay) {
  6327. const hoverOptions = this.options.hover;
  6328. const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.datasetIndex === y.datasetIndex && x.index === y.index));
  6329. const deactivated = diff(lastActive, active);
  6330. const activated = replay ? active : diff(active, lastActive);
  6331. if (deactivated.length) {
  6332. this.updateHoverStyle(deactivated, hoverOptions.mode, false);
  6333. }
  6334. if (activated.length && hoverOptions.mode) {
  6335. this.updateHoverStyle(activated, hoverOptions.mode, true);
  6336. }
  6337. }
  6338. _eventHandler(e, replay) {
  6339. const args = {
  6340. event: e,
  6341. replay,
  6342. cancelable: true,
  6343. inChartArea: this.isPointInArea(e)
  6344. };
  6345. const eventFilter = (plugin)=>(plugin.options.events || this.options.events).includes(e.native.type);
  6346. if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {
  6347. return;
  6348. }
  6349. const changed = this._handleEvent(e, replay, args.inChartArea);
  6350. args.cancelable = false;
  6351. this.notifyPlugins('afterEvent', args, eventFilter);
  6352. if (changed || args.changed) {
  6353. this.render();
  6354. }
  6355. return this;
  6356. }
  6357. _handleEvent(e, replay, inChartArea) {
  6358. const { _active: lastActive = [] , options } = this;
  6359. const useFinalPosition = replay;
  6360. const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);
  6361. const isClick = helpers_segment._isClickEvent(e);
  6362. const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);
  6363. if (inChartArea) {
  6364. this._lastEvent = null;
  6365. helpers_segment.callback(options.onHover, [
  6366. e,
  6367. active,
  6368. this
  6369. ], this);
  6370. if (isClick) {
  6371. helpers_segment.callback(options.onClick, [
  6372. e,
  6373. active,
  6374. this
  6375. ], this);
  6376. }
  6377. }
  6378. const changed = !helpers_segment._elementsEqual(active, lastActive);
  6379. if (changed || replay) {
  6380. this._active = active;
  6381. this._updateHoverStyles(active, lastActive, replay);
  6382. }
  6383. this._lastEvent = lastEvent;
  6384. return changed;
  6385. }
  6386. _getActiveElements(e, lastActive, inChartArea, useFinalPosition) {
  6387. if (e.type === 'mouseout') {
  6388. return [];
  6389. }
  6390. if (!inChartArea) {
  6391. return lastActive;
  6392. }
  6393. const hoverOptions = this.options.hover;
  6394. return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
  6395. }
  6396. }
  6397. function invalidatePlugins() {
  6398. return helpers_segment.each(Chart.instances, (chart)=>chart._plugins.invalidate());
  6399. }
  6400. function clipArc(ctx, element, endAngle) {
  6401. const { startAngle , pixelMargin , x , y , outerRadius , innerRadius } = element;
  6402. let angleMargin = pixelMargin / outerRadius;
  6403. // Draw an inner border by clipping the arc and drawing a double-width border
  6404. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  6405. ctx.beginPath();
  6406. ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  6407. if (innerRadius > pixelMargin) {
  6408. angleMargin = pixelMargin / innerRadius;
  6409. ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
  6410. } else {
  6411. ctx.arc(x, y, pixelMargin, endAngle + helpers_segment.HALF_PI, startAngle - helpers_segment.HALF_PI);
  6412. }
  6413. ctx.closePath();
  6414. ctx.clip();
  6415. }
  6416. function toRadiusCorners(value) {
  6417. return helpers_segment._readValueToProps(value, [
  6418. 'outerStart',
  6419. 'outerEnd',
  6420. 'innerStart',
  6421. 'innerEnd'
  6422. ]);
  6423. }
  6424. /**
  6425. * Parse border radius from the provided options
  6426. */ function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
  6427. const o = toRadiusCorners(arc.options.borderRadius);
  6428. const halfThickness = (outerRadius - innerRadius) / 2;
  6429. const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
  6430. // Outer limits are complicated. We want to compute the available angular distance at
  6431. // a radius of outerRadius - borderRadius because for small angular distances, this term limits.
  6432. // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners.
  6433. //
  6434. // If the borderRadius is large, that value can become negative.
  6435. // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius
  6436. // we know that the thickness term will dominate and compute the limits at that point
  6437. const computeOuterLimit = (val)=>{
  6438. const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
  6439. return helpers_segment._limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
  6440. };
  6441. return {
  6442. outerStart: computeOuterLimit(o.outerStart),
  6443. outerEnd: computeOuterLimit(o.outerEnd),
  6444. innerStart: helpers_segment._limitValue(o.innerStart, 0, innerLimit),
  6445. innerEnd: helpers_segment._limitValue(o.innerEnd, 0, innerLimit)
  6446. };
  6447. }
  6448. /**
  6449. * Convert (r, 𝜃) to (x, y)
  6450. */ function rThetaToXY(r, theta, x, y) {
  6451. return {
  6452. x: x + r * Math.cos(theta),
  6453. y: y + r * Math.sin(theta)
  6454. };
  6455. }
  6456. /**
  6457. * Path the arc, respecting border radius by separating into left and right halves.
  6458. *
  6459. * Start End
  6460. *
  6461. * 1--->a--->2 Outer
  6462. * / \
  6463. * 8 3
  6464. * | |
  6465. * | |
  6466. * 7 4
  6467. * \ /
  6468. * 6<---b<---5 Inner
  6469. */ function pathArc(ctx, element, offset, spacing, end, circular) {
  6470. const { x , y , startAngle: start , pixelMargin , innerRadius: innerR } = element;
  6471. const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);
  6472. const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;
  6473. let spacingOffset = 0;
  6474. const alpha = end - start;
  6475. if (spacing) {
  6476. // When spacing is present, it is the same for all items
  6477. // So we adjust the start and end angle of the arc such that
  6478. // the distance is the same as it would be without the spacing
  6479. const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;
  6480. const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;
  6481. const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;
  6482. const adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha;
  6483. spacingOffset = (alpha - adjustedAngle) / 2;
  6484. }
  6485. const beta = Math.max(0.001, alpha * outerRadius - offset / helpers_segment.PI) / outerRadius;
  6486. const angleOffset = (alpha - beta) / 2;
  6487. const startAngle = start + angleOffset + spacingOffset;
  6488. const endAngle = end - angleOffset - spacingOffset;
  6489. const { outerStart , outerEnd , innerStart , innerEnd } = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
  6490. const outerStartAdjustedRadius = outerRadius - outerStart;
  6491. const outerEndAdjustedRadius = outerRadius - outerEnd;
  6492. const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
  6493. const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
  6494. const innerStartAdjustedRadius = innerRadius + innerStart;
  6495. const innerEndAdjustedRadius = innerRadius + innerEnd;
  6496. const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
  6497. const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
  6498. ctx.beginPath();
  6499. if (circular) {
  6500. // The first arc segments from point 1 to point a to point 2
  6501. const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2;
  6502. ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle);
  6503. ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle);
  6504. // The corner segment from point 2 to point 3
  6505. if (outerEnd > 0) {
  6506. const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
  6507. ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + helpers_segment.HALF_PI);
  6508. }
  6509. // The line from point 3 to point 4
  6510. const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
  6511. ctx.lineTo(p4.x, p4.y);
  6512. // The corner segment from point 4 to point 5
  6513. if (innerEnd > 0) {
  6514. const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
  6515. ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + helpers_segment.HALF_PI, innerEndAdjustedAngle + Math.PI);
  6516. }
  6517. // The inner arc from point 5 to point b to point 6
  6518. const innerMidAdjustedAngle = (endAngle - innerEnd / innerRadius + (startAngle + innerStart / innerRadius)) / 2;
  6519. ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, innerMidAdjustedAngle, true);
  6520. ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + innerStart / innerRadius, true);
  6521. // The corner segment from point 6 to point 7
  6522. if (innerStart > 0) {
  6523. const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
  6524. ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - helpers_segment.HALF_PI);
  6525. }
  6526. // The line from point 7 to point 8
  6527. const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
  6528. ctx.lineTo(p8.x, p8.y);
  6529. // The corner segment from point 8 to point 1
  6530. if (outerStart > 0) {
  6531. const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
  6532. ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - helpers_segment.HALF_PI, outerStartAdjustedAngle);
  6533. }
  6534. } else {
  6535. ctx.moveTo(x, y);
  6536. const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x;
  6537. const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y;
  6538. ctx.lineTo(outerStartX, outerStartY);
  6539. const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x;
  6540. const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y;
  6541. ctx.lineTo(outerEndX, outerEndY);
  6542. }
  6543. ctx.closePath();
  6544. }
  6545. function drawArc(ctx, element, offset, spacing, circular) {
  6546. const { fullCircles , startAngle , circumference } = element;
  6547. let endAngle = element.endAngle;
  6548. if (fullCircles) {
  6549. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6550. for(let i = 0; i < fullCircles; ++i){
  6551. ctx.fill();
  6552. }
  6553. if (!isNaN(circumference)) {
  6554. endAngle = startAngle + (circumference % helpers_segment.TAU || helpers_segment.TAU);
  6555. }
  6556. }
  6557. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6558. ctx.fill();
  6559. return endAngle;
  6560. }
  6561. function drawBorder(ctx, element, offset, spacing, circular) {
  6562. const { fullCircles , startAngle , circumference , options } = element;
  6563. const { borderWidth , borderJoinStyle , borderDash , borderDashOffset } = options;
  6564. const inner = options.borderAlign === 'inner';
  6565. if (!borderWidth) {
  6566. return;
  6567. }
  6568. ctx.setLineDash(borderDash || []);
  6569. ctx.lineDashOffset = borderDashOffset;
  6570. if (inner) {
  6571. ctx.lineWidth = borderWidth * 2;
  6572. ctx.lineJoin = borderJoinStyle || 'round';
  6573. } else {
  6574. ctx.lineWidth = borderWidth;
  6575. ctx.lineJoin = borderJoinStyle || 'bevel';
  6576. }
  6577. let endAngle = element.endAngle;
  6578. if (fullCircles) {
  6579. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6580. for(let i = 0; i < fullCircles; ++i){
  6581. ctx.stroke();
  6582. }
  6583. if (!isNaN(circumference)) {
  6584. endAngle = startAngle + (circumference % helpers_segment.TAU || helpers_segment.TAU);
  6585. }
  6586. }
  6587. if (inner) {
  6588. clipArc(ctx, element, endAngle);
  6589. }
  6590. if (!fullCircles) {
  6591. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6592. ctx.stroke();
  6593. }
  6594. }
  6595. class ArcElement extends Element {
  6596. static id = 'arc';
  6597. static defaults = {
  6598. borderAlign: 'center',
  6599. borderColor: '#fff',
  6600. borderDash: [],
  6601. borderDashOffset: 0,
  6602. borderJoinStyle: undefined,
  6603. borderRadius: 0,
  6604. borderWidth: 2,
  6605. offset: 0,
  6606. spacing: 0,
  6607. angle: undefined,
  6608. circular: true
  6609. };
  6610. static defaultRoutes = {
  6611. backgroundColor: 'backgroundColor'
  6612. };
  6613. static descriptors = {
  6614. _scriptable: true,
  6615. _indexable: (name)=>name !== 'borderDash'
  6616. };
  6617. circumference;
  6618. endAngle;
  6619. fullCircles;
  6620. innerRadius;
  6621. outerRadius;
  6622. pixelMargin;
  6623. startAngle;
  6624. constructor(cfg){
  6625. super();
  6626. this.options = undefined;
  6627. this.circumference = undefined;
  6628. this.startAngle = undefined;
  6629. this.endAngle = undefined;
  6630. this.innerRadius = undefined;
  6631. this.outerRadius = undefined;
  6632. this.pixelMargin = 0;
  6633. this.fullCircles = 0;
  6634. if (cfg) {
  6635. Object.assign(this, cfg);
  6636. }
  6637. }
  6638. inRange(chartX, chartY, useFinalPosition) {
  6639. const point = this.getProps([
  6640. 'x',
  6641. 'y'
  6642. ], useFinalPosition);
  6643. const { angle , distance } = helpers_segment.getAngleFromPoint(point, {
  6644. x: chartX,
  6645. y: chartY
  6646. });
  6647. const { startAngle , endAngle , innerRadius , outerRadius , circumference } = this.getProps([
  6648. 'startAngle',
  6649. 'endAngle',
  6650. 'innerRadius',
  6651. 'outerRadius',
  6652. 'circumference'
  6653. ], useFinalPosition);
  6654. const rAdjust = (this.options.spacing + this.options.borderWidth) / 2;
  6655. const _circumference = helpers_segment.valueOrDefault(circumference, endAngle - startAngle);
  6656. const betweenAngles = _circumference >= helpers_segment.TAU || helpers_segment._angleBetween(angle, startAngle, endAngle);
  6657. const withinRadius = helpers_segment._isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust);
  6658. return betweenAngles && withinRadius;
  6659. }
  6660. getCenterPoint(useFinalPosition) {
  6661. const { x , y , startAngle , endAngle , innerRadius , outerRadius } = this.getProps([
  6662. 'x',
  6663. 'y',
  6664. 'startAngle',
  6665. 'endAngle',
  6666. 'innerRadius',
  6667. 'outerRadius'
  6668. ], useFinalPosition);
  6669. const { offset , spacing } = this.options;
  6670. const halfAngle = (startAngle + endAngle) / 2;
  6671. const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;
  6672. return {
  6673. x: x + Math.cos(halfAngle) * halfRadius,
  6674. y: y + Math.sin(halfAngle) * halfRadius
  6675. };
  6676. }
  6677. tooltipPosition(useFinalPosition) {
  6678. return this.getCenterPoint(useFinalPosition);
  6679. }
  6680. draw(ctx) {
  6681. const { options , circumference } = this;
  6682. const offset = (options.offset || 0) / 4;
  6683. const spacing = (options.spacing || 0) / 2;
  6684. const circular = options.circular;
  6685. this.pixelMargin = options.borderAlign === 'inner' ? 0.33 : 0;
  6686. this.fullCircles = circumference > helpers_segment.TAU ? Math.floor(circumference / helpers_segment.TAU) : 0;
  6687. if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) {
  6688. return;
  6689. }
  6690. ctx.save();
  6691. const halfAngle = (this.startAngle + this.endAngle) / 2;
  6692. ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset);
  6693. const fix = 1 - Math.sin(Math.min(helpers_segment.PI, circumference || 0));
  6694. const radiusOffset = offset * fix;
  6695. ctx.fillStyle = options.backgroundColor;
  6696. ctx.strokeStyle = options.borderColor;
  6697. drawArc(ctx, this, radiusOffset, spacing, circular);
  6698. drawBorder(ctx, this, radiusOffset, spacing, circular);
  6699. ctx.restore();
  6700. }
  6701. }
  6702. function setStyle(ctx, options, style = options) {
  6703. ctx.lineCap = helpers_segment.valueOrDefault(style.borderCapStyle, options.borderCapStyle);
  6704. ctx.setLineDash(helpers_segment.valueOrDefault(style.borderDash, options.borderDash));
  6705. ctx.lineDashOffset = helpers_segment.valueOrDefault(style.borderDashOffset, options.borderDashOffset);
  6706. ctx.lineJoin = helpers_segment.valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
  6707. ctx.lineWidth = helpers_segment.valueOrDefault(style.borderWidth, options.borderWidth);
  6708. ctx.strokeStyle = helpers_segment.valueOrDefault(style.borderColor, options.borderColor);
  6709. }
  6710. function lineTo(ctx, previous, target) {
  6711. ctx.lineTo(target.x, target.y);
  6712. }
  6713. function getLineMethod(options) {
  6714. if (options.stepped) {
  6715. return helpers_segment._steppedLineTo;
  6716. }
  6717. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6718. return helpers_segment._bezierCurveTo;
  6719. }
  6720. return lineTo;
  6721. }
  6722. function pathVars(points, segment, params = {}) {
  6723. const count = points.length;
  6724. const { start: paramsStart = 0 , end: paramsEnd = count - 1 } = params;
  6725. const { start: segmentStart , end: segmentEnd } = segment;
  6726. const start = Math.max(paramsStart, segmentStart);
  6727. const end = Math.min(paramsEnd, segmentEnd);
  6728. const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
  6729. return {
  6730. count,
  6731. start,
  6732. loop: segment.loop,
  6733. ilen: end < start && !outside ? count + end - start : end - start
  6734. };
  6735. }
  6736. function pathSegment(ctx, line, segment, params) {
  6737. const { points , options } = line;
  6738. const { count , start , loop , ilen } = pathVars(points, segment, params);
  6739. const lineMethod = getLineMethod(options);
  6740. let { move =true , reverse } = params || {};
  6741. let i, point, prev;
  6742. for(i = 0; i <= ilen; ++i){
  6743. point = points[(start + (reverse ? ilen - i : i)) % count];
  6744. if (point.skip) {
  6745. continue;
  6746. } else if (move) {
  6747. ctx.moveTo(point.x, point.y);
  6748. move = false;
  6749. } else {
  6750. lineMethod(ctx, prev, point, reverse, options.stepped);
  6751. }
  6752. prev = point;
  6753. }
  6754. if (loop) {
  6755. point = points[(start + (reverse ? ilen : 0)) % count];
  6756. lineMethod(ctx, prev, point, reverse, options.stepped);
  6757. }
  6758. return !!loop;
  6759. }
  6760. function fastPathSegment(ctx, line, segment, params) {
  6761. const points = line.points;
  6762. const { count , start , ilen } = pathVars(points, segment, params);
  6763. const { move =true , reverse } = params || {};
  6764. let avgX = 0;
  6765. let countX = 0;
  6766. let i, point, prevX, minY, maxY, lastY;
  6767. const pointIndex = (index)=>(start + (reverse ? ilen - index : index)) % count;
  6768. const drawX = ()=>{
  6769. if (minY !== maxY) {
  6770. ctx.lineTo(avgX, maxY);
  6771. ctx.lineTo(avgX, minY);
  6772. ctx.lineTo(avgX, lastY);
  6773. }
  6774. };
  6775. if (move) {
  6776. point = points[pointIndex(0)];
  6777. ctx.moveTo(point.x, point.y);
  6778. }
  6779. for(i = 0; i <= ilen; ++i){
  6780. point = points[pointIndex(i)];
  6781. if (point.skip) {
  6782. continue;
  6783. }
  6784. const x = point.x;
  6785. const y = point.y;
  6786. const truncX = x | 0;
  6787. if (truncX === prevX) {
  6788. if (y < minY) {
  6789. minY = y;
  6790. } else if (y > maxY) {
  6791. maxY = y;
  6792. }
  6793. avgX = (countX * avgX + x) / ++countX;
  6794. } else {
  6795. drawX();
  6796. ctx.lineTo(x, y);
  6797. prevX = truncX;
  6798. countX = 0;
  6799. minY = maxY = y;
  6800. }
  6801. lastY = y;
  6802. }
  6803. drawX();
  6804. }
  6805. function _getSegmentMethod(line) {
  6806. const opts = line.options;
  6807. const borderDash = opts.borderDash && opts.borderDash.length;
  6808. const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
  6809. return useFastPath ? fastPathSegment : pathSegment;
  6810. }
  6811. function _getInterpolationMethod(options) {
  6812. if (options.stepped) {
  6813. return helpers_segment._steppedInterpolation;
  6814. }
  6815. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6816. return helpers_segment._bezierInterpolation;
  6817. }
  6818. return helpers_segment._pointInLine;
  6819. }
  6820. function strokePathWithCache(ctx, line, start, count) {
  6821. let path = line._path;
  6822. if (!path) {
  6823. path = line._path = new Path2D();
  6824. if (line.path(path, start, count)) {
  6825. path.closePath();
  6826. }
  6827. }
  6828. setStyle(ctx, line.options);
  6829. ctx.stroke(path);
  6830. }
  6831. function strokePathDirect(ctx, line, start, count) {
  6832. const { segments , options } = line;
  6833. const segmentMethod = _getSegmentMethod(line);
  6834. for (const segment of segments){
  6835. setStyle(ctx, options, segment.style);
  6836. ctx.beginPath();
  6837. if (segmentMethod(ctx, line, segment, {
  6838. start,
  6839. end: start + count - 1
  6840. })) {
  6841. ctx.closePath();
  6842. }
  6843. ctx.stroke();
  6844. }
  6845. }
  6846. const usePath2D = typeof Path2D === 'function';
  6847. function draw(ctx, line, start, count) {
  6848. if (usePath2D && !line.options.segment) {
  6849. strokePathWithCache(ctx, line, start, count);
  6850. } else {
  6851. strokePathDirect(ctx, line, start, count);
  6852. }
  6853. }
  6854. class LineElement extends Element {
  6855. static id = 'line';
  6856. static defaults = {
  6857. borderCapStyle: 'butt',
  6858. borderDash: [],
  6859. borderDashOffset: 0,
  6860. borderJoinStyle: 'miter',
  6861. borderWidth: 3,
  6862. capBezierPoints: true,
  6863. cubicInterpolationMode: 'default',
  6864. fill: false,
  6865. spanGaps: false,
  6866. stepped: false,
  6867. tension: 0
  6868. };
  6869. static defaultRoutes = {
  6870. backgroundColor: 'backgroundColor',
  6871. borderColor: 'borderColor'
  6872. };
  6873. static descriptors = {
  6874. _scriptable: true,
  6875. _indexable: (name)=>name !== 'borderDash' && name !== 'fill'
  6876. };
  6877. constructor(cfg){
  6878. super();
  6879. this.animated = true;
  6880. this.options = undefined;
  6881. this._chart = undefined;
  6882. this._loop = undefined;
  6883. this._fullLoop = undefined;
  6884. this._path = undefined;
  6885. this._points = undefined;
  6886. this._segments = undefined;
  6887. this._decimated = false;
  6888. this._pointsUpdated = false;
  6889. this._datasetIndex = undefined;
  6890. if (cfg) {
  6891. Object.assign(this, cfg);
  6892. }
  6893. }
  6894. updateControlPoints(chartArea, indexAxis) {
  6895. const options = this.options;
  6896. if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) {
  6897. const loop = options.spanGaps ? this._loop : this._fullLoop;
  6898. helpers_segment._updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis);
  6899. this._pointsUpdated = true;
  6900. }
  6901. }
  6902. set points(points) {
  6903. this._points = points;
  6904. delete this._segments;
  6905. delete this._path;
  6906. this._pointsUpdated = false;
  6907. }
  6908. get points() {
  6909. return this._points;
  6910. }
  6911. get segments() {
  6912. return this._segments || (this._segments = helpers_segment._computeSegments(this, this.options.segment));
  6913. }
  6914. first() {
  6915. const segments = this.segments;
  6916. const points = this.points;
  6917. return segments.length && points[segments[0].start];
  6918. }
  6919. last() {
  6920. const segments = this.segments;
  6921. const points = this.points;
  6922. const count = segments.length;
  6923. return count && points[segments[count - 1].end];
  6924. }
  6925. interpolate(point, property) {
  6926. const options = this.options;
  6927. const value = point[property];
  6928. const points = this.points;
  6929. const segments = helpers_segment._boundSegments(this, {
  6930. property,
  6931. start: value,
  6932. end: value
  6933. });
  6934. if (!segments.length) {
  6935. return;
  6936. }
  6937. const result = [];
  6938. const _interpolate = _getInterpolationMethod(options);
  6939. let i, ilen;
  6940. for(i = 0, ilen = segments.length; i < ilen; ++i){
  6941. const { start , end } = segments[i];
  6942. const p1 = points[start];
  6943. const p2 = points[end];
  6944. if (p1 === p2) {
  6945. result.push(p1);
  6946. continue;
  6947. }
  6948. const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
  6949. const interpolated = _interpolate(p1, p2, t, options.stepped);
  6950. interpolated[property] = point[property];
  6951. result.push(interpolated);
  6952. }
  6953. return result.length === 1 ? result[0] : result;
  6954. }
  6955. pathSegment(ctx, segment, params) {
  6956. const segmentMethod = _getSegmentMethod(this);
  6957. return segmentMethod(ctx, this, segment, params);
  6958. }
  6959. path(ctx, start, count) {
  6960. const segments = this.segments;
  6961. const segmentMethod = _getSegmentMethod(this);
  6962. let loop = this._loop;
  6963. start = start || 0;
  6964. count = count || this.points.length - start;
  6965. for (const segment of segments){
  6966. loop &= segmentMethod(ctx, this, segment, {
  6967. start,
  6968. end: start + count - 1
  6969. });
  6970. }
  6971. return !!loop;
  6972. }
  6973. draw(ctx, chartArea, start, count) {
  6974. const options = this.options || {};
  6975. const points = this.points || [];
  6976. if (points.length && options.borderWidth) {
  6977. ctx.save();
  6978. draw(ctx, this, start, count);
  6979. ctx.restore();
  6980. }
  6981. if (this.animated) {
  6982. this._pointsUpdated = false;
  6983. this._path = undefined;
  6984. }
  6985. }
  6986. }
  6987. function inRange$1(el, pos, axis, useFinalPosition) {
  6988. const options = el.options;
  6989. const { [axis]: value } = el.getProps([
  6990. axis
  6991. ], useFinalPosition);
  6992. return Math.abs(pos - value) < options.radius + options.hitRadius;
  6993. }
  6994. class PointElement extends Element {
  6995. static id = 'point';
  6996. parsed;
  6997. skip;
  6998. stop;
  6999. /**
  7000. * @type {any}
  7001. */ static defaults = {
  7002. borderWidth: 1,
  7003. hitRadius: 1,
  7004. hoverBorderWidth: 1,
  7005. hoverRadius: 4,
  7006. pointStyle: 'circle',
  7007. radius: 3,
  7008. rotation: 0
  7009. };
  7010. /**
  7011. * @type {any}
  7012. */ static defaultRoutes = {
  7013. backgroundColor: 'backgroundColor',
  7014. borderColor: 'borderColor'
  7015. };
  7016. constructor(cfg){
  7017. super();
  7018. this.options = undefined;
  7019. this.parsed = undefined;
  7020. this.skip = undefined;
  7021. this.stop = undefined;
  7022. if (cfg) {
  7023. Object.assign(this, cfg);
  7024. }
  7025. }
  7026. inRange(mouseX, mouseY, useFinalPosition) {
  7027. const options = this.options;
  7028. const { x , y } = this.getProps([
  7029. 'x',
  7030. 'y'
  7031. ], useFinalPosition);
  7032. return Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2) < Math.pow(options.hitRadius + options.radius, 2);
  7033. }
  7034. inXRange(mouseX, useFinalPosition) {
  7035. return inRange$1(this, mouseX, 'x', useFinalPosition);
  7036. }
  7037. inYRange(mouseY, useFinalPosition) {
  7038. return inRange$1(this, mouseY, 'y', useFinalPosition);
  7039. }
  7040. getCenterPoint(useFinalPosition) {
  7041. const { x , y } = this.getProps([
  7042. 'x',
  7043. 'y'
  7044. ], useFinalPosition);
  7045. return {
  7046. x,
  7047. y
  7048. };
  7049. }
  7050. size(options) {
  7051. options = options || this.options || {};
  7052. let radius = options.radius || 0;
  7053. radius = Math.max(radius, radius && options.hoverRadius || 0);
  7054. const borderWidth = radius && options.borderWidth || 0;
  7055. return (radius + borderWidth) * 2;
  7056. }
  7057. draw(ctx, area) {
  7058. const options = this.options;
  7059. if (this.skip || options.radius < 0.1 || !helpers_segment._isPointInArea(this, area, this.size(options) / 2)) {
  7060. return;
  7061. }
  7062. ctx.strokeStyle = options.borderColor;
  7063. ctx.lineWidth = options.borderWidth;
  7064. ctx.fillStyle = options.backgroundColor;
  7065. helpers_segment.drawPoint(ctx, options, this.x, this.y);
  7066. }
  7067. getRange() {
  7068. const options = this.options || {};
  7069. // @ts-expect-error Fallbacks should never be hit in practice
  7070. return options.radius + options.hitRadius;
  7071. }
  7072. }
  7073. function getBarBounds(bar, useFinalPosition) {
  7074. const { x , y , base , width , height } = bar.getProps([
  7075. 'x',
  7076. 'y',
  7077. 'base',
  7078. 'width',
  7079. 'height'
  7080. ], useFinalPosition);
  7081. let left, right, top, bottom, half;
  7082. if (bar.horizontal) {
  7083. half = height / 2;
  7084. left = Math.min(x, base);
  7085. right = Math.max(x, base);
  7086. top = y - half;
  7087. bottom = y + half;
  7088. } else {
  7089. half = width / 2;
  7090. left = x - half;
  7091. right = x + half;
  7092. top = Math.min(y, base);
  7093. bottom = Math.max(y, base);
  7094. }
  7095. return {
  7096. left,
  7097. top,
  7098. right,
  7099. bottom
  7100. };
  7101. }
  7102. function skipOrLimit(skip, value, min, max) {
  7103. return skip ? 0 : helpers_segment._limitValue(value, min, max);
  7104. }
  7105. function parseBorderWidth(bar, maxW, maxH) {
  7106. const value = bar.options.borderWidth;
  7107. const skip = bar.borderSkipped;
  7108. const o = helpers_segment.toTRBL(value);
  7109. return {
  7110. t: skipOrLimit(skip.top, o.top, 0, maxH),
  7111. r: skipOrLimit(skip.right, o.right, 0, maxW),
  7112. b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
  7113. l: skipOrLimit(skip.left, o.left, 0, maxW)
  7114. };
  7115. }
  7116. function parseBorderRadius(bar, maxW, maxH) {
  7117. const { enableBorderRadius } = bar.getProps([
  7118. 'enableBorderRadius'
  7119. ]);
  7120. const value = bar.options.borderRadius;
  7121. const o = helpers_segment.toTRBLCorners(value);
  7122. const maxR = Math.min(maxW, maxH);
  7123. const skip = bar.borderSkipped;
  7124. const enableBorder = enableBorderRadius || helpers_segment.isObject(value);
  7125. return {
  7126. topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
  7127. topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
  7128. bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
  7129. bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
  7130. };
  7131. }
  7132. function boundingRects(bar) {
  7133. const bounds = getBarBounds(bar);
  7134. const width = bounds.right - bounds.left;
  7135. const height = bounds.bottom - bounds.top;
  7136. const border = parseBorderWidth(bar, width / 2, height / 2);
  7137. const radius = parseBorderRadius(bar, width / 2, height / 2);
  7138. return {
  7139. outer: {
  7140. x: bounds.left,
  7141. y: bounds.top,
  7142. w: width,
  7143. h: height,
  7144. radius
  7145. },
  7146. inner: {
  7147. x: bounds.left + border.l,
  7148. y: bounds.top + border.t,
  7149. w: width - border.l - border.r,
  7150. h: height - border.t - border.b,
  7151. radius: {
  7152. topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
  7153. topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
  7154. bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
  7155. bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r))
  7156. }
  7157. }
  7158. };
  7159. }
  7160. function inRange(bar, x, y, useFinalPosition) {
  7161. const skipX = x === null;
  7162. const skipY = y === null;
  7163. const skipBoth = skipX && skipY;
  7164. const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
  7165. return bounds && (skipX || helpers_segment._isBetween(x, bounds.left, bounds.right)) && (skipY || helpers_segment._isBetween(y, bounds.top, bounds.bottom));
  7166. }
  7167. function hasRadius(radius) {
  7168. return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
  7169. }
  7170. function addNormalRectPath(ctx, rect) {
  7171. ctx.rect(rect.x, rect.y, rect.w, rect.h);
  7172. }
  7173. function inflateRect(rect, amount, refRect = {}) {
  7174. const x = rect.x !== refRect.x ? -amount : 0;
  7175. const y = rect.y !== refRect.y ? -amount : 0;
  7176. const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;
  7177. const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;
  7178. return {
  7179. x: rect.x + x,
  7180. y: rect.y + y,
  7181. w: rect.w + w,
  7182. h: rect.h + h,
  7183. radius: rect.radius
  7184. };
  7185. }
  7186. class BarElement extends Element {
  7187. static id = 'bar';
  7188. static defaults = {
  7189. borderSkipped: 'start',
  7190. borderWidth: 0,
  7191. borderRadius: 0,
  7192. inflateAmount: 'auto',
  7193. pointStyle: undefined
  7194. };
  7195. static defaultRoutes = {
  7196. backgroundColor: 'backgroundColor',
  7197. borderColor: 'borderColor'
  7198. };
  7199. constructor(cfg){
  7200. super();
  7201. this.options = undefined;
  7202. this.horizontal = undefined;
  7203. this.base = undefined;
  7204. this.width = undefined;
  7205. this.height = undefined;
  7206. this.inflateAmount = undefined;
  7207. if (cfg) {
  7208. Object.assign(this, cfg);
  7209. }
  7210. }
  7211. draw(ctx) {
  7212. const { inflateAmount , options: { borderColor , backgroundColor } } = this;
  7213. const { inner , outer } = boundingRects(this);
  7214. const addRectPath = hasRadius(outer.radius) ? helpers_segment.addRoundedRectPath : addNormalRectPath;
  7215. ctx.save();
  7216. if (outer.w !== inner.w || outer.h !== inner.h) {
  7217. ctx.beginPath();
  7218. addRectPath(ctx, inflateRect(outer, inflateAmount, inner));
  7219. ctx.clip();
  7220. addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));
  7221. ctx.fillStyle = borderColor;
  7222. ctx.fill('evenodd');
  7223. }
  7224. ctx.beginPath();
  7225. addRectPath(ctx, inflateRect(inner, inflateAmount));
  7226. ctx.fillStyle = backgroundColor;
  7227. ctx.fill();
  7228. ctx.restore();
  7229. }
  7230. inRange(mouseX, mouseY, useFinalPosition) {
  7231. return inRange(this, mouseX, mouseY, useFinalPosition);
  7232. }
  7233. inXRange(mouseX, useFinalPosition) {
  7234. return inRange(this, mouseX, null, useFinalPosition);
  7235. }
  7236. inYRange(mouseY, useFinalPosition) {
  7237. return inRange(this, null, mouseY, useFinalPosition);
  7238. }
  7239. getCenterPoint(useFinalPosition) {
  7240. const { x , y , base , horizontal } = this.getProps([
  7241. 'x',
  7242. 'y',
  7243. 'base',
  7244. 'horizontal'
  7245. ], useFinalPosition);
  7246. return {
  7247. x: horizontal ? (x + base) / 2 : x,
  7248. y: horizontal ? y : (y + base) / 2
  7249. };
  7250. }
  7251. getRange(axis) {
  7252. return axis === 'x' ? this.width / 2 : this.height / 2;
  7253. }
  7254. }
  7255. var elements = /*#__PURE__*/Object.freeze({
  7256. __proto__: null,
  7257. ArcElement: ArcElement,
  7258. BarElement: BarElement,
  7259. LineElement: LineElement,
  7260. PointElement: PointElement
  7261. });
  7262. const BORDER_COLORS = [
  7263. 'rgb(54, 162, 235)',
  7264. 'rgb(255, 99, 132)',
  7265. 'rgb(255, 159, 64)',
  7266. 'rgb(255, 205, 86)',
  7267. 'rgb(75, 192, 192)',
  7268. 'rgb(153, 102, 255)',
  7269. 'rgb(201, 203, 207)' // grey
  7270. ];
  7271. // Border colors with 50% transparency
  7272. const BACKGROUND_COLORS = /* #__PURE__ */ BORDER_COLORS.map((color)=>color.replace('rgb(', 'rgba(').replace(')', ', 0.5)'));
  7273. function getBorderColor(i) {
  7274. return BORDER_COLORS[i % BORDER_COLORS.length];
  7275. }
  7276. function getBackgroundColor(i) {
  7277. return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length];
  7278. }
  7279. function colorizeDefaultDataset(dataset, i) {
  7280. dataset.borderColor = getBorderColor(i);
  7281. dataset.backgroundColor = getBackgroundColor(i);
  7282. return ++i;
  7283. }
  7284. function colorizeDoughnutDataset(dataset, i) {
  7285. dataset.backgroundColor = dataset.data.map(()=>getBorderColor(i++));
  7286. return i;
  7287. }
  7288. function colorizePolarAreaDataset(dataset, i) {
  7289. dataset.backgroundColor = dataset.data.map(()=>getBackgroundColor(i++));
  7290. return i;
  7291. }
  7292. function getColorizer(chart) {
  7293. let i = 0;
  7294. return (dataset, datasetIndex)=>{
  7295. const controller = chart.getDatasetMeta(datasetIndex).controller;
  7296. if (controller instanceof DoughnutController) {
  7297. i = colorizeDoughnutDataset(dataset, i);
  7298. } else if (controller instanceof PolarAreaController) {
  7299. i = colorizePolarAreaDataset(dataset, i);
  7300. } else if (controller) {
  7301. i = colorizeDefaultDataset(dataset, i);
  7302. }
  7303. };
  7304. }
  7305. function containsColorsDefinitions(descriptors) {
  7306. let k;
  7307. for(k in descriptors){
  7308. if (descriptors[k].borderColor || descriptors[k].backgroundColor) {
  7309. return true;
  7310. }
  7311. }
  7312. return false;
  7313. }
  7314. function containsColorsDefinition(descriptor) {
  7315. return descriptor && (descriptor.borderColor || descriptor.backgroundColor);
  7316. }
  7317. var plugin_colors = {
  7318. id: 'colors',
  7319. defaults: {
  7320. enabled: true,
  7321. forceOverride: false
  7322. },
  7323. beforeLayout (chart, _args, options) {
  7324. if (!options.enabled) {
  7325. return;
  7326. }
  7327. const { data: { datasets } , options: chartOptions } = chart.config;
  7328. const { elements } = chartOptions;
  7329. if (!options.forceOverride && (containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || elements && containsColorsDefinitions(elements))) {
  7330. return;
  7331. }
  7332. const colorizer = getColorizer(chart);
  7333. datasets.forEach(colorizer);
  7334. }
  7335. };
  7336. function lttbDecimation(data, start, count, availableWidth, options) {
  7337. const samples = options.samples || availableWidth;
  7338. if (samples >= count) {
  7339. return data.slice(start, start + count);
  7340. }
  7341. const decimated = [];
  7342. const bucketWidth = (count - 2) / (samples - 2);
  7343. let sampledIndex = 0;
  7344. const endIndex = start + count - 1;
  7345. let a = start;
  7346. let i, maxAreaPoint, maxArea, area, nextA;
  7347. decimated[sampledIndex++] = data[a];
  7348. for(i = 0; i < samples - 2; i++){
  7349. let avgX = 0;
  7350. let avgY = 0;
  7351. let j;
  7352. const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
  7353. const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
  7354. const avgRangeLength = avgRangeEnd - avgRangeStart;
  7355. for(j = avgRangeStart; j < avgRangeEnd; j++){
  7356. avgX += data[j].x;
  7357. avgY += data[j].y;
  7358. }
  7359. avgX /= avgRangeLength;
  7360. avgY /= avgRangeLength;
  7361. const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
  7362. const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;
  7363. const { x: pointAx , y: pointAy } = data[a];
  7364. maxArea = area = -1;
  7365. for(j = rangeOffs; j < rangeTo; j++){
  7366. area = 0.5 * Math.abs((pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy));
  7367. if (area > maxArea) {
  7368. maxArea = area;
  7369. maxAreaPoint = data[j];
  7370. nextA = j;
  7371. }
  7372. }
  7373. decimated[sampledIndex++] = maxAreaPoint;
  7374. a = nextA;
  7375. }
  7376. decimated[sampledIndex++] = data[endIndex];
  7377. return decimated;
  7378. }
  7379. function minMaxDecimation(data, start, count, availableWidth) {
  7380. let avgX = 0;
  7381. let countX = 0;
  7382. let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
  7383. const decimated = [];
  7384. const endIndex = start + count - 1;
  7385. const xMin = data[start].x;
  7386. const xMax = data[endIndex].x;
  7387. const dx = xMax - xMin;
  7388. for(i = start; i < start + count; ++i){
  7389. point = data[i];
  7390. x = (point.x - xMin) / dx * availableWidth;
  7391. y = point.y;
  7392. const truncX = x | 0;
  7393. if (truncX === prevX) {
  7394. if (y < minY) {
  7395. minY = y;
  7396. minIndex = i;
  7397. } else if (y > maxY) {
  7398. maxY = y;
  7399. maxIndex = i;
  7400. }
  7401. avgX = (countX * avgX + point.x) / ++countX;
  7402. } else {
  7403. const lastIndex = i - 1;
  7404. if (!helpers_segment.isNullOrUndef(minIndex) && !helpers_segment.isNullOrUndef(maxIndex)) {
  7405. const intermediateIndex1 = Math.min(minIndex, maxIndex);
  7406. const intermediateIndex2 = Math.max(minIndex, maxIndex);
  7407. if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
  7408. decimated.push({
  7409. ...data[intermediateIndex1],
  7410. x: avgX
  7411. });
  7412. }
  7413. if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
  7414. decimated.push({
  7415. ...data[intermediateIndex2],
  7416. x: avgX
  7417. });
  7418. }
  7419. }
  7420. if (i > 0 && lastIndex !== startIndex) {
  7421. decimated.push(data[lastIndex]);
  7422. }
  7423. decimated.push(point);
  7424. prevX = truncX;
  7425. countX = 0;
  7426. minY = maxY = y;
  7427. minIndex = maxIndex = startIndex = i;
  7428. }
  7429. }
  7430. return decimated;
  7431. }
  7432. function cleanDecimatedDataset(dataset) {
  7433. if (dataset._decimated) {
  7434. const data = dataset._data;
  7435. delete dataset._decimated;
  7436. delete dataset._data;
  7437. Object.defineProperty(dataset, 'data', {
  7438. configurable: true,
  7439. enumerable: true,
  7440. writable: true,
  7441. value: data
  7442. });
  7443. }
  7444. }
  7445. function cleanDecimatedData(chart) {
  7446. chart.data.datasets.forEach((dataset)=>{
  7447. cleanDecimatedDataset(dataset);
  7448. });
  7449. }
  7450. function getStartAndCountOfVisiblePointsSimplified(meta, points) {
  7451. const pointCount = points.length;
  7452. let start = 0;
  7453. let count;
  7454. const { iScale } = meta;
  7455. const { min , max , minDefined , maxDefined } = iScale.getUserBounds();
  7456. if (minDefined) {
  7457. start = helpers_segment._limitValue(helpers_segment._lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
  7458. }
  7459. if (maxDefined) {
  7460. count = helpers_segment._limitValue(helpers_segment._lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
  7461. } else {
  7462. count = pointCount - start;
  7463. }
  7464. return {
  7465. start,
  7466. count
  7467. };
  7468. }
  7469. var plugin_decimation = {
  7470. id: 'decimation',
  7471. defaults: {
  7472. algorithm: 'min-max',
  7473. enabled: false
  7474. },
  7475. beforeElementsUpdate: (chart, args, options)=>{
  7476. if (!options.enabled) {
  7477. cleanDecimatedData(chart);
  7478. return;
  7479. }
  7480. const availableWidth = chart.width;
  7481. chart.data.datasets.forEach((dataset, datasetIndex)=>{
  7482. const { _data , indexAxis } = dataset;
  7483. const meta = chart.getDatasetMeta(datasetIndex);
  7484. const data = _data || dataset.data;
  7485. if (helpers_segment.resolve([
  7486. indexAxis,
  7487. chart.options.indexAxis
  7488. ]) === 'y') {
  7489. return;
  7490. }
  7491. if (!meta.controller.supportsDecimation) {
  7492. return;
  7493. }
  7494. const xAxis = chart.scales[meta.xAxisID];
  7495. if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
  7496. return;
  7497. }
  7498. if (chart.options.parsing) {
  7499. return;
  7500. }
  7501. let { start , count } = getStartAndCountOfVisiblePointsSimplified(meta, data);
  7502. const threshold = options.threshold || 4 * availableWidth;
  7503. if (count <= threshold) {
  7504. cleanDecimatedDataset(dataset);
  7505. return;
  7506. }
  7507. if (helpers_segment.isNullOrUndef(_data)) {
  7508. dataset._data = data;
  7509. delete dataset.data;
  7510. Object.defineProperty(dataset, 'data', {
  7511. configurable: true,
  7512. enumerable: true,
  7513. get: function() {
  7514. return this._decimated;
  7515. },
  7516. set: function(d) {
  7517. this._data = d;
  7518. }
  7519. });
  7520. }
  7521. let decimated;
  7522. switch(options.algorithm){
  7523. case 'lttb':
  7524. decimated = lttbDecimation(data, start, count, availableWidth, options);
  7525. break;
  7526. case 'min-max':
  7527. decimated = minMaxDecimation(data, start, count, availableWidth);
  7528. break;
  7529. default:
  7530. throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
  7531. }
  7532. dataset._decimated = decimated;
  7533. });
  7534. },
  7535. destroy (chart) {
  7536. cleanDecimatedData(chart);
  7537. }
  7538. };
  7539. function _segments(line, target, property) {
  7540. const segments = line.segments;
  7541. const points = line.points;
  7542. const tpoints = target.points;
  7543. const parts = [];
  7544. for (const segment of segments){
  7545. let { start , end } = segment;
  7546. end = _findSegmentEnd(start, end, points);
  7547. const bounds = _getBounds(property, points[start], points[end], segment.loop);
  7548. if (!target.segments) {
  7549. parts.push({
  7550. source: segment,
  7551. target: bounds,
  7552. start: points[start],
  7553. end: points[end]
  7554. });
  7555. continue;
  7556. }
  7557. const targetSegments = helpers_segment._boundSegments(target, bounds);
  7558. for (const tgt of targetSegments){
  7559. const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
  7560. const fillSources = helpers_segment._boundSegment(segment, points, subBounds);
  7561. for (const fillSource of fillSources){
  7562. parts.push({
  7563. source: fillSource,
  7564. target: tgt,
  7565. start: {
  7566. [property]: _getEdge(bounds, subBounds, 'start', Math.max)
  7567. },
  7568. end: {
  7569. [property]: _getEdge(bounds, subBounds, 'end', Math.min)
  7570. }
  7571. });
  7572. }
  7573. }
  7574. }
  7575. return parts;
  7576. }
  7577. function _getBounds(property, first, last, loop) {
  7578. if (loop) {
  7579. return;
  7580. }
  7581. let start = first[property];
  7582. let end = last[property];
  7583. if (property === 'angle') {
  7584. start = helpers_segment._normalizeAngle(start);
  7585. end = helpers_segment._normalizeAngle(end);
  7586. }
  7587. return {
  7588. property,
  7589. start,
  7590. end
  7591. };
  7592. }
  7593. function _pointsFromSegments(boundary, line) {
  7594. const { x =null , y =null } = boundary || {};
  7595. const linePoints = line.points;
  7596. const points = [];
  7597. line.segments.forEach(({ start , end })=>{
  7598. end = _findSegmentEnd(start, end, linePoints);
  7599. const first = linePoints[start];
  7600. const last = linePoints[end];
  7601. if (y !== null) {
  7602. points.push({
  7603. x: first.x,
  7604. y
  7605. });
  7606. points.push({
  7607. x: last.x,
  7608. y
  7609. });
  7610. } else if (x !== null) {
  7611. points.push({
  7612. x,
  7613. y: first.y
  7614. });
  7615. points.push({
  7616. x,
  7617. y: last.y
  7618. });
  7619. }
  7620. });
  7621. return points;
  7622. }
  7623. function _findSegmentEnd(start, end, points) {
  7624. for(; end > start; end--){
  7625. const point = points[end];
  7626. if (!isNaN(point.x) && !isNaN(point.y)) {
  7627. break;
  7628. }
  7629. }
  7630. return end;
  7631. }
  7632. function _getEdge(a, b, prop, fn) {
  7633. if (a && b) {
  7634. return fn(a[prop], b[prop]);
  7635. }
  7636. return a ? a[prop] : b ? b[prop] : 0;
  7637. }
  7638. function _createBoundaryLine(boundary, line) {
  7639. let points = [];
  7640. let _loop = false;
  7641. if (helpers_segment.isArray(boundary)) {
  7642. _loop = true;
  7643. points = boundary;
  7644. } else {
  7645. points = _pointsFromSegments(boundary, line);
  7646. }
  7647. return points.length ? new LineElement({
  7648. points,
  7649. options: {
  7650. tension: 0
  7651. },
  7652. _loop,
  7653. _fullLoop: _loop
  7654. }) : null;
  7655. }
  7656. function _shouldApplyFill(source) {
  7657. return source && source.fill !== false;
  7658. }
  7659. function _resolveTarget(sources, index, propagate) {
  7660. const source = sources[index];
  7661. let fill = source.fill;
  7662. const visited = [
  7663. index
  7664. ];
  7665. let target;
  7666. if (!propagate) {
  7667. return fill;
  7668. }
  7669. while(fill !== false && visited.indexOf(fill) === -1){
  7670. if (!helpers_segment.isNumberFinite(fill)) {
  7671. return fill;
  7672. }
  7673. target = sources[fill];
  7674. if (!target) {
  7675. return false;
  7676. }
  7677. if (target.visible) {
  7678. return fill;
  7679. }
  7680. visited.push(fill);
  7681. fill = target.fill;
  7682. }
  7683. return false;
  7684. }
  7685. function _decodeFill(line, index, count) {
  7686. const fill = parseFillOption(line);
  7687. if (helpers_segment.isObject(fill)) {
  7688. return isNaN(fill.value) ? false : fill;
  7689. }
  7690. let target = parseFloat(fill);
  7691. if (helpers_segment.isNumberFinite(target) && Math.floor(target) === target) {
  7692. return decodeTargetIndex(fill[0], index, target, count);
  7693. }
  7694. return [
  7695. 'origin',
  7696. 'start',
  7697. 'end',
  7698. 'stack',
  7699. 'shape'
  7700. ].indexOf(fill) >= 0 && fill;
  7701. }
  7702. function decodeTargetIndex(firstCh, index, target, count) {
  7703. if (firstCh === '-' || firstCh === '+') {
  7704. target = index + target;
  7705. }
  7706. if (target === index || target < 0 || target >= count) {
  7707. return false;
  7708. }
  7709. return target;
  7710. }
  7711. function _getTargetPixel(fill, scale) {
  7712. let pixel = null;
  7713. if (fill === 'start') {
  7714. pixel = scale.bottom;
  7715. } else if (fill === 'end') {
  7716. pixel = scale.top;
  7717. } else if (helpers_segment.isObject(fill)) {
  7718. pixel = scale.getPixelForValue(fill.value);
  7719. } else if (scale.getBasePixel) {
  7720. pixel = scale.getBasePixel();
  7721. }
  7722. return pixel;
  7723. }
  7724. function _getTargetValue(fill, scale, startValue) {
  7725. let value;
  7726. if (fill === 'start') {
  7727. value = startValue;
  7728. } else if (fill === 'end') {
  7729. value = scale.options.reverse ? scale.min : scale.max;
  7730. } else if (helpers_segment.isObject(fill)) {
  7731. value = fill.value;
  7732. } else {
  7733. value = scale.getBaseValue();
  7734. }
  7735. return value;
  7736. }
  7737. function parseFillOption(line) {
  7738. const options = line.options;
  7739. const fillOption = options.fill;
  7740. let fill = helpers_segment.valueOrDefault(fillOption && fillOption.target, fillOption);
  7741. if (fill === undefined) {
  7742. fill = !!options.backgroundColor;
  7743. }
  7744. if (fill === false || fill === null) {
  7745. return false;
  7746. }
  7747. if (fill === true) {
  7748. return 'origin';
  7749. }
  7750. return fill;
  7751. }
  7752. function _buildStackLine(source) {
  7753. const { scale , index , line } = source;
  7754. const points = [];
  7755. const segments = line.segments;
  7756. const sourcePoints = line.points;
  7757. const linesBelow = getLinesBelow(scale, index);
  7758. linesBelow.push(_createBoundaryLine({
  7759. x: null,
  7760. y: scale.bottom
  7761. }, line));
  7762. for(let i = 0; i < segments.length; i++){
  7763. const segment = segments[i];
  7764. for(let j = segment.start; j <= segment.end; j++){
  7765. addPointsBelow(points, sourcePoints[j], linesBelow);
  7766. }
  7767. }
  7768. return new LineElement({
  7769. points,
  7770. options: {}
  7771. });
  7772. }
  7773. function getLinesBelow(scale, index) {
  7774. const below = [];
  7775. const metas = scale.getMatchingVisibleMetas('line');
  7776. for(let i = 0; i < metas.length; i++){
  7777. const meta = metas[i];
  7778. if (meta.index === index) {
  7779. break;
  7780. }
  7781. if (!meta.hidden) {
  7782. below.unshift(meta.dataset);
  7783. }
  7784. }
  7785. return below;
  7786. }
  7787. function addPointsBelow(points, sourcePoint, linesBelow) {
  7788. const postponed = [];
  7789. for(let j = 0; j < linesBelow.length; j++){
  7790. const line = linesBelow[j];
  7791. const { first , last , point } = findPoint(line, sourcePoint, 'x');
  7792. if (!point || first && last) {
  7793. continue;
  7794. }
  7795. if (first) {
  7796. postponed.unshift(point);
  7797. } else {
  7798. points.push(point);
  7799. if (!last) {
  7800. break;
  7801. }
  7802. }
  7803. }
  7804. points.push(...postponed);
  7805. }
  7806. function findPoint(line, sourcePoint, property) {
  7807. const point = line.interpolate(sourcePoint, property);
  7808. if (!point) {
  7809. return {};
  7810. }
  7811. const pointValue = point[property];
  7812. const segments = line.segments;
  7813. const linePoints = line.points;
  7814. let first = false;
  7815. let last = false;
  7816. for(let i = 0; i < segments.length; i++){
  7817. const segment = segments[i];
  7818. const firstValue = linePoints[segment.start][property];
  7819. const lastValue = linePoints[segment.end][property];
  7820. if (helpers_segment._isBetween(pointValue, firstValue, lastValue)) {
  7821. first = pointValue === firstValue;
  7822. last = pointValue === lastValue;
  7823. break;
  7824. }
  7825. }
  7826. return {
  7827. first,
  7828. last,
  7829. point
  7830. };
  7831. }
  7832. class simpleArc {
  7833. constructor(opts){
  7834. this.x = opts.x;
  7835. this.y = opts.y;
  7836. this.radius = opts.radius;
  7837. }
  7838. pathSegment(ctx, bounds, opts) {
  7839. const { x , y , radius } = this;
  7840. bounds = bounds || {
  7841. start: 0,
  7842. end: helpers_segment.TAU
  7843. };
  7844. ctx.arc(x, y, radius, bounds.end, bounds.start, true);
  7845. return !opts.bounds;
  7846. }
  7847. interpolate(point) {
  7848. const { x , y , radius } = this;
  7849. const angle = point.angle;
  7850. return {
  7851. x: x + Math.cos(angle) * radius,
  7852. y: y + Math.sin(angle) * radius,
  7853. angle
  7854. };
  7855. }
  7856. }
  7857. function _getTarget(source) {
  7858. const { chart , fill , line } = source;
  7859. if (helpers_segment.isNumberFinite(fill)) {
  7860. return getLineByIndex(chart, fill);
  7861. }
  7862. if (fill === 'stack') {
  7863. return _buildStackLine(source);
  7864. }
  7865. if (fill === 'shape') {
  7866. return true;
  7867. }
  7868. const boundary = computeBoundary(source);
  7869. if (boundary instanceof simpleArc) {
  7870. return boundary;
  7871. }
  7872. return _createBoundaryLine(boundary, line);
  7873. }
  7874. function getLineByIndex(chart, index) {
  7875. const meta = chart.getDatasetMeta(index);
  7876. const visible = meta && chart.isDatasetVisible(index);
  7877. return visible ? meta.dataset : null;
  7878. }
  7879. function computeBoundary(source) {
  7880. const scale = source.scale || {};
  7881. if (scale.getPointPositionForValue) {
  7882. return computeCircularBoundary(source);
  7883. }
  7884. return computeLinearBoundary(source);
  7885. }
  7886. function computeLinearBoundary(source) {
  7887. const { scale ={} , fill } = source;
  7888. const pixel = _getTargetPixel(fill, scale);
  7889. if (helpers_segment.isNumberFinite(pixel)) {
  7890. const horizontal = scale.isHorizontal();
  7891. return {
  7892. x: horizontal ? pixel : null,
  7893. y: horizontal ? null : pixel
  7894. };
  7895. }
  7896. return null;
  7897. }
  7898. function computeCircularBoundary(source) {
  7899. const { scale , fill } = source;
  7900. const options = scale.options;
  7901. const length = scale.getLabels().length;
  7902. const start = options.reverse ? scale.max : scale.min;
  7903. const value = _getTargetValue(fill, scale, start);
  7904. const target = [];
  7905. if (options.grid.circular) {
  7906. const center = scale.getPointPositionForValue(0, start);
  7907. return new simpleArc({
  7908. x: center.x,
  7909. y: center.y,
  7910. radius: scale.getDistanceFromCenterForValue(value)
  7911. });
  7912. }
  7913. for(let i = 0; i < length; ++i){
  7914. target.push(scale.getPointPositionForValue(i, value));
  7915. }
  7916. return target;
  7917. }
  7918. function _drawfill(ctx, source, area) {
  7919. const target = _getTarget(source);
  7920. const { line , scale , axis } = source;
  7921. const lineOpts = line.options;
  7922. const fillOption = lineOpts.fill;
  7923. const color = lineOpts.backgroundColor;
  7924. const { above =color , below =color } = fillOption || {};
  7925. if (target && line.points.length) {
  7926. helpers_segment.clipArea(ctx, area);
  7927. doFill(ctx, {
  7928. line,
  7929. target,
  7930. above,
  7931. below,
  7932. area,
  7933. scale,
  7934. axis
  7935. });
  7936. helpers_segment.unclipArea(ctx);
  7937. }
  7938. }
  7939. function doFill(ctx, cfg) {
  7940. const { line , target , above , below , area , scale } = cfg;
  7941. const property = line._loop ? 'angle' : cfg.axis;
  7942. ctx.save();
  7943. if (property === 'x' && below !== above) {
  7944. clipVertical(ctx, target, area.top);
  7945. fill(ctx, {
  7946. line,
  7947. target,
  7948. color: above,
  7949. scale,
  7950. property
  7951. });
  7952. ctx.restore();
  7953. ctx.save();
  7954. clipVertical(ctx, target, area.bottom);
  7955. }
  7956. fill(ctx, {
  7957. line,
  7958. target,
  7959. color: below,
  7960. scale,
  7961. property
  7962. });
  7963. ctx.restore();
  7964. }
  7965. function clipVertical(ctx, target, clipY) {
  7966. const { segments , points } = target;
  7967. let first = true;
  7968. let lineLoop = false;
  7969. ctx.beginPath();
  7970. for (const segment of segments){
  7971. const { start , end } = segment;
  7972. const firstPoint = points[start];
  7973. const lastPoint = points[_findSegmentEnd(start, end, points)];
  7974. if (first) {
  7975. ctx.moveTo(firstPoint.x, firstPoint.y);
  7976. first = false;
  7977. } else {
  7978. ctx.lineTo(firstPoint.x, clipY);
  7979. ctx.lineTo(firstPoint.x, firstPoint.y);
  7980. }
  7981. lineLoop = !!target.pathSegment(ctx, segment, {
  7982. move: lineLoop
  7983. });
  7984. if (lineLoop) {
  7985. ctx.closePath();
  7986. } else {
  7987. ctx.lineTo(lastPoint.x, clipY);
  7988. }
  7989. }
  7990. ctx.lineTo(target.first().x, clipY);
  7991. ctx.closePath();
  7992. ctx.clip();
  7993. }
  7994. function fill(ctx, cfg) {
  7995. const { line , target , property , color , scale } = cfg;
  7996. const segments = _segments(line, target, property);
  7997. for (const { source: src , target: tgt , start , end } of segments){
  7998. const { style: { backgroundColor =color } = {} } = src;
  7999. const notShape = target !== true;
  8000. ctx.save();
  8001. ctx.fillStyle = backgroundColor;
  8002. clipBounds(ctx, scale, notShape && _getBounds(property, start, end));
  8003. ctx.beginPath();
  8004. const lineLoop = !!line.pathSegment(ctx, src);
  8005. let loop;
  8006. if (notShape) {
  8007. if (lineLoop) {
  8008. ctx.closePath();
  8009. } else {
  8010. interpolatedLineTo(ctx, target, end, property);
  8011. }
  8012. const targetLoop = !!target.pathSegment(ctx, tgt, {
  8013. move: lineLoop,
  8014. reverse: true
  8015. });
  8016. loop = lineLoop && targetLoop;
  8017. if (!loop) {
  8018. interpolatedLineTo(ctx, target, start, property);
  8019. }
  8020. }
  8021. ctx.closePath();
  8022. ctx.fill(loop ? 'evenodd' : 'nonzero');
  8023. ctx.restore();
  8024. }
  8025. }
  8026. function clipBounds(ctx, scale, bounds) {
  8027. const { top , bottom } = scale.chart.chartArea;
  8028. const { property , start , end } = bounds || {};
  8029. if (property === 'x') {
  8030. ctx.beginPath();
  8031. ctx.rect(start, top, end - start, bottom - top);
  8032. ctx.clip();
  8033. }
  8034. }
  8035. function interpolatedLineTo(ctx, target, point, property) {
  8036. const interpolatedPoint = target.interpolate(point, property);
  8037. if (interpolatedPoint) {
  8038. ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
  8039. }
  8040. }
  8041. var index = {
  8042. id: 'filler',
  8043. afterDatasetsUpdate (chart, _args, options) {
  8044. const count = (chart.data.datasets || []).length;
  8045. const sources = [];
  8046. let meta, i, line, source;
  8047. for(i = 0; i < count; ++i){
  8048. meta = chart.getDatasetMeta(i);
  8049. line = meta.dataset;
  8050. source = null;
  8051. if (line && line.options && line instanceof LineElement) {
  8052. source = {
  8053. visible: chart.isDatasetVisible(i),
  8054. index: i,
  8055. fill: _decodeFill(line, i, count),
  8056. chart,
  8057. axis: meta.controller.options.indexAxis,
  8058. scale: meta.vScale,
  8059. line
  8060. };
  8061. }
  8062. meta.$filler = source;
  8063. sources.push(source);
  8064. }
  8065. for(i = 0; i < count; ++i){
  8066. source = sources[i];
  8067. if (!source || source.fill === false) {
  8068. continue;
  8069. }
  8070. source.fill = _resolveTarget(sources, i, options.propagate);
  8071. }
  8072. },
  8073. beforeDraw (chart, _args, options) {
  8074. const draw = options.drawTime === 'beforeDraw';
  8075. const metasets = chart.getSortedVisibleDatasetMetas();
  8076. const area = chart.chartArea;
  8077. for(let i = metasets.length - 1; i >= 0; --i){
  8078. const source = metasets[i].$filler;
  8079. if (!source) {
  8080. continue;
  8081. }
  8082. source.line.updateControlPoints(area, source.axis);
  8083. if (draw && source.fill) {
  8084. _drawfill(chart.ctx, source, area);
  8085. }
  8086. }
  8087. },
  8088. beforeDatasetsDraw (chart, _args, options) {
  8089. if (options.drawTime !== 'beforeDatasetsDraw') {
  8090. return;
  8091. }
  8092. const metasets = chart.getSortedVisibleDatasetMetas();
  8093. for(let i = metasets.length - 1; i >= 0; --i){
  8094. const source = metasets[i].$filler;
  8095. if (_shouldApplyFill(source)) {
  8096. _drawfill(chart.ctx, source, chart.chartArea);
  8097. }
  8098. }
  8099. },
  8100. beforeDatasetDraw (chart, args, options) {
  8101. const source = args.meta.$filler;
  8102. if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') {
  8103. return;
  8104. }
  8105. _drawfill(chart.ctx, source, chart.chartArea);
  8106. },
  8107. defaults: {
  8108. propagate: true,
  8109. drawTime: 'beforeDatasetDraw'
  8110. }
  8111. };
  8112. const getBoxSize = (labelOpts, fontSize)=>{
  8113. let { boxHeight =fontSize , boxWidth =fontSize } = labelOpts;
  8114. if (labelOpts.usePointStyle) {
  8115. boxHeight = Math.min(boxHeight, fontSize);
  8116. boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize);
  8117. }
  8118. return {
  8119. boxWidth,
  8120. boxHeight,
  8121. itemHeight: Math.max(fontSize, boxHeight)
  8122. };
  8123. };
  8124. const itemsEqual = (a, b)=>a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
  8125. class Legend extends Element {
  8126. constructor(config){
  8127. super();
  8128. this._added = false;
  8129. this.legendHitBoxes = [];
  8130. this._hoveredItem = null;
  8131. this.doughnutMode = false;
  8132. this.chart = config.chart;
  8133. this.options = config.options;
  8134. this.ctx = config.ctx;
  8135. this.legendItems = undefined;
  8136. this.columnSizes = undefined;
  8137. this.lineWidths = undefined;
  8138. this.maxHeight = undefined;
  8139. this.maxWidth = undefined;
  8140. this.top = undefined;
  8141. this.bottom = undefined;
  8142. this.left = undefined;
  8143. this.right = undefined;
  8144. this.height = undefined;
  8145. this.width = undefined;
  8146. this._margins = undefined;
  8147. this.position = undefined;
  8148. this.weight = undefined;
  8149. this.fullSize = undefined;
  8150. }
  8151. update(maxWidth, maxHeight, margins) {
  8152. this.maxWidth = maxWidth;
  8153. this.maxHeight = maxHeight;
  8154. this._margins = margins;
  8155. this.setDimensions();
  8156. this.buildLabels();
  8157. this.fit();
  8158. }
  8159. setDimensions() {
  8160. if (this.isHorizontal()) {
  8161. this.width = this.maxWidth;
  8162. this.left = this._margins.left;
  8163. this.right = this.width;
  8164. } else {
  8165. this.height = this.maxHeight;
  8166. this.top = this._margins.top;
  8167. this.bottom = this.height;
  8168. }
  8169. }
  8170. buildLabels() {
  8171. const labelOpts = this.options.labels || {};
  8172. let legendItems = helpers_segment.callback(labelOpts.generateLabels, [
  8173. this.chart
  8174. ], this) || [];
  8175. if (labelOpts.filter) {
  8176. legendItems = legendItems.filter((item)=>labelOpts.filter(item, this.chart.data));
  8177. }
  8178. if (labelOpts.sort) {
  8179. legendItems = legendItems.sort((a, b)=>labelOpts.sort(a, b, this.chart.data));
  8180. }
  8181. if (this.options.reverse) {
  8182. legendItems.reverse();
  8183. }
  8184. this.legendItems = legendItems;
  8185. }
  8186. fit() {
  8187. const { options , ctx } = this;
  8188. if (!options.display) {
  8189. this.width = this.height = 0;
  8190. return;
  8191. }
  8192. const labelOpts = options.labels;
  8193. const labelFont = helpers_segment.toFont(labelOpts.font);
  8194. const fontSize = labelFont.size;
  8195. const titleHeight = this._computeTitleHeight();
  8196. const { boxWidth , itemHeight } = getBoxSize(labelOpts, fontSize);
  8197. let width, height;
  8198. ctx.font = labelFont.string;
  8199. if (this.isHorizontal()) {
  8200. width = this.maxWidth;
  8201. height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  8202. } else {
  8203. height = this.maxHeight;
  8204. width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10;
  8205. }
  8206. this.width = Math.min(width, options.maxWidth || this.maxWidth);
  8207. this.height = Math.min(height, options.maxHeight || this.maxHeight);
  8208. }
  8209. _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
  8210. const { ctx , maxWidth , options: { labels: { padding } } } = this;
  8211. const hitboxes = this.legendHitBoxes = [];
  8212. const lineWidths = this.lineWidths = [
  8213. 0
  8214. ];
  8215. const lineHeight = itemHeight + padding;
  8216. let totalHeight = titleHeight;
  8217. ctx.textAlign = 'left';
  8218. ctx.textBaseline = 'middle';
  8219. let row = -1;
  8220. let top = -lineHeight;
  8221. this.legendItems.forEach((legendItem, i)=>{
  8222. const itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width;
  8223. if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
  8224. totalHeight += lineHeight;
  8225. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  8226. top += lineHeight;
  8227. row++;
  8228. }
  8229. hitboxes[i] = {
  8230. left: 0,
  8231. top,
  8232. row,
  8233. width: itemWidth,
  8234. height: itemHeight
  8235. };
  8236. lineWidths[lineWidths.length - 1] += itemWidth + padding;
  8237. });
  8238. return totalHeight;
  8239. }
  8240. _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) {
  8241. const { ctx , maxHeight , options: { labels: { padding } } } = this;
  8242. const hitboxes = this.legendHitBoxes = [];
  8243. const columnSizes = this.columnSizes = [];
  8244. const heightLimit = maxHeight - titleHeight;
  8245. let totalWidth = padding;
  8246. let currentColWidth = 0;
  8247. let currentColHeight = 0;
  8248. let left = 0;
  8249. let col = 0;
  8250. this.legendItems.forEach((legendItem, i)=>{
  8251. const { itemWidth , itemHeight } = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight);
  8252. if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {
  8253. totalWidth += currentColWidth + padding;
  8254. columnSizes.push({
  8255. width: currentColWidth,
  8256. height: currentColHeight
  8257. });
  8258. left += currentColWidth + padding;
  8259. col++;
  8260. currentColWidth = currentColHeight = 0;
  8261. }
  8262. hitboxes[i] = {
  8263. left,
  8264. top: currentColHeight,
  8265. col,
  8266. width: itemWidth,
  8267. height: itemHeight
  8268. };
  8269. currentColWidth = Math.max(currentColWidth, itemWidth);
  8270. currentColHeight += itemHeight + padding;
  8271. });
  8272. totalWidth += currentColWidth;
  8273. columnSizes.push({
  8274. width: currentColWidth,
  8275. height: currentColHeight
  8276. });
  8277. return totalWidth;
  8278. }
  8279. adjustHitBoxes() {
  8280. if (!this.options.display) {
  8281. return;
  8282. }
  8283. const titleHeight = this._computeTitleHeight();
  8284. const { legendHitBoxes: hitboxes , options: { align , labels: { padding } , rtl } } = this;
  8285. const rtlHelper = helpers_segment.getRtlAdapter(rtl, this.left, this.width);
  8286. if (this.isHorizontal()) {
  8287. let row = 0;
  8288. let left = helpers_segment._alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  8289. for (const hitbox of hitboxes){
  8290. if (row !== hitbox.row) {
  8291. row = hitbox.row;
  8292. left = helpers_segment._alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  8293. }
  8294. hitbox.top += this.top + titleHeight + padding;
  8295. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);
  8296. left += hitbox.width + padding;
  8297. }
  8298. } else {
  8299. let col = 0;
  8300. let top = helpers_segment._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  8301. for (const hitbox of hitboxes){
  8302. if (hitbox.col !== col) {
  8303. col = hitbox.col;
  8304. top = helpers_segment._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  8305. }
  8306. hitbox.top = top;
  8307. hitbox.left += this.left + padding;
  8308. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);
  8309. top += hitbox.height + padding;
  8310. }
  8311. }
  8312. }
  8313. isHorizontal() {
  8314. return this.options.position === 'top' || this.options.position === 'bottom';
  8315. }
  8316. draw() {
  8317. if (this.options.display) {
  8318. const ctx = this.ctx;
  8319. helpers_segment.clipArea(ctx, this);
  8320. this._draw();
  8321. helpers_segment.unclipArea(ctx);
  8322. }
  8323. }
  8324. _draw() {
  8325. const { options: opts , columnSizes , lineWidths , ctx } = this;
  8326. const { align , labels: labelOpts } = opts;
  8327. const defaultColor = helpers_segment.defaults.color;
  8328. const rtlHelper = helpers_segment.getRtlAdapter(opts.rtl, this.left, this.width);
  8329. const labelFont = helpers_segment.toFont(labelOpts.font);
  8330. const { padding } = labelOpts;
  8331. const fontSize = labelFont.size;
  8332. const halfFontSize = fontSize / 2;
  8333. let cursor;
  8334. this.drawTitle();
  8335. ctx.textAlign = rtlHelper.textAlign('left');
  8336. ctx.textBaseline = 'middle';
  8337. ctx.lineWidth = 0.5;
  8338. ctx.font = labelFont.string;
  8339. const { boxWidth , boxHeight , itemHeight } = getBoxSize(labelOpts, fontSize);
  8340. const drawLegendBox = function(x, y, legendItem) {
  8341. if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
  8342. return;
  8343. }
  8344. ctx.save();
  8345. const lineWidth = helpers_segment.valueOrDefault(legendItem.lineWidth, 1);
  8346. ctx.fillStyle = helpers_segment.valueOrDefault(legendItem.fillStyle, defaultColor);
  8347. ctx.lineCap = helpers_segment.valueOrDefault(legendItem.lineCap, 'butt');
  8348. ctx.lineDashOffset = helpers_segment.valueOrDefault(legendItem.lineDashOffset, 0);
  8349. ctx.lineJoin = helpers_segment.valueOrDefault(legendItem.lineJoin, 'miter');
  8350. ctx.lineWidth = lineWidth;
  8351. ctx.strokeStyle = helpers_segment.valueOrDefault(legendItem.strokeStyle, defaultColor);
  8352. ctx.setLineDash(helpers_segment.valueOrDefault(legendItem.lineDash, []));
  8353. if (labelOpts.usePointStyle) {
  8354. const drawOptions = {
  8355. radius: boxHeight * Math.SQRT2 / 2,
  8356. pointStyle: legendItem.pointStyle,
  8357. rotation: legendItem.rotation,
  8358. borderWidth: lineWidth
  8359. };
  8360. const centerX = rtlHelper.xPlus(x, boxWidth / 2);
  8361. const centerY = y + halfFontSize;
  8362. helpers_segment.drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth);
  8363. } else {
  8364. const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
  8365. const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
  8366. const borderRadius = helpers_segment.toTRBLCorners(legendItem.borderRadius);
  8367. ctx.beginPath();
  8368. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  8369. helpers_segment.addRoundedRectPath(ctx, {
  8370. x: xBoxLeft,
  8371. y: yBoxTop,
  8372. w: boxWidth,
  8373. h: boxHeight,
  8374. radius: borderRadius
  8375. });
  8376. } else {
  8377. ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
  8378. }
  8379. ctx.fill();
  8380. if (lineWidth !== 0) {
  8381. ctx.stroke();
  8382. }
  8383. }
  8384. ctx.restore();
  8385. };
  8386. const fillText = function(x, y, legendItem) {
  8387. helpers_segment.renderText(ctx, legendItem.text, x, y + itemHeight / 2, labelFont, {
  8388. strikethrough: legendItem.hidden,
  8389. textAlign: rtlHelper.textAlign(legendItem.textAlign)
  8390. });
  8391. };
  8392. const isHorizontal = this.isHorizontal();
  8393. const titleHeight = this._computeTitleHeight();
  8394. if (isHorizontal) {
  8395. cursor = {
  8396. x: helpers_segment._alignStartEnd(align, this.left + padding, this.right - lineWidths[0]),
  8397. y: this.top + padding + titleHeight,
  8398. line: 0
  8399. };
  8400. } else {
  8401. cursor = {
  8402. x: this.left + padding,
  8403. y: helpers_segment._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height),
  8404. line: 0
  8405. };
  8406. }
  8407. helpers_segment.overrideTextDirection(this.ctx, opts.textDirection);
  8408. const lineHeight = itemHeight + padding;
  8409. this.legendItems.forEach((legendItem, i)=>{
  8410. ctx.strokeStyle = legendItem.fontColor;
  8411. ctx.fillStyle = legendItem.fontColor;
  8412. const textWidth = ctx.measureText(legendItem.text).width;
  8413. const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
  8414. const width = boxWidth + halfFontSize + textWidth;
  8415. let x = cursor.x;
  8416. let y = cursor.y;
  8417. rtlHelper.setWidth(this.width);
  8418. if (isHorizontal) {
  8419. if (i > 0 && x + width + padding > this.right) {
  8420. y = cursor.y += lineHeight;
  8421. cursor.line++;
  8422. x = cursor.x = helpers_segment._alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]);
  8423. }
  8424. } else if (i > 0 && y + lineHeight > this.bottom) {
  8425. x = cursor.x = x + columnSizes[cursor.line].width + padding;
  8426. cursor.line++;
  8427. y = cursor.y = helpers_segment._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height);
  8428. }
  8429. const realX = rtlHelper.x(x);
  8430. drawLegendBox(realX, y, legendItem);
  8431. x = helpers_segment._textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl);
  8432. fillText(rtlHelper.x(x), y, legendItem);
  8433. if (isHorizontal) {
  8434. cursor.x += width + padding;
  8435. } else if (typeof legendItem.text !== 'string') {
  8436. const fontLineHeight = labelFont.lineHeight;
  8437. cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding;
  8438. } else {
  8439. cursor.y += lineHeight;
  8440. }
  8441. });
  8442. helpers_segment.restoreTextDirection(this.ctx, opts.textDirection);
  8443. }
  8444. drawTitle() {
  8445. const opts = this.options;
  8446. const titleOpts = opts.title;
  8447. const titleFont = helpers_segment.toFont(titleOpts.font);
  8448. const titlePadding = helpers_segment.toPadding(titleOpts.padding);
  8449. if (!titleOpts.display) {
  8450. return;
  8451. }
  8452. const rtlHelper = helpers_segment.getRtlAdapter(opts.rtl, this.left, this.width);
  8453. const ctx = this.ctx;
  8454. const position = titleOpts.position;
  8455. const halfFontSize = titleFont.size / 2;
  8456. const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
  8457. let y;
  8458. let left = this.left;
  8459. let maxWidth = this.width;
  8460. if (this.isHorizontal()) {
  8461. maxWidth = Math.max(...this.lineWidths);
  8462. y = this.top + topPaddingPlusHalfFontSize;
  8463. left = helpers_segment._alignStartEnd(opts.align, left, this.right - maxWidth);
  8464. } else {
  8465. const maxHeight = this.columnSizes.reduce((acc, size)=>Math.max(acc, size.height), 0);
  8466. y = topPaddingPlusHalfFontSize + helpers_segment._alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight());
  8467. }
  8468. const x = helpers_segment._alignStartEnd(position, left, left + maxWidth);
  8469. ctx.textAlign = rtlHelper.textAlign(helpers_segment._toLeftRightCenter(position));
  8470. ctx.textBaseline = 'middle';
  8471. ctx.strokeStyle = titleOpts.color;
  8472. ctx.fillStyle = titleOpts.color;
  8473. ctx.font = titleFont.string;
  8474. helpers_segment.renderText(ctx, titleOpts.text, x, y, titleFont);
  8475. }
  8476. _computeTitleHeight() {
  8477. const titleOpts = this.options.title;
  8478. const titleFont = helpers_segment.toFont(titleOpts.font);
  8479. const titlePadding = helpers_segment.toPadding(titleOpts.padding);
  8480. return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
  8481. }
  8482. _getLegendItemAt(x, y) {
  8483. let i, hitBox, lh;
  8484. if (helpers_segment._isBetween(x, this.left, this.right) && helpers_segment._isBetween(y, this.top, this.bottom)) {
  8485. lh = this.legendHitBoxes;
  8486. for(i = 0; i < lh.length; ++i){
  8487. hitBox = lh[i];
  8488. if (helpers_segment._isBetween(x, hitBox.left, hitBox.left + hitBox.width) && helpers_segment._isBetween(y, hitBox.top, hitBox.top + hitBox.height)) {
  8489. return this.legendItems[i];
  8490. }
  8491. }
  8492. }
  8493. return null;
  8494. }
  8495. handleEvent(e) {
  8496. const opts = this.options;
  8497. if (!isListened(e.type, opts)) {
  8498. return;
  8499. }
  8500. const hoveredItem = this._getLegendItemAt(e.x, e.y);
  8501. if (e.type === 'mousemove' || e.type === 'mouseout') {
  8502. const previous = this._hoveredItem;
  8503. const sameItem = itemsEqual(previous, hoveredItem);
  8504. if (previous && !sameItem) {
  8505. helpers_segment.callback(opts.onLeave, [
  8506. e,
  8507. previous,
  8508. this
  8509. ], this);
  8510. }
  8511. this._hoveredItem = hoveredItem;
  8512. if (hoveredItem && !sameItem) {
  8513. helpers_segment.callback(opts.onHover, [
  8514. e,
  8515. hoveredItem,
  8516. this
  8517. ], this);
  8518. }
  8519. } else if (hoveredItem) {
  8520. helpers_segment.callback(opts.onClick, [
  8521. e,
  8522. hoveredItem,
  8523. this
  8524. ], this);
  8525. }
  8526. }
  8527. }
  8528. function calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) {
  8529. const itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx);
  8530. const itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight);
  8531. return {
  8532. itemWidth,
  8533. itemHeight
  8534. };
  8535. }
  8536. function calculateItemWidth(legendItem, boxWidth, labelFont, ctx) {
  8537. let legendItemText = legendItem.text;
  8538. if (legendItemText && typeof legendItemText !== 'string') {
  8539. legendItemText = legendItemText.reduce((a, b)=>a.length > b.length ? a : b);
  8540. }
  8541. return boxWidth + labelFont.size / 2 + ctx.measureText(legendItemText).width;
  8542. }
  8543. function calculateItemHeight(_itemHeight, legendItem, fontLineHeight) {
  8544. let itemHeight = _itemHeight;
  8545. if (typeof legendItem.text !== 'string') {
  8546. itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight);
  8547. }
  8548. return itemHeight;
  8549. }
  8550. function calculateLegendItemHeight(legendItem, fontLineHeight) {
  8551. const labelHeight = legendItem.text ? legendItem.text.length : 0;
  8552. return fontLineHeight * labelHeight;
  8553. }
  8554. function isListened(type, opts) {
  8555. if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) {
  8556. return true;
  8557. }
  8558. if (opts.onClick && (type === 'click' || type === 'mouseup')) {
  8559. return true;
  8560. }
  8561. return false;
  8562. }
  8563. var plugin_legend = {
  8564. id: 'legend',
  8565. _element: Legend,
  8566. start (chart, _args, options) {
  8567. const legend = chart.legend = new Legend({
  8568. ctx: chart.ctx,
  8569. options,
  8570. chart
  8571. });
  8572. layouts.configure(chart, legend, options);
  8573. layouts.addBox(chart, legend);
  8574. },
  8575. stop (chart) {
  8576. layouts.removeBox(chart, chart.legend);
  8577. delete chart.legend;
  8578. },
  8579. beforeUpdate (chart, _args, options) {
  8580. const legend = chart.legend;
  8581. layouts.configure(chart, legend, options);
  8582. legend.options = options;
  8583. },
  8584. afterUpdate (chart) {
  8585. const legend = chart.legend;
  8586. legend.buildLabels();
  8587. legend.adjustHitBoxes();
  8588. },
  8589. afterEvent (chart, args) {
  8590. if (!args.replay) {
  8591. chart.legend.handleEvent(args.event);
  8592. }
  8593. },
  8594. defaults: {
  8595. display: true,
  8596. position: 'top',
  8597. align: 'center',
  8598. fullSize: true,
  8599. reverse: false,
  8600. weight: 1000,
  8601. onClick (e, legendItem, legend) {
  8602. const index = legendItem.datasetIndex;
  8603. const ci = legend.chart;
  8604. if (ci.isDatasetVisible(index)) {
  8605. ci.hide(index);
  8606. legendItem.hidden = true;
  8607. } else {
  8608. ci.show(index);
  8609. legendItem.hidden = false;
  8610. }
  8611. },
  8612. onHover: null,
  8613. onLeave: null,
  8614. labels: {
  8615. color: (ctx)=>ctx.chart.options.color,
  8616. boxWidth: 40,
  8617. padding: 10,
  8618. generateLabels (chart) {
  8619. const datasets = chart.data.datasets;
  8620. const { labels: { usePointStyle , pointStyle , textAlign , color , useBorderRadius , borderRadius } } = chart.legend.options;
  8621. return chart._getSortedDatasetMetas().map((meta)=>{
  8622. const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  8623. const borderWidth = helpers_segment.toPadding(style.borderWidth);
  8624. return {
  8625. text: datasets[meta.index].label,
  8626. fillStyle: style.backgroundColor,
  8627. fontColor: color,
  8628. hidden: !meta.visible,
  8629. lineCap: style.borderCapStyle,
  8630. lineDash: style.borderDash,
  8631. lineDashOffset: style.borderDashOffset,
  8632. lineJoin: style.borderJoinStyle,
  8633. lineWidth: (borderWidth.width + borderWidth.height) / 4,
  8634. strokeStyle: style.borderColor,
  8635. pointStyle: pointStyle || style.pointStyle,
  8636. rotation: style.rotation,
  8637. textAlign: textAlign || style.textAlign,
  8638. borderRadius: useBorderRadius && (borderRadius || style.borderRadius),
  8639. datasetIndex: meta.index
  8640. };
  8641. }, this);
  8642. }
  8643. },
  8644. title: {
  8645. color: (ctx)=>ctx.chart.options.color,
  8646. display: false,
  8647. position: 'center',
  8648. text: ''
  8649. }
  8650. },
  8651. descriptors: {
  8652. _scriptable: (name)=>!name.startsWith('on'),
  8653. labels: {
  8654. _scriptable: (name)=>![
  8655. 'generateLabels',
  8656. 'filter',
  8657. 'sort'
  8658. ].includes(name)
  8659. }
  8660. }
  8661. };
  8662. class Title extends Element {
  8663. constructor(config){
  8664. super();
  8665. this.chart = config.chart;
  8666. this.options = config.options;
  8667. this.ctx = config.ctx;
  8668. this._padding = undefined;
  8669. this.top = undefined;
  8670. this.bottom = undefined;
  8671. this.left = undefined;
  8672. this.right = undefined;
  8673. this.width = undefined;
  8674. this.height = undefined;
  8675. this.position = undefined;
  8676. this.weight = undefined;
  8677. this.fullSize = undefined;
  8678. }
  8679. update(maxWidth, maxHeight) {
  8680. const opts = this.options;
  8681. this.left = 0;
  8682. this.top = 0;
  8683. if (!opts.display) {
  8684. this.width = this.height = this.right = this.bottom = 0;
  8685. return;
  8686. }
  8687. this.width = this.right = maxWidth;
  8688. this.height = this.bottom = maxHeight;
  8689. const lineCount = helpers_segment.isArray(opts.text) ? opts.text.length : 1;
  8690. this._padding = helpers_segment.toPadding(opts.padding);
  8691. const textSize = lineCount * helpers_segment.toFont(opts.font).lineHeight + this._padding.height;
  8692. if (this.isHorizontal()) {
  8693. this.height = textSize;
  8694. } else {
  8695. this.width = textSize;
  8696. }
  8697. }
  8698. isHorizontal() {
  8699. const pos = this.options.position;
  8700. return pos === 'top' || pos === 'bottom';
  8701. }
  8702. _drawArgs(offset) {
  8703. const { top , left , bottom , right , options } = this;
  8704. const align = options.align;
  8705. let rotation = 0;
  8706. let maxWidth, titleX, titleY;
  8707. if (this.isHorizontal()) {
  8708. titleX = helpers_segment._alignStartEnd(align, left, right);
  8709. titleY = top + offset;
  8710. maxWidth = right - left;
  8711. } else {
  8712. if (options.position === 'left') {
  8713. titleX = left + offset;
  8714. titleY = helpers_segment._alignStartEnd(align, bottom, top);
  8715. rotation = helpers_segment.PI * -0.5;
  8716. } else {
  8717. titleX = right - offset;
  8718. titleY = helpers_segment._alignStartEnd(align, top, bottom);
  8719. rotation = helpers_segment.PI * 0.5;
  8720. }
  8721. maxWidth = bottom - top;
  8722. }
  8723. return {
  8724. titleX,
  8725. titleY,
  8726. maxWidth,
  8727. rotation
  8728. };
  8729. }
  8730. draw() {
  8731. const ctx = this.ctx;
  8732. const opts = this.options;
  8733. if (!opts.display) {
  8734. return;
  8735. }
  8736. const fontOpts = helpers_segment.toFont(opts.font);
  8737. const lineHeight = fontOpts.lineHeight;
  8738. const offset = lineHeight / 2 + this._padding.top;
  8739. const { titleX , titleY , maxWidth , rotation } = this._drawArgs(offset);
  8740. helpers_segment.renderText(ctx, opts.text, 0, 0, fontOpts, {
  8741. color: opts.color,
  8742. maxWidth,
  8743. rotation,
  8744. textAlign: helpers_segment._toLeftRightCenter(opts.align),
  8745. textBaseline: 'middle',
  8746. translation: [
  8747. titleX,
  8748. titleY
  8749. ]
  8750. });
  8751. }
  8752. }
  8753. function createTitle(chart, titleOpts) {
  8754. const title = new Title({
  8755. ctx: chart.ctx,
  8756. options: titleOpts,
  8757. chart
  8758. });
  8759. layouts.configure(chart, title, titleOpts);
  8760. layouts.addBox(chart, title);
  8761. chart.titleBlock = title;
  8762. }
  8763. var plugin_title = {
  8764. id: 'title',
  8765. _element: Title,
  8766. start (chart, _args, options) {
  8767. createTitle(chart, options);
  8768. },
  8769. stop (chart) {
  8770. const titleBlock = chart.titleBlock;
  8771. layouts.removeBox(chart, titleBlock);
  8772. delete chart.titleBlock;
  8773. },
  8774. beforeUpdate (chart, _args, options) {
  8775. const title = chart.titleBlock;
  8776. layouts.configure(chart, title, options);
  8777. title.options = options;
  8778. },
  8779. defaults: {
  8780. align: 'center',
  8781. display: false,
  8782. font: {
  8783. weight: 'bold'
  8784. },
  8785. fullSize: true,
  8786. padding: 10,
  8787. position: 'top',
  8788. text: '',
  8789. weight: 2000
  8790. },
  8791. defaultRoutes: {
  8792. color: 'color'
  8793. },
  8794. descriptors: {
  8795. _scriptable: true,
  8796. _indexable: false
  8797. }
  8798. };
  8799. const map = new WeakMap();
  8800. var plugin_subtitle = {
  8801. id: 'subtitle',
  8802. start (chart, _args, options) {
  8803. const title = new Title({
  8804. ctx: chart.ctx,
  8805. options,
  8806. chart
  8807. });
  8808. layouts.configure(chart, title, options);
  8809. layouts.addBox(chart, title);
  8810. map.set(chart, title);
  8811. },
  8812. stop (chart) {
  8813. layouts.removeBox(chart, map.get(chart));
  8814. map.delete(chart);
  8815. },
  8816. beforeUpdate (chart, _args, options) {
  8817. const title = map.get(chart);
  8818. layouts.configure(chart, title, options);
  8819. title.options = options;
  8820. },
  8821. defaults: {
  8822. align: 'center',
  8823. display: false,
  8824. font: {
  8825. weight: 'normal'
  8826. },
  8827. fullSize: true,
  8828. padding: 0,
  8829. position: 'top',
  8830. text: '',
  8831. weight: 1500
  8832. },
  8833. defaultRoutes: {
  8834. color: 'color'
  8835. },
  8836. descriptors: {
  8837. _scriptable: true,
  8838. _indexable: false
  8839. }
  8840. };
  8841. const positioners = {
  8842. average (items) {
  8843. if (!items.length) {
  8844. return false;
  8845. }
  8846. let i, len;
  8847. let xSet = new Set();
  8848. let y = 0;
  8849. let count = 0;
  8850. for(i = 0, len = items.length; i < len; ++i){
  8851. const el = items[i].element;
  8852. if (el && el.hasValue()) {
  8853. const pos = el.tooltipPosition();
  8854. xSet.add(pos.x);
  8855. y += pos.y;
  8856. ++count;
  8857. }
  8858. }
  8859. const xAverage = [
  8860. ...xSet
  8861. ].reduce((a, b)=>a + b) / xSet.size;
  8862. return {
  8863. x: xAverage,
  8864. y: y / count
  8865. };
  8866. },
  8867. nearest (items, eventPosition) {
  8868. if (!items.length) {
  8869. return false;
  8870. }
  8871. let x = eventPosition.x;
  8872. let y = eventPosition.y;
  8873. let minDistance = Number.POSITIVE_INFINITY;
  8874. let i, len, nearestElement;
  8875. for(i = 0, len = items.length; i < len; ++i){
  8876. const el = items[i].element;
  8877. if (el && el.hasValue()) {
  8878. const center = el.getCenterPoint();
  8879. const d = helpers_segment.distanceBetweenPoints(eventPosition, center);
  8880. if (d < minDistance) {
  8881. minDistance = d;
  8882. nearestElement = el;
  8883. }
  8884. }
  8885. }
  8886. if (nearestElement) {
  8887. const tp = nearestElement.tooltipPosition();
  8888. x = tp.x;
  8889. y = tp.y;
  8890. }
  8891. return {
  8892. x,
  8893. y
  8894. };
  8895. }
  8896. };
  8897. function pushOrConcat(base, toPush) {
  8898. if (toPush) {
  8899. if (helpers_segment.isArray(toPush)) {
  8900. Array.prototype.push.apply(base, toPush);
  8901. } else {
  8902. base.push(toPush);
  8903. }
  8904. }
  8905. return base;
  8906. }
  8907. function splitNewlines(str) {
  8908. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  8909. return str.split('\n');
  8910. }
  8911. return str;
  8912. }
  8913. function createTooltipItem(chart, item) {
  8914. const { element , datasetIndex , index } = item;
  8915. const controller = chart.getDatasetMeta(datasetIndex).controller;
  8916. const { label , value } = controller.getLabelAndValue(index);
  8917. return {
  8918. chart,
  8919. label,
  8920. parsed: controller.getParsed(index),
  8921. raw: chart.data.datasets[datasetIndex].data[index],
  8922. formattedValue: value,
  8923. dataset: controller.getDataset(),
  8924. dataIndex: index,
  8925. datasetIndex,
  8926. element
  8927. };
  8928. }
  8929. function getTooltipSize(tooltip, options) {
  8930. const ctx = tooltip.chart.ctx;
  8931. const { body , footer , title } = tooltip;
  8932. const { boxWidth , boxHeight } = options;
  8933. const bodyFont = helpers_segment.toFont(options.bodyFont);
  8934. const titleFont = helpers_segment.toFont(options.titleFont);
  8935. const footerFont = helpers_segment.toFont(options.footerFont);
  8936. const titleLineCount = title.length;
  8937. const footerLineCount = footer.length;
  8938. const bodyLineItemCount = body.length;
  8939. const padding = helpers_segment.toPadding(options.padding);
  8940. let height = padding.height;
  8941. let width = 0;
  8942. let combinedBodyLength = body.reduce((count, bodyItem)=>count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
  8943. combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
  8944. if (titleLineCount) {
  8945. height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom;
  8946. }
  8947. if (combinedBodyLength) {
  8948. const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
  8949. height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing;
  8950. }
  8951. if (footerLineCount) {
  8952. height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing;
  8953. }
  8954. let widthPadding = 0;
  8955. const maxLineWidth = function(line) {
  8956. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  8957. };
  8958. ctx.save();
  8959. ctx.font = titleFont.string;
  8960. helpers_segment.each(tooltip.title, maxLineWidth);
  8961. ctx.font = bodyFont.string;
  8962. helpers_segment.each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
  8963. widthPadding = options.displayColors ? boxWidth + 2 + options.boxPadding : 0;
  8964. helpers_segment.each(body, (bodyItem)=>{
  8965. helpers_segment.each(bodyItem.before, maxLineWidth);
  8966. helpers_segment.each(bodyItem.lines, maxLineWidth);
  8967. helpers_segment.each(bodyItem.after, maxLineWidth);
  8968. });
  8969. widthPadding = 0;
  8970. ctx.font = footerFont.string;
  8971. helpers_segment.each(tooltip.footer, maxLineWidth);
  8972. ctx.restore();
  8973. width += padding.width;
  8974. return {
  8975. width,
  8976. height
  8977. };
  8978. }
  8979. function determineYAlign(chart, size) {
  8980. const { y , height } = size;
  8981. if (y < height / 2) {
  8982. return 'top';
  8983. } else if (y > chart.height - height / 2) {
  8984. return 'bottom';
  8985. }
  8986. return 'center';
  8987. }
  8988. function doesNotFitWithAlign(xAlign, chart, options, size) {
  8989. const { x , width } = size;
  8990. const caret = options.caretSize + options.caretPadding;
  8991. if (xAlign === 'left' && x + width + caret > chart.width) {
  8992. return true;
  8993. }
  8994. if (xAlign === 'right' && x - width - caret < 0) {
  8995. return true;
  8996. }
  8997. }
  8998. function determineXAlign(chart, options, size, yAlign) {
  8999. const { x , width } = size;
  9000. const { width: chartWidth , chartArea: { left , right } } = chart;
  9001. let xAlign = 'center';
  9002. if (yAlign === 'center') {
  9003. xAlign = x <= (left + right) / 2 ? 'left' : 'right';
  9004. } else if (x <= width / 2) {
  9005. xAlign = 'left';
  9006. } else if (x >= chartWidth - width / 2) {
  9007. xAlign = 'right';
  9008. }
  9009. if (doesNotFitWithAlign(xAlign, chart, options, size)) {
  9010. xAlign = 'center';
  9011. }
  9012. return xAlign;
  9013. }
  9014. function determineAlignment(chart, options, size) {
  9015. const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size);
  9016. return {
  9017. xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign),
  9018. yAlign
  9019. };
  9020. }
  9021. function alignX(size, xAlign) {
  9022. let { x , width } = size;
  9023. if (xAlign === 'right') {
  9024. x -= width;
  9025. } else if (xAlign === 'center') {
  9026. x -= width / 2;
  9027. }
  9028. return x;
  9029. }
  9030. function alignY(size, yAlign, paddingAndSize) {
  9031. let { y , height } = size;
  9032. if (yAlign === 'top') {
  9033. y += paddingAndSize;
  9034. } else if (yAlign === 'bottom') {
  9035. y -= height + paddingAndSize;
  9036. } else {
  9037. y -= height / 2;
  9038. }
  9039. return y;
  9040. }
  9041. function getBackgroundPoint(options, size, alignment, chart) {
  9042. const { caretSize , caretPadding , cornerRadius } = options;
  9043. const { xAlign , yAlign } = alignment;
  9044. const paddingAndSize = caretSize + caretPadding;
  9045. const { topLeft , topRight , bottomLeft , bottomRight } = helpers_segment.toTRBLCorners(cornerRadius);
  9046. let x = alignX(size, xAlign);
  9047. const y = alignY(size, yAlign, paddingAndSize);
  9048. if (yAlign === 'center') {
  9049. if (xAlign === 'left') {
  9050. x += paddingAndSize;
  9051. } else if (xAlign === 'right') {
  9052. x -= paddingAndSize;
  9053. }
  9054. } else if (xAlign === 'left') {
  9055. x -= Math.max(topLeft, bottomLeft) + caretSize;
  9056. } else if (xAlign === 'right') {
  9057. x += Math.max(topRight, bottomRight) + caretSize;
  9058. }
  9059. return {
  9060. x: helpers_segment._limitValue(x, 0, chart.width - size.width),
  9061. y: helpers_segment._limitValue(y, 0, chart.height - size.height)
  9062. };
  9063. }
  9064. function getAlignedX(tooltip, align, options) {
  9065. const padding = helpers_segment.toPadding(options.padding);
  9066. return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left;
  9067. }
  9068. function getBeforeAfterBodyLines(callback) {
  9069. return pushOrConcat([], splitNewlines(callback));
  9070. }
  9071. function createTooltipContext(parent, tooltip, tooltipItems) {
  9072. return helpers_segment.createContext(parent, {
  9073. tooltip,
  9074. tooltipItems,
  9075. type: 'tooltip'
  9076. });
  9077. }
  9078. function overrideCallbacks(callbacks, context) {
  9079. const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
  9080. return override ? callbacks.override(override) : callbacks;
  9081. }
  9082. const defaultCallbacks = {
  9083. beforeTitle: helpers_segment.noop,
  9084. title (tooltipItems) {
  9085. if (tooltipItems.length > 0) {
  9086. const item = tooltipItems[0];
  9087. const labels = item.chart.data.labels;
  9088. const labelCount = labels ? labels.length : 0;
  9089. if (this && this.options && this.options.mode === 'dataset') {
  9090. return item.dataset.label || '';
  9091. } else if (item.label) {
  9092. return item.label;
  9093. } else if (labelCount > 0 && item.dataIndex < labelCount) {
  9094. return labels[item.dataIndex];
  9095. }
  9096. }
  9097. return '';
  9098. },
  9099. afterTitle: helpers_segment.noop,
  9100. beforeBody: helpers_segment.noop,
  9101. beforeLabel: helpers_segment.noop,
  9102. label (tooltipItem) {
  9103. if (this && this.options && this.options.mode === 'dataset') {
  9104. return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
  9105. }
  9106. let label = tooltipItem.dataset.label || '';
  9107. if (label) {
  9108. label += ': ';
  9109. }
  9110. const value = tooltipItem.formattedValue;
  9111. if (!helpers_segment.isNullOrUndef(value)) {
  9112. label += value;
  9113. }
  9114. return label;
  9115. },
  9116. labelColor (tooltipItem) {
  9117. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9118. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9119. return {
  9120. borderColor: options.borderColor,
  9121. backgroundColor: options.backgroundColor,
  9122. borderWidth: options.borderWidth,
  9123. borderDash: options.borderDash,
  9124. borderDashOffset: options.borderDashOffset,
  9125. borderRadius: 0
  9126. };
  9127. },
  9128. labelTextColor () {
  9129. return this.options.bodyColor;
  9130. },
  9131. labelPointStyle (tooltipItem) {
  9132. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9133. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9134. return {
  9135. pointStyle: options.pointStyle,
  9136. rotation: options.rotation
  9137. };
  9138. },
  9139. afterLabel: helpers_segment.noop,
  9140. afterBody: helpers_segment.noop,
  9141. beforeFooter: helpers_segment.noop,
  9142. footer: helpers_segment.noop,
  9143. afterFooter: helpers_segment.noop
  9144. };
  9145. function invokeCallbackWithFallback(callbacks, name, ctx, arg) {
  9146. const result = callbacks[name].call(ctx, arg);
  9147. if (typeof result === 'undefined') {
  9148. return defaultCallbacks[name].call(ctx, arg);
  9149. }
  9150. return result;
  9151. }
  9152. class Tooltip extends Element {
  9153. static positioners = positioners;
  9154. constructor(config){
  9155. super();
  9156. this.opacity = 0;
  9157. this._active = [];
  9158. this._eventPosition = undefined;
  9159. this._size = undefined;
  9160. this._cachedAnimations = undefined;
  9161. this._tooltipItems = [];
  9162. this.$animations = undefined;
  9163. this.$context = undefined;
  9164. this.chart = config.chart;
  9165. this.options = config.options;
  9166. this.dataPoints = undefined;
  9167. this.title = undefined;
  9168. this.beforeBody = undefined;
  9169. this.body = undefined;
  9170. this.afterBody = undefined;
  9171. this.footer = undefined;
  9172. this.xAlign = undefined;
  9173. this.yAlign = undefined;
  9174. this.x = undefined;
  9175. this.y = undefined;
  9176. this.height = undefined;
  9177. this.width = undefined;
  9178. this.caretX = undefined;
  9179. this.caretY = undefined;
  9180. this.labelColors = undefined;
  9181. this.labelPointStyles = undefined;
  9182. this.labelTextColors = undefined;
  9183. }
  9184. initialize(options) {
  9185. this.options = options;
  9186. this._cachedAnimations = undefined;
  9187. this.$context = undefined;
  9188. }
  9189. _resolveAnimations() {
  9190. const cached = this._cachedAnimations;
  9191. if (cached) {
  9192. return cached;
  9193. }
  9194. const chart = this.chart;
  9195. const options = this.options.setContext(this.getContext());
  9196. const opts = options.enabled && chart.options.animation && options.animations;
  9197. const animations = new Animations(this.chart, opts);
  9198. if (opts._cacheable) {
  9199. this._cachedAnimations = Object.freeze(animations);
  9200. }
  9201. return animations;
  9202. }
  9203. getContext() {
  9204. return this.$context || (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems));
  9205. }
  9206. getTitle(context, options) {
  9207. const { callbacks } = options;
  9208. const beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context);
  9209. const title = invokeCallbackWithFallback(callbacks, 'title', this, context);
  9210. const afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context);
  9211. let lines = [];
  9212. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  9213. lines = pushOrConcat(lines, splitNewlines(title));
  9214. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  9215. return lines;
  9216. }
  9217. getBeforeBody(tooltipItems, options) {
  9218. return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems));
  9219. }
  9220. getBody(tooltipItems, options) {
  9221. const { callbacks } = options;
  9222. const bodyItems = [];
  9223. helpers_segment.each(tooltipItems, (context)=>{
  9224. const bodyItem = {
  9225. before: [],
  9226. lines: [],
  9227. after: []
  9228. };
  9229. const scoped = overrideCallbacks(callbacks, context);
  9230. pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', this, context)));
  9231. pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', this, context));
  9232. pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', this, context)));
  9233. bodyItems.push(bodyItem);
  9234. });
  9235. return bodyItems;
  9236. }
  9237. getAfterBody(tooltipItems, options) {
  9238. return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems));
  9239. }
  9240. getFooter(tooltipItems, options) {
  9241. const { callbacks } = options;
  9242. const beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems);
  9243. const footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems);
  9244. const afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems);
  9245. let lines = [];
  9246. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  9247. lines = pushOrConcat(lines, splitNewlines(footer));
  9248. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  9249. return lines;
  9250. }
  9251. _createItems(options) {
  9252. const active = this._active;
  9253. const data = this.chart.data;
  9254. const labelColors = [];
  9255. const labelPointStyles = [];
  9256. const labelTextColors = [];
  9257. let tooltipItems = [];
  9258. let i, len;
  9259. for(i = 0, len = active.length; i < len; ++i){
  9260. tooltipItems.push(createTooltipItem(this.chart, active[i]));
  9261. }
  9262. if (options.filter) {
  9263. tooltipItems = tooltipItems.filter((element, index, array)=>options.filter(element, index, array, data));
  9264. }
  9265. if (options.itemSort) {
  9266. tooltipItems = tooltipItems.sort((a, b)=>options.itemSort(a, b, data));
  9267. }
  9268. helpers_segment.each(tooltipItems, (context)=>{
  9269. const scoped = overrideCallbacks(options.callbacks, context);
  9270. labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', this, context));
  9271. labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', this, context));
  9272. labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', this, context));
  9273. });
  9274. this.labelColors = labelColors;
  9275. this.labelPointStyles = labelPointStyles;
  9276. this.labelTextColors = labelTextColors;
  9277. this.dataPoints = tooltipItems;
  9278. return tooltipItems;
  9279. }
  9280. update(changed, replay) {
  9281. const options = this.options.setContext(this.getContext());
  9282. const active = this._active;
  9283. let properties;
  9284. let tooltipItems = [];
  9285. if (!active.length) {
  9286. if (this.opacity !== 0) {
  9287. properties = {
  9288. opacity: 0
  9289. };
  9290. }
  9291. } else {
  9292. const position = positioners[options.position].call(this, active, this._eventPosition);
  9293. tooltipItems = this._createItems(options);
  9294. this.title = this.getTitle(tooltipItems, options);
  9295. this.beforeBody = this.getBeforeBody(tooltipItems, options);
  9296. this.body = this.getBody(tooltipItems, options);
  9297. this.afterBody = this.getAfterBody(tooltipItems, options);
  9298. this.footer = this.getFooter(tooltipItems, options);
  9299. const size = this._size = getTooltipSize(this, options);
  9300. const positionAndSize = Object.assign({}, position, size);
  9301. const alignment = determineAlignment(this.chart, options, positionAndSize);
  9302. const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart);
  9303. this.xAlign = alignment.xAlign;
  9304. this.yAlign = alignment.yAlign;
  9305. properties = {
  9306. opacity: 1,
  9307. x: backgroundPoint.x,
  9308. y: backgroundPoint.y,
  9309. width: size.width,
  9310. height: size.height,
  9311. caretX: position.x,
  9312. caretY: position.y
  9313. };
  9314. }
  9315. this._tooltipItems = tooltipItems;
  9316. this.$context = undefined;
  9317. if (properties) {
  9318. this._resolveAnimations().update(this, properties);
  9319. }
  9320. if (changed && options.external) {
  9321. options.external.call(this, {
  9322. chart: this.chart,
  9323. tooltip: this,
  9324. replay
  9325. });
  9326. }
  9327. }
  9328. drawCaret(tooltipPoint, ctx, size, options) {
  9329. const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
  9330. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  9331. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  9332. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  9333. }
  9334. getCaretPosition(tooltipPoint, size, options) {
  9335. const { xAlign , yAlign } = this;
  9336. const { caretSize , cornerRadius } = options;
  9337. const { topLeft , topRight , bottomLeft , bottomRight } = helpers_segment.toTRBLCorners(cornerRadius);
  9338. const { x: ptX , y: ptY } = tooltipPoint;
  9339. const { width , height } = size;
  9340. let x1, x2, x3, y1, y2, y3;
  9341. if (yAlign === 'center') {
  9342. y2 = ptY + height / 2;
  9343. if (xAlign === 'left') {
  9344. x1 = ptX;
  9345. x2 = x1 - caretSize;
  9346. y1 = y2 + caretSize;
  9347. y3 = y2 - caretSize;
  9348. } else {
  9349. x1 = ptX + width;
  9350. x2 = x1 + caretSize;
  9351. y1 = y2 - caretSize;
  9352. y3 = y2 + caretSize;
  9353. }
  9354. x3 = x1;
  9355. } else {
  9356. if (xAlign === 'left') {
  9357. x2 = ptX + Math.max(topLeft, bottomLeft) + caretSize;
  9358. } else if (xAlign === 'right') {
  9359. x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize;
  9360. } else {
  9361. x2 = this.caretX;
  9362. }
  9363. if (yAlign === 'top') {
  9364. y1 = ptY;
  9365. y2 = y1 - caretSize;
  9366. x1 = x2 - caretSize;
  9367. x3 = x2 + caretSize;
  9368. } else {
  9369. y1 = ptY + height;
  9370. y2 = y1 + caretSize;
  9371. x1 = x2 + caretSize;
  9372. x3 = x2 - caretSize;
  9373. }
  9374. y3 = y1;
  9375. }
  9376. return {
  9377. x1,
  9378. x2,
  9379. x3,
  9380. y1,
  9381. y2,
  9382. y3
  9383. };
  9384. }
  9385. drawTitle(pt, ctx, options) {
  9386. const title = this.title;
  9387. const length = title.length;
  9388. let titleFont, titleSpacing, i;
  9389. if (length) {
  9390. const rtlHelper = helpers_segment.getRtlAdapter(options.rtl, this.x, this.width);
  9391. pt.x = getAlignedX(this, options.titleAlign, options);
  9392. ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
  9393. ctx.textBaseline = 'middle';
  9394. titleFont = helpers_segment.toFont(options.titleFont);
  9395. titleSpacing = options.titleSpacing;
  9396. ctx.fillStyle = options.titleColor;
  9397. ctx.font = titleFont.string;
  9398. for(i = 0; i < length; ++i){
  9399. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
  9400. pt.y += titleFont.lineHeight + titleSpacing;
  9401. if (i + 1 === length) {
  9402. pt.y += options.titleMarginBottom - titleSpacing;
  9403. }
  9404. }
  9405. }
  9406. }
  9407. _drawColorBox(ctx, pt, i, rtlHelper, options) {
  9408. const labelColor = this.labelColors[i];
  9409. const labelPointStyle = this.labelPointStyles[i];
  9410. const { boxHeight , boxWidth } = options;
  9411. const bodyFont = helpers_segment.toFont(options.bodyFont);
  9412. const colorX = getAlignedX(this, 'left', options);
  9413. const rtlColorX = rtlHelper.x(colorX);
  9414. const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
  9415. const colorY = pt.y + yOffSet;
  9416. if (options.usePointStyle) {
  9417. const drawOptions = {
  9418. radius: Math.min(boxWidth, boxHeight) / 2,
  9419. pointStyle: labelPointStyle.pointStyle,
  9420. rotation: labelPointStyle.rotation,
  9421. borderWidth: 1
  9422. };
  9423. const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
  9424. const centerY = colorY + boxHeight / 2;
  9425. ctx.strokeStyle = options.multiKeyBackground;
  9426. ctx.fillStyle = options.multiKeyBackground;
  9427. helpers_segment.drawPoint(ctx, drawOptions, centerX, centerY);
  9428. ctx.strokeStyle = labelColor.borderColor;
  9429. ctx.fillStyle = labelColor.backgroundColor;
  9430. helpers_segment.drawPoint(ctx, drawOptions, centerX, centerY);
  9431. } else {
  9432. ctx.lineWidth = helpers_segment.isObject(labelColor.borderWidth) ? Math.max(...Object.values(labelColor.borderWidth)) : labelColor.borderWidth || 1;
  9433. ctx.strokeStyle = labelColor.borderColor;
  9434. ctx.setLineDash(labelColor.borderDash || []);
  9435. ctx.lineDashOffset = labelColor.borderDashOffset || 0;
  9436. const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
  9437. const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
  9438. const borderRadius = helpers_segment.toTRBLCorners(labelColor.borderRadius);
  9439. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  9440. ctx.beginPath();
  9441. ctx.fillStyle = options.multiKeyBackground;
  9442. helpers_segment.addRoundedRectPath(ctx, {
  9443. x: outerX,
  9444. y: colorY,
  9445. w: boxWidth,
  9446. h: boxHeight,
  9447. radius: borderRadius
  9448. });
  9449. ctx.fill();
  9450. ctx.stroke();
  9451. ctx.fillStyle = labelColor.backgroundColor;
  9452. ctx.beginPath();
  9453. helpers_segment.addRoundedRectPath(ctx, {
  9454. x: innerX,
  9455. y: colorY + 1,
  9456. w: boxWidth - 2,
  9457. h: boxHeight - 2,
  9458. radius: borderRadius
  9459. });
  9460. ctx.fill();
  9461. } else {
  9462. ctx.fillStyle = options.multiKeyBackground;
  9463. ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
  9464. ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
  9465. ctx.fillStyle = labelColor.backgroundColor;
  9466. ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
  9467. }
  9468. }
  9469. ctx.fillStyle = this.labelTextColors[i];
  9470. }
  9471. drawBody(pt, ctx, options) {
  9472. const { body } = this;
  9473. const { bodySpacing , bodyAlign , displayColors , boxHeight , boxWidth , boxPadding } = options;
  9474. const bodyFont = helpers_segment.toFont(options.bodyFont);
  9475. let bodyLineHeight = bodyFont.lineHeight;
  9476. let xLinePadding = 0;
  9477. const rtlHelper = helpers_segment.getRtlAdapter(options.rtl, this.x, this.width);
  9478. const fillLineOfText = function(line) {
  9479. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
  9480. pt.y += bodyLineHeight + bodySpacing;
  9481. };
  9482. const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  9483. let bodyItem, textColor, lines, i, j, ilen, jlen;
  9484. ctx.textAlign = bodyAlign;
  9485. ctx.textBaseline = 'middle';
  9486. ctx.font = bodyFont.string;
  9487. pt.x = getAlignedX(this, bodyAlignForCalculation, options);
  9488. ctx.fillStyle = options.bodyColor;
  9489. helpers_segment.each(this.beforeBody, fillLineOfText);
  9490. xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? boxWidth / 2 + boxPadding : boxWidth + 2 + boxPadding : 0;
  9491. for(i = 0, ilen = body.length; i < ilen; ++i){
  9492. bodyItem = body[i];
  9493. textColor = this.labelTextColors[i];
  9494. ctx.fillStyle = textColor;
  9495. helpers_segment.each(bodyItem.before, fillLineOfText);
  9496. lines = bodyItem.lines;
  9497. if (displayColors && lines.length) {
  9498. this._drawColorBox(ctx, pt, i, rtlHelper, options);
  9499. bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
  9500. }
  9501. for(j = 0, jlen = lines.length; j < jlen; ++j){
  9502. fillLineOfText(lines[j]);
  9503. bodyLineHeight = bodyFont.lineHeight;
  9504. }
  9505. helpers_segment.each(bodyItem.after, fillLineOfText);
  9506. }
  9507. xLinePadding = 0;
  9508. bodyLineHeight = bodyFont.lineHeight;
  9509. helpers_segment.each(this.afterBody, fillLineOfText);
  9510. pt.y -= bodySpacing;
  9511. }
  9512. drawFooter(pt, ctx, options) {
  9513. const footer = this.footer;
  9514. const length = footer.length;
  9515. let footerFont, i;
  9516. if (length) {
  9517. const rtlHelper = helpers_segment.getRtlAdapter(options.rtl, this.x, this.width);
  9518. pt.x = getAlignedX(this, options.footerAlign, options);
  9519. pt.y += options.footerMarginTop;
  9520. ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
  9521. ctx.textBaseline = 'middle';
  9522. footerFont = helpers_segment.toFont(options.footerFont);
  9523. ctx.fillStyle = options.footerColor;
  9524. ctx.font = footerFont.string;
  9525. for(i = 0; i < length; ++i){
  9526. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
  9527. pt.y += footerFont.lineHeight + options.footerSpacing;
  9528. }
  9529. }
  9530. }
  9531. drawBackground(pt, ctx, tooltipSize, options) {
  9532. const { xAlign , yAlign } = this;
  9533. const { x , y } = pt;
  9534. const { width , height } = tooltipSize;
  9535. const { topLeft , topRight , bottomLeft , bottomRight } = helpers_segment.toTRBLCorners(options.cornerRadius);
  9536. ctx.fillStyle = options.backgroundColor;
  9537. ctx.strokeStyle = options.borderColor;
  9538. ctx.lineWidth = options.borderWidth;
  9539. ctx.beginPath();
  9540. ctx.moveTo(x + topLeft, y);
  9541. if (yAlign === 'top') {
  9542. this.drawCaret(pt, ctx, tooltipSize, options);
  9543. }
  9544. ctx.lineTo(x + width - topRight, y);
  9545. ctx.quadraticCurveTo(x + width, y, x + width, y + topRight);
  9546. if (yAlign === 'center' && xAlign === 'right') {
  9547. this.drawCaret(pt, ctx, tooltipSize, options);
  9548. }
  9549. ctx.lineTo(x + width, y + height - bottomRight);
  9550. ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height);
  9551. if (yAlign === 'bottom') {
  9552. this.drawCaret(pt, ctx, tooltipSize, options);
  9553. }
  9554. ctx.lineTo(x + bottomLeft, y + height);
  9555. ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft);
  9556. if (yAlign === 'center' && xAlign === 'left') {
  9557. this.drawCaret(pt, ctx, tooltipSize, options);
  9558. }
  9559. ctx.lineTo(x, y + topLeft);
  9560. ctx.quadraticCurveTo(x, y, x + topLeft, y);
  9561. ctx.closePath();
  9562. ctx.fill();
  9563. if (options.borderWidth > 0) {
  9564. ctx.stroke();
  9565. }
  9566. }
  9567. _updateAnimationTarget(options) {
  9568. const chart = this.chart;
  9569. const anims = this.$animations;
  9570. const animX = anims && anims.x;
  9571. const animY = anims && anims.y;
  9572. if (animX || animY) {
  9573. const position = positioners[options.position].call(this, this._active, this._eventPosition);
  9574. if (!position) {
  9575. return;
  9576. }
  9577. const size = this._size = getTooltipSize(this, options);
  9578. const positionAndSize = Object.assign({}, position, this._size);
  9579. const alignment = determineAlignment(chart, options, positionAndSize);
  9580. const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
  9581. if (animX._to !== point.x || animY._to !== point.y) {
  9582. this.xAlign = alignment.xAlign;
  9583. this.yAlign = alignment.yAlign;
  9584. this.width = size.width;
  9585. this.height = size.height;
  9586. this.caretX = position.x;
  9587. this.caretY = position.y;
  9588. this._resolveAnimations().update(this, point);
  9589. }
  9590. }
  9591. }
  9592. _willRender() {
  9593. return !!this.opacity;
  9594. }
  9595. draw(ctx) {
  9596. const options = this.options.setContext(this.getContext());
  9597. let opacity = this.opacity;
  9598. if (!opacity) {
  9599. return;
  9600. }
  9601. this._updateAnimationTarget(options);
  9602. const tooltipSize = {
  9603. width: this.width,
  9604. height: this.height
  9605. };
  9606. const pt = {
  9607. x: this.x,
  9608. y: this.y
  9609. };
  9610. opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
  9611. const padding = helpers_segment.toPadding(options.padding);
  9612. const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length;
  9613. if (options.enabled && hasTooltipContent) {
  9614. ctx.save();
  9615. ctx.globalAlpha = opacity;
  9616. this.drawBackground(pt, ctx, tooltipSize, options);
  9617. helpers_segment.overrideTextDirection(ctx, options.textDirection);
  9618. pt.y += padding.top;
  9619. this.drawTitle(pt, ctx, options);
  9620. this.drawBody(pt, ctx, options);
  9621. this.drawFooter(pt, ctx, options);
  9622. helpers_segment.restoreTextDirection(ctx, options.textDirection);
  9623. ctx.restore();
  9624. }
  9625. }
  9626. getActiveElements() {
  9627. return this._active || [];
  9628. }
  9629. setActiveElements(activeElements, eventPosition) {
  9630. const lastActive = this._active;
  9631. const active = activeElements.map(({ datasetIndex , index })=>{
  9632. const meta = this.chart.getDatasetMeta(datasetIndex);
  9633. if (!meta) {
  9634. throw new Error('Cannot find a dataset at index ' + datasetIndex);
  9635. }
  9636. return {
  9637. datasetIndex,
  9638. element: meta.data[index],
  9639. index
  9640. };
  9641. });
  9642. const changed = !helpers_segment._elementsEqual(lastActive, active);
  9643. const positionChanged = this._positionChanged(active, eventPosition);
  9644. if (changed || positionChanged) {
  9645. this._active = active;
  9646. this._eventPosition = eventPosition;
  9647. this._ignoreReplayEvents = true;
  9648. this.update(true);
  9649. }
  9650. }
  9651. handleEvent(e, replay, inChartArea = true) {
  9652. if (replay && this._ignoreReplayEvents) {
  9653. return false;
  9654. }
  9655. this._ignoreReplayEvents = false;
  9656. const options = this.options;
  9657. const lastActive = this._active || [];
  9658. const active = this._getActiveElements(e, lastActive, replay, inChartArea);
  9659. const positionChanged = this._positionChanged(active, e);
  9660. const changed = replay || !helpers_segment._elementsEqual(active, lastActive) || positionChanged;
  9661. if (changed) {
  9662. this._active = active;
  9663. if (options.enabled || options.external) {
  9664. this._eventPosition = {
  9665. x: e.x,
  9666. y: e.y
  9667. };
  9668. this.update(true, replay);
  9669. }
  9670. }
  9671. return changed;
  9672. }
  9673. _getActiveElements(e, lastActive, replay, inChartArea) {
  9674. const options = this.options;
  9675. if (e.type === 'mouseout') {
  9676. return [];
  9677. }
  9678. if (!inChartArea) {
  9679. return lastActive.filter((i)=>this.chart.data.datasets[i.datasetIndex] && this.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined);
  9680. }
  9681. const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay);
  9682. if (options.reverse) {
  9683. active.reverse();
  9684. }
  9685. return active;
  9686. }
  9687. _positionChanged(active, e) {
  9688. const { caretX , caretY , options } = this;
  9689. const position = positioners[options.position].call(this, active, e);
  9690. return position !== false && (caretX !== position.x || caretY !== position.y);
  9691. }
  9692. }
  9693. var plugin_tooltip = {
  9694. id: 'tooltip',
  9695. _element: Tooltip,
  9696. positioners,
  9697. afterInit (chart, _args, options) {
  9698. if (options) {
  9699. chart.tooltip = new Tooltip({
  9700. chart,
  9701. options
  9702. });
  9703. }
  9704. },
  9705. beforeUpdate (chart, _args, options) {
  9706. if (chart.tooltip) {
  9707. chart.tooltip.initialize(options);
  9708. }
  9709. },
  9710. reset (chart, _args, options) {
  9711. if (chart.tooltip) {
  9712. chart.tooltip.initialize(options);
  9713. }
  9714. },
  9715. afterDraw (chart) {
  9716. const tooltip = chart.tooltip;
  9717. if (tooltip && tooltip._willRender()) {
  9718. const args = {
  9719. tooltip
  9720. };
  9721. if (chart.notifyPlugins('beforeTooltipDraw', {
  9722. ...args,
  9723. cancelable: true
  9724. }) === false) {
  9725. return;
  9726. }
  9727. tooltip.draw(chart.ctx);
  9728. chart.notifyPlugins('afterTooltipDraw', args);
  9729. }
  9730. },
  9731. afterEvent (chart, args) {
  9732. if (chart.tooltip) {
  9733. const useFinalPosition = args.replay;
  9734. if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) {
  9735. args.changed = true;
  9736. }
  9737. }
  9738. },
  9739. defaults: {
  9740. enabled: true,
  9741. external: null,
  9742. position: 'average',
  9743. backgroundColor: 'rgba(0,0,0,0.8)',
  9744. titleColor: '#fff',
  9745. titleFont: {
  9746. weight: 'bold'
  9747. },
  9748. titleSpacing: 2,
  9749. titleMarginBottom: 6,
  9750. titleAlign: 'left',
  9751. bodyColor: '#fff',
  9752. bodySpacing: 2,
  9753. bodyFont: {},
  9754. bodyAlign: 'left',
  9755. footerColor: '#fff',
  9756. footerSpacing: 2,
  9757. footerMarginTop: 6,
  9758. footerFont: {
  9759. weight: 'bold'
  9760. },
  9761. footerAlign: 'left',
  9762. padding: 6,
  9763. caretPadding: 2,
  9764. caretSize: 5,
  9765. cornerRadius: 6,
  9766. boxHeight: (ctx, opts)=>opts.bodyFont.size,
  9767. boxWidth: (ctx, opts)=>opts.bodyFont.size,
  9768. multiKeyBackground: '#fff',
  9769. displayColors: true,
  9770. boxPadding: 0,
  9771. borderColor: 'rgba(0,0,0,0)',
  9772. borderWidth: 0,
  9773. animation: {
  9774. duration: 400,
  9775. easing: 'easeOutQuart'
  9776. },
  9777. animations: {
  9778. numbers: {
  9779. type: 'number',
  9780. properties: [
  9781. 'x',
  9782. 'y',
  9783. 'width',
  9784. 'height',
  9785. 'caretX',
  9786. 'caretY'
  9787. ]
  9788. },
  9789. opacity: {
  9790. easing: 'linear',
  9791. duration: 200
  9792. }
  9793. },
  9794. callbacks: defaultCallbacks
  9795. },
  9796. defaultRoutes: {
  9797. bodyFont: 'font',
  9798. footerFont: 'font',
  9799. titleFont: 'font'
  9800. },
  9801. descriptors: {
  9802. _scriptable: (name)=>name !== 'filter' && name !== 'itemSort' && name !== 'external',
  9803. _indexable: false,
  9804. callbacks: {
  9805. _scriptable: false,
  9806. _indexable: false
  9807. },
  9808. animation: {
  9809. _fallback: false
  9810. },
  9811. animations: {
  9812. _fallback: 'animation'
  9813. }
  9814. },
  9815. additionalOptionScopes: [
  9816. 'interaction'
  9817. ]
  9818. };
  9819. var plugins = /*#__PURE__*/Object.freeze({
  9820. __proto__: null,
  9821. Colors: plugin_colors,
  9822. Decimation: plugin_decimation,
  9823. Filler: index,
  9824. Legend: plugin_legend,
  9825. SubTitle: plugin_subtitle,
  9826. Title: plugin_title,
  9827. Tooltip: plugin_tooltip
  9828. });
  9829. const addIfString = (labels, raw, index, addedLabels)=>{
  9830. if (typeof raw === 'string') {
  9831. index = labels.push(raw) - 1;
  9832. addedLabels.unshift({
  9833. index,
  9834. label: raw
  9835. });
  9836. } else if (isNaN(raw)) {
  9837. index = null;
  9838. }
  9839. return index;
  9840. };
  9841. function findOrAddLabel(labels, raw, index, addedLabels) {
  9842. const first = labels.indexOf(raw);
  9843. if (first === -1) {
  9844. return addIfString(labels, raw, index, addedLabels);
  9845. }
  9846. const last = labels.lastIndexOf(raw);
  9847. return first !== last ? index : first;
  9848. }
  9849. const validIndex = (index, max)=>index === null ? null : helpers_segment._limitValue(Math.round(index), 0, max);
  9850. function _getLabelForValue(value) {
  9851. const labels = this.getLabels();
  9852. if (value >= 0 && value < labels.length) {
  9853. return labels[value];
  9854. }
  9855. return value;
  9856. }
  9857. class CategoryScale extends Scale {
  9858. static id = 'category';
  9859. static defaults = {
  9860. ticks: {
  9861. callback: _getLabelForValue
  9862. }
  9863. };
  9864. constructor(cfg){
  9865. super(cfg);
  9866. this._startValue = undefined;
  9867. this._valueRange = 0;
  9868. this._addedLabels = [];
  9869. }
  9870. init(scaleOptions) {
  9871. const added = this._addedLabels;
  9872. if (added.length) {
  9873. const labels = this.getLabels();
  9874. for (const { index , label } of added){
  9875. if (labels[index] === label) {
  9876. labels.splice(index, 1);
  9877. }
  9878. }
  9879. this._addedLabels = [];
  9880. }
  9881. super.init(scaleOptions);
  9882. }
  9883. parse(raw, index) {
  9884. if (helpers_segment.isNullOrUndef(raw)) {
  9885. return null;
  9886. }
  9887. const labels = this.getLabels();
  9888. index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, helpers_segment.valueOrDefault(index, raw), this._addedLabels);
  9889. return validIndex(index, labels.length - 1);
  9890. }
  9891. determineDataLimits() {
  9892. const { minDefined , maxDefined } = this.getUserBounds();
  9893. let { min , max } = this.getMinMax(true);
  9894. if (this.options.bounds === 'ticks') {
  9895. if (!minDefined) {
  9896. min = 0;
  9897. }
  9898. if (!maxDefined) {
  9899. max = this.getLabels().length - 1;
  9900. }
  9901. }
  9902. this.min = min;
  9903. this.max = max;
  9904. }
  9905. buildTicks() {
  9906. const min = this.min;
  9907. const max = this.max;
  9908. const offset = this.options.offset;
  9909. const ticks = [];
  9910. let labels = this.getLabels();
  9911. labels = min === 0 && max === labels.length - 1 ? labels : labels.slice(min, max + 1);
  9912. this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
  9913. this._startValue = this.min - (offset ? 0.5 : 0);
  9914. for(let value = min; value <= max; value++){
  9915. ticks.push({
  9916. value
  9917. });
  9918. }
  9919. return ticks;
  9920. }
  9921. getLabelForValue(value) {
  9922. return _getLabelForValue.call(this, value);
  9923. }
  9924. configure() {
  9925. super.configure();
  9926. if (!this.isHorizontal()) {
  9927. this._reversePixels = !this._reversePixels;
  9928. }
  9929. }
  9930. getPixelForValue(value) {
  9931. if (typeof value !== 'number') {
  9932. value = this.parse(value);
  9933. }
  9934. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  9935. }
  9936. getPixelForTick(index) {
  9937. const ticks = this.ticks;
  9938. if (index < 0 || index > ticks.length - 1) {
  9939. return null;
  9940. }
  9941. return this.getPixelForValue(ticks[index].value);
  9942. }
  9943. getValueForPixel(pixel) {
  9944. return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange);
  9945. }
  9946. getBasePixel() {
  9947. return this.bottom;
  9948. }
  9949. }
  9950. function generateTicks$1(generationOptions, dataRange) {
  9951. const ticks = [];
  9952. const MIN_SPACING = 1e-14;
  9953. const { bounds , step , min , max , precision , count , maxTicks , maxDigits , includeBounds } = generationOptions;
  9954. const unit = step || 1;
  9955. const maxSpaces = maxTicks - 1;
  9956. const { min: rmin , max: rmax } = dataRange;
  9957. const minDefined = !helpers_segment.isNullOrUndef(min);
  9958. const maxDefined = !helpers_segment.isNullOrUndef(max);
  9959. const countDefined = !helpers_segment.isNullOrUndef(count);
  9960. const minSpacing = (rmax - rmin) / (maxDigits + 1);
  9961. let spacing = helpers_segment.niceNum((rmax - rmin) / maxSpaces / unit) * unit;
  9962. let factor, niceMin, niceMax, numSpaces;
  9963. if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
  9964. return [
  9965. {
  9966. value: rmin
  9967. },
  9968. {
  9969. value: rmax
  9970. }
  9971. ];
  9972. }
  9973. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  9974. if (numSpaces > maxSpaces) {
  9975. spacing = helpers_segment.niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
  9976. }
  9977. if (!helpers_segment.isNullOrUndef(precision)) {
  9978. factor = Math.pow(10, precision);
  9979. spacing = Math.ceil(spacing * factor) / factor;
  9980. }
  9981. if (bounds === 'ticks') {
  9982. niceMin = Math.floor(rmin / spacing) * spacing;
  9983. niceMax = Math.ceil(rmax / spacing) * spacing;
  9984. } else {
  9985. niceMin = rmin;
  9986. niceMax = rmax;
  9987. }
  9988. if (minDefined && maxDefined && step && helpers_segment.almostWhole((max - min) / step, spacing / 1000)) {
  9989. numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));
  9990. spacing = (max - min) / numSpaces;
  9991. niceMin = min;
  9992. niceMax = max;
  9993. } else if (countDefined) {
  9994. niceMin = minDefined ? min : niceMin;
  9995. niceMax = maxDefined ? max : niceMax;
  9996. numSpaces = count - 1;
  9997. spacing = (niceMax - niceMin) / numSpaces;
  9998. } else {
  9999. numSpaces = (niceMax - niceMin) / spacing;
  10000. if (helpers_segment.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10001. numSpaces = Math.round(numSpaces);
  10002. } else {
  10003. numSpaces = Math.ceil(numSpaces);
  10004. }
  10005. }
  10006. const decimalPlaces = Math.max(helpers_segment._decimalPlaces(spacing), helpers_segment._decimalPlaces(niceMin));
  10007. factor = Math.pow(10, helpers_segment.isNullOrUndef(precision) ? decimalPlaces : precision);
  10008. niceMin = Math.round(niceMin * factor) / factor;
  10009. niceMax = Math.round(niceMax * factor) / factor;
  10010. let j = 0;
  10011. if (minDefined) {
  10012. if (includeBounds && niceMin !== min) {
  10013. ticks.push({
  10014. value: min
  10015. });
  10016. if (niceMin < min) {
  10017. j++;
  10018. }
  10019. if (helpers_segment.almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {
  10020. j++;
  10021. }
  10022. } else if (niceMin < min) {
  10023. j++;
  10024. }
  10025. }
  10026. for(; j < numSpaces; ++j){
  10027. const tickValue = Math.round((niceMin + j * spacing) * factor) / factor;
  10028. if (maxDefined && tickValue > max) {
  10029. break;
  10030. }
  10031. ticks.push({
  10032. value: tickValue
  10033. });
  10034. }
  10035. if (maxDefined && includeBounds && niceMax !== max) {
  10036. if (ticks.length && helpers_segment.almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {
  10037. ticks[ticks.length - 1].value = max;
  10038. } else {
  10039. ticks.push({
  10040. value: max
  10041. });
  10042. }
  10043. } else if (!maxDefined || niceMax === max) {
  10044. ticks.push({
  10045. value: niceMax
  10046. });
  10047. }
  10048. return ticks;
  10049. }
  10050. function relativeLabelSize(value, minSpacing, { horizontal , minRotation }) {
  10051. const rad = helpers_segment.toRadians(minRotation);
  10052. const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;
  10053. const length = 0.75 * minSpacing * ('' + value).length;
  10054. return Math.min(minSpacing / ratio, length);
  10055. }
  10056. class LinearScaleBase extends Scale {
  10057. constructor(cfg){
  10058. super(cfg);
  10059. this.start = undefined;
  10060. this.end = undefined;
  10061. this._startValue = undefined;
  10062. this._endValue = undefined;
  10063. this._valueRange = 0;
  10064. }
  10065. parse(raw, index) {
  10066. if (helpers_segment.isNullOrUndef(raw)) {
  10067. return null;
  10068. }
  10069. if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
  10070. return null;
  10071. }
  10072. return +raw;
  10073. }
  10074. handleTickRangeOptions() {
  10075. const { beginAtZero } = this.options;
  10076. const { minDefined , maxDefined } = this.getUserBounds();
  10077. let { min , max } = this;
  10078. const setMin = (v)=>min = minDefined ? min : v;
  10079. const setMax = (v)=>max = maxDefined ? max : v;
  10080. if (beginAtZero) {
  10081. const minSign = helpers_segment.sign(min);
  10082. const maxSign = helpers_segment.sign(max);
  10083. if (minSign < 0 && maxSign < 0) {
  10084. setMax(0);
  10085. } else if (minSign > 0 && maxSign > 0) {
  10086. setMin(0);
  10087. }
  10088. }
  10089. if (min === max) {
  10090. let offset = max === 0 ? 1 : Math.abs(max * 0.05);
  10091. setMax(max + offset);
  10092. if (!beginAtZero) {
  10093. setMin(min - offset);
  10094. }
  10095. }
  10096. this.min = min;
  10097. this.max = max;
  10098. }
  10099. getTickLimit() {
  10100. const tickOpts = this.options.ticks;
  10101. let { maxTicksLimit , stepSize } = tickOpts;
  10102. let maxTicks;
  10103. if (stepSize) {
  10104. maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1;
  10105. if (maxTicks > 1000) {
  10106. console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`);
  10107. maxTicks = 1000;
  10108. }
  10109. } else {
  10110. maxTicks = this.computeTickLimit();
  10111. maxTicksLimit = maxTicksLimit || 11;
  10112. }
  10113. if (maxTicksLimit) {
  10114. maxTicks = Math.min(maxTicksLimit, maxTicks);
  10115. }
  10116. return maxTicks;
  10117. }
  10118. computeTickLimit() {
  10119. return Number.POSITIVE_INFINITY;
  10120. }
  10121. buildTicks() {
  10122. const opts = this.options;
  10123. const tickOpts = opts.ticks;
  10124. let maxTicks = this.getTickLimit();
  10125. maxTicks = Math.max(2, maxTicks);
  10126. const numericGeneratorOptions = {
  10127. maxTicks,
  10128. bounds: opts.bounds,
  10129. min: opts.min,
  10130. max: opts.max,
  10131. precision: tickOpts.precision,
  10132. step: tickOpts.stepSize,
  10133. count: tickOpts.count,
  10134. maxDigits: this._maxDigits(),
  10135. horizontal: this.isHorizontal(),
  10136. minRotation: tickOpts.minRotation || 0,
  10137. includeBounds: tickOpts.includeBounds !== false
  10138. };
  10139. const dataRange = this._range || this;
  10140. const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
  10141. if (opts.bounds === 'ticks') {
  10142. helpers_segment._setMinAndMaxByKey(ticks, this, 'value');
  10143. }
  10144. if (opts.reverse) {
  10145. ticks.reverse();
  10146. this.start = this.max;
  10147. this.end = this.min;
  10148. } else {
  10149. this.start = this.min;
  10150. this.end = this.max;
  10151. }
  10152. return ticks;
  10153. }
  10154. configure() {
  10155. const ticks = this.ticks;
  10156. let start = this.min;
  10157. let end = this.max;
  10158. super.configure();
  10159. if (this.options.offset && ticks.length) {
  10160. const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  10161. start -= offset;
  10162. end += offset;
  10163. }
  10164. this._startValue = start;
  10165. this._endValue = end;
  10166. this._valueRange = end - start;
  10167. }
  10168. getLabelForValue(value) {
  10169. return helpers_segment.formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  10170. }
  10171. }
  10172. class LinearScale extends LinearScaleBase {
  10173. static id = 'linear';
  10174. static defaults = {
  10175. ticks: {
  10176. callback: helpers_segment.Ticks.formatters.numeric
  10177. }
  10178. };
  10179. determineDataLimits() {
  10180. const { min , max } = this.getMinMax(true);
  10181. this.min = helpers_segment.isNumberFinite(min) ? min : 0;
  10182. this.max = helpers_segment.isNumberFinite(max) ? max : 1;
  10183. this.handleTickRangeOptions();
  10184. }
  10185. computeTickLimit() {
  10186. const horizontal = this.isHorizontal();
  10187. const length = horizontal ? this.width : this.height;
  10188. const minRotation = helpers_segment.toRadians(this.options.ticks.minRotation);
  10189. const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;
  10190. const tickFont = this._resolveTickFontOptions(0);
  10191. return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));
  10192. }
  10193. getPixelForValue(value) {
  10194. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  10195. }
  10196. getValueForPixel(pixel) {
  10197. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  10198. }
  10199. }
  10200. const log10Floor = (v)=>Math.floor(helpers_segment.log10(v));
  10201. const changeExponent = (v, m)=>Math.pow(10, log10Floor(v) + m);
  10202. function isMajor(tickVal) {
  10203. const remain = tickVal / Math.pow(10, log10Floor(tickVal));
  10204. return remain === 1;
  10205. }
  10206. function steps(min, max, rangeExp) {
  10207. const rangeStep = Math.pow(10, rangeExp);
  10208. const start = Math.floor(min / rangeStep);
  10209. const end = Math.ceil(max / rangeStep);
  10210. return end - start;
  10211. }
  10212. function startExp(min, max) {
  10213. const range = max - min;
  10214. let rangeExp = log10Floor(range);
  10215. while(steps(min, max, rangeExp) > 10){
  10216. rangeExp++;
  10217. }
  10218. while(steps(min, max, rangeExp) < 10){
  10219. rangeExp--;
  10220. }
  10221. return Math.min(rangeExp, log10Floor(min));
  10222. }
  10223. function generateTicks(generationOptions, { min , max }) {
  10224. min = helpers_segment.finiteOrDefault(generationOptions.min, min);
  10225. const ticks = [];
  10226. const minExp = log10Floor(min);
  10227. let exp = startExp(min, max);
  10228. let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  10229. const stepSize = Math.pow(10, exp);
  10230. const base = minExp > exp ? Math.pow(10, minExp) : 0;
  10231. const start = Math.round((min - base) * precision) / precision;
  10232. const offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10;
  10233. let significand = Math.floor((start - offset) / Math.pow(10, exp));
  10234. let value = helpers_segment.finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision);
  10235. while(value < max){
  10236. ticks.push({
  10237. value,
  10238. major: isMajor(value),
  10239. significand
  10240. });
  10241. if (significand >= 10) {
  10242. significand = significand < 15 ? 15 : 20;
  10243. } else {
  10244. significand++;
  10245. }
  10246. if (significand >= 20) {
  10247. exp++;
  10248. significand = 2;
  10249. precision = exp >= 0 ? 1 : precision;
  10250. }
  10251. value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision;
  10252. }
  10253. const lastTick = helpers_segment.finiteOrDefault(generationOptions.max, value);
  10254. ticks.push({
  10255. value: lastTick,
  10256. major: isMajor(lastTick),
  10257. significand
  10258. });
  10259. return ticks;
  10260. }
  10261. class LogarithmicScale extends Scale {
  10262. static id = 'logarithmic';
  10263. static defaults = {
  10264. ticks: {
  10265. callback: helpers_segment.Ticks.formatters.logarithmic,
  10266. major: {
  10267. enabled: true
  10268. }
  10269. }
  10270. };
  10271. constructor(cfg){
  10272. super(cfg);
  10273. this.start = undefined;
  10274. this.end = undefined;
  10275. this._startValue = undefined;
  10276. this._valueRange = 0;
  10277. }
  10278. parse(raw, index) {
  10279. const value = LinearScaleBase.prototype.parse.apply(this, [
  10280. raw,
  10281. index
  10282. ]);
  10283. if (value === 0) {
  10284. this._zero = true;
  10285. return undefined;
  10286. }
  10287. return helpers_segment.isNumberFinite(value) && value > 0 ? value : null;
  10288. }
  10289. determineDataLimits() {
  10290. const { min , max } = this.getMinMax(true);
  10291. this.min = helpers_segment.isNumberFinite(min) ? Math.max(0, min) : null;
  10292. this.max = helpers_segment.isNumberFinite(max) ? Math.max(0, max) : null;
  10293. if (this.options.beginAtZero) {
  10294. this._zero = true;
  10295. }
  10296. if (this._zero && this.min !== this._suggestedMin && !helpers_segment.isNumberFinite(this._userMin)) {
  10297. this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0);
  10298. }
  10299. this.handleTickRangeOptions();
  10300. }
  10301. handleTickRangeOptions() {
  10302. const { minDefined , maxDefined } = this.getUserBounds();
  10303. let min = this.min;
  10304. let max = this.max;
  10305. const setMin = (v)=>min = minDefined ? min : v;
  10306. const setMax = (v)=>max = maxDefined ? max : v;
  10307. if (min === max) {
  10308. if (min <= 0) {
  10309. setMin(1);
  10310. setMax(10);
  10311. } else {
  10312. setMin(changeExponent(min, -1));
  10313. setMax(changeExponent(max, +1));
  10314. }
  10315. }
  10316. if (min <= 0) {
  10317. setMin(changeExponent(max, -1));
  10318. }
  10319. if (max <= 0) {
  10320. setMax(changeExponent(min, +1));
  10321. }
  10322. this.min = min;
  10323. this.max = max;
  10324. }
  10325. buildTicks() {
  10326. const opts = this.options;
  10327. const generationOptions = {
  10328. min: this._userMin,
  10329. max: this._userMax
  10330. };
  10331. const ticks = generateTicks(generationOptions, this);
  10332. if (opts.bounds === 'ticks') {
  10333. helpers_segment._setMinAndMaxByKey(ticks, this, 'value');
  10334. }
  10335. if (opts.reverse) {
  10336. ticks.reverse();
  10337. this.start = this.max;
  10338. this.end = this.min;
  10339. } else {
  10340. this.start = this.min;
  10341. this.end = this.max;
  10342. }
  10343. return ticks;
  10344. }
  10345. getLabelForValue(value) {
  10346. return value === undefined ? '0' : helpers_segment.formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  10347. }
  10348. configure() {
  10349. const start = this.min;
  10350. super.configure();
  10351. this._startValue = helpers_segment.log10(start);
  10352. this._valueRange = helpers_segment.log10(this.max) - helpers_segment.log10(start);
  10353. }
  10354. getPixelForValue(value) {
  10355. if (value === undefined || value === 0) {
  10356. value = this.min;
  10357. }
  10358. if (value === null || isNaN(value)) {
  10359. return NaN;
  10360. }
  10361. return this.getPixelForDecimal(value === this.min ? 0 : (helpers_segment.log10(value) - this._startValue) / this._valueRange);
  10362. }
  10363. getValueForPixel(pixel) {
  10364. const decimal = this.getDecimalForPixel(pixel);
  10365. return Math.pow(10, this._startValue + decimal * this._valueRange);
  10366. }
  10367. }
  10368. function getTickBackdropHeight(opts) {
  10369. const tickOpts = opts.ticks;
  10370. if (tickOpts.display && opts.display) {
  10371. const padding = helpers_segment.toPadding(tickOpts.backdropPadding);
  10372. return helpers_segment.valueOrDefault(tickOpts.font && tickOpts.font.size, helpers_segment.defaults.font.size) + padding.height;
  10373. }
  10374. return 0;
  10375. }
  10376. function measureLabelSize(ctx, font, label) {
  10377. label = helpers_segment.isArray(label) ? label : [
  10378. label
  10379. ];
  10380. return {
  10381. w: helpers_segment._longestText(ctx, font.string, label),
  10382. h: label.length * font.lineHeight
  10383. };
  10384. }
  10385. function determineLimits(angle, pos, size, min, max) {
  10386. if (angle === min || angle === max) {
  10387. return {
  10388. start: pos - size / 2,
  10389. end: pos + size / 2
  10390. };
  10391. } else if (angle < min || angle > max) {
  10392. return {
  10393. start: pos - size,
  10394. end: pos
  10395. };
  10396. }
  10397. return {
  10398. start: pos,
  10399. end: pos + size
  10400. };
  10401. }
  10402. function fitWithPointLabels(scale) {
  10403. const orig = {
  10404. l: scale.left + scale._padding.left,
  10405. r: scale.right - scale._padding.right,
  10406. t: scale.top + scale._padding.top,
  10407. b: scale.bottom - scale._padding.bottom
  10408. };
  10409. const limits = Object.assign({}, orig);
  10410. const labelSizes = [];
  10411. const padding = [];
  10412. const valueCount = scale._pointLabels.length;
  10413. const pointLabelOpts = scale.options.pointLabels;
  10414. const additionalAngle = pointLabelOpts.centerPointLabels ? helpers_segment.PI / valueCount : 0;
  10415. for(let i = 0; i < valueCount; i++){
  10416. const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i));
  10417. padding[i] = opts.padding;
  10418. const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle);
  10419. const plFont = helpers_segment.toFont(opts.font);
  10420. const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);
  10421. labelSizes[i] = textSize;
  10422. const angleRadians = helpers_segment._normalizeAngle(scale.getIndexAngle(i) + additionalAngle);
  10423. const angle = Math.round(helpers_segment.toDegrees(angleRadians));
  10424. const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  10425. const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  10426. updateLimits(limits, orig, angleRadians, hLimits, vLimits);
  10427. }
  10428. scale.setCenterPoint(orig.l - limits.l, limits.r - orig.r, orig.t - limits.t, limits.b - orig.b);
  10429. scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);
  10430. }
  10431. function updateLimits(limits, orig, angle, hLimits, vLimits) {
  10432. const sin = Math.abs(Math.sin(angle));
  10433. const cos = Math.abs(Math.cos(angle));
  10434. let x = 0;
  10435. let y = 0;
  10436. if (hLimits.start < orig.l) {
  10437. x = (orig.l - hLimits.start) / sin;
  10438. limits.l = Math.min(limits.l, orig.l - x);
  10439. } else if (hLimits.end > orig.r) {
  10440. x = (hLimits.end - orig.r) / sin;
  10441. limits.r = Math.max(limits.r, orig.r + x);
  10442. }
  10443. if (vLimits.start < orig.t) {
  10444. y = (orig.t - vLimits.start) / cos;
  10445. limits.t = Math.min(limits.t, orig.t - y);
  10446. } else if (vLimits.end > orig.b) {
  10447. y = (vLimits.end - orig.b) / cos;
  10448. limits.b = Math.max(limits.b, orig.b + y);
  10449. }
  10450. }
  10451. function createPointLabelItem(scale, index, itemOpts) {
  10452. const outerDistance = scale.drawingArea;
  10453. const { extra , additionalAngle , padding , size } = itemOpts;
  10454. const pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle);
  10455. const angle = Math.round(helpers_segment.toDegrees(helpers_segment._normalizeAngle(pointLabelPosition.angle + helpers_segment.HALF_PI)));
  10456. const y = yForAngle(pointLabelPosition.y, size.h, angle);
  10457. const textAlign = getTextAlignForAngle(angle);
  10458. const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);
  10459. return {
  10460. visible: true,
  10461. x: pointLabelPosition.x,
  10462. y,
  10463. textAlign,
  10464. left,
  10465. top: y,
  10466. right: left + size.w,
  10467. bottom: y + size.h
  10468. };
  10469. }
  10470. function isNotOverlapped(item, area) {
  10471. if (!area) {
  10472. return true;
  10473. }
  10474. const { left , top , right , bottom } = item;
  10475. const apexesInArea = helpers_segment._isPointInArea({
  10476. x: left,
  10477. y: top
  10478. }, area) || helpers_segment._isPointInArea({
  10479. x: left,
  10480. y: bottom
  10481. }, area) || helpers_segment._isPointInArea({
  10482. x: right,
  10483. y: top
  10484. }, area) || helpers_segment._isPointInArea({
  10485. x: right,
  10486. y: bottom
  10487. }, area);
  10488. return !apexesInArea;
  10489. }
  10490. function buildPointLabelItems(scale, labelSizes, padding) {
  10491. const items = [];
  10492. const valueCount = scale._pointLabels.length;
  10493. const opts = scale.options;
  10494. const { centerPointLabels , display } = opts.pointLabels;
  10495. const itemOpts = {
  10496. extra: getTickBackdropHeight(opts) / 2,
  10497. additionalAngle: centerPointLabels ? helpers_segment.PI / valueCount : 0
  10498. };
  10499. let area;
  10500. for(let i = 0; i < valueCount; i++){
  10501. itemOpts.padding = padding[i];
  10502. itemOpts.size = labelSizes[i];
  10503. const item = createPointLabelItem(scale, i, itemOpts);
  10504. items.push(item);
  10505. if (display === 'auto') {
  10506. item.visible = isNotOverlapped(item, area);
  10507. if (item.visible) {
  10508. area = item;
  10509. }
  10510. }
  10511. }
  10512. return items;
  10513. }
  10514. function getTextAlignForAngle(angle) {
  10515. if (angle === 0 || angle === 180) {
  10516. return 'center';
  10517. } else if (angle < 180) {
  10518. return 'left';
  10519. }
  10520. return 'right';
  10521. }
  10522. function leftForTextAlign(x, w, align) {
  10523. if (align === 'right') {
  10524. x -= w;
  10525. } else if (align === 'center') {
  10526. x -= w / 2;
  10527. }
  10528. return x;
  10529. }
  10530. function yForAngle(y, h, angle) {
  10531. if (angle === 90 || angle === 270) {
  10532. y -= h / 2;
  10533. } else if (angle > 270 || angle < 90) {
  10534. y -= h;
  10535. }
  10536. return y;
  10537. }
  10538. function drawPointLabelBox(ctx, opts, item) {
  10539. const { left , top , right , bottom } = item;
  10540. const { backdropColor } = opts;
  10541. if (!helpers_segment.isNullOrUndef(backdropColor)) {
  10542. const borderRadius = helpers_segment.toTRBLCorners(opts.borderRadius);
  10543. const padding = helpers_segment.toPadding(opts.backdropPadding);
  10544. ctx.fillStyle = backdropColor;
  10545. const backdropLeft = left - padding.left;
  10546. const backdropTop = top - padding.top;
  10547. const backdropWidth = right - left + padding.width;
  10548. const backdropHeight = bottom - top + padding.height;
  10549. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  10550. ctx.beginPath();
  10551. helpers_segment.addRoundedRectPath(ctx, {
  10552. x: backdropLeft,
  10553. y: backdropTop,
  10554. w: backdropWidth,
  10555. h: backdropHeight,
  10556. radius: borderRadius
  10557. });
  10558. ctx.fill();
  10559. } else {
  10560. ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight);
  10561. }
  10562. }
  10563. }
  10564. function drawPointLabels(scale, labelCount) {
  10565. const { ctx , options: { pointLabels } } = scale;
  10566. for(let i = labelCount - 1; i >= 0; i--){
  10567. const item = scale._pointLabelItems[i];
  10568. if (!item.visible) {
  10569. continue;
  10570. }
  10571. const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));
  10572. drawPointLabelBox(ctx, optsAtIndex, item);
  10573. const plFont = helpers_segment.toFont(optsAtIndex.font);
  10574. const { x , y , textAlign } = item;
  10575. helpers_segment.renderText(ctx, scale._pointLabels[i], x, y + plFont.lineHeight / 2, plFont, {
  10576. color: optsAtIndex.color,
  10577. textAlign: textAlign,
  10578. textBaseline: 'middle'
  10579. });
  10580. }
  10581. }
  10582. function pathRadiusLine(scale, radius, circular, labelCount) {
  10583. const { ctx } = scale;
  10584. if (circular) {
  10585. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, helpers_segment.TAU);
  10586. } else {
  10587. let pointPosition = scale.getPointPosition(0, radius);
  10588. ctx.moveTo(pointPosition.x, pointPosition.y);
  10589. for(let i = 1; i < labelCount; i++){
  10590. pointPosition = scale.getPointPosition(i, radius);
  10591. ctx.lineTo(pointPosition.x, pointPosition.y);
  10592. }
  10593. }
  10594. }
  10595. function drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) {
  10596. const ctx = scale.ctx;
  10597. const circular = gridLineOpts.circular;
  10598. const { color , lineWidth } = gridLineOpts;
  10599. if (!circular && !labelCount || !color || !lineWidth || radius < 0) {
  10600. return;
  10601. }
  10602. ctx.save();
  10603. ctx.strokeStyle = color;
  10604. ctx.lineWidth = lineWidth;
  10605. ctx.setLineDash(borderOpts.dash);
  10606. ctx.lineDashOffset = borderOpts.dashOffset;
  10607. ctx.beginPath();
  10608. pathRadiusLine(scale, radius, circular, labelCount);
  10609. ctx.closePath();
  10610. ctx.stroke();
  10611. ctx.restore();
  10612. }
  10613. function createPointLabelContext(parent, index, label) {
  10614. return helpers_segment.createContext(parent, {
  10615. label,
  10616. index,
  10617. type: 'pointLabel'
  10618. });
  10619. }
  10620. class RadialLinearScale extends LinearScaleBase {
  10621. static id = 'radialLinear';
  10622. static defaults = {
  10623. display: true,
  10624. animate: true,
  10625. position: 'chartArea',
  10626. angleLines: {
  10627. display: true,
  10628. lineWidth: 1,
  10629. borderDash: [],
  10630. borderDashOffset: 0.0
  10631. },
  10632. grid: {
  10633. circular: false
  10634. },
  10635. startAngle: 0,
  10636. ticks: {
  10637. showLabelBackdrop: true,
  10638. callback: helpers_segment.Ticks.formatters.numeric
  10639. },
  10640. pointLabels: {
  10641. backdropColor: undefined,
  10642. backdropPadding: 2,
  10643. display: true,
  10644. font: {
  10645. size: 10
  10646. },
  10647. callback (label) {
  10648. return label;
  10649. },
  10650. padding: 5,
  10651. centerPointLabels: false
  10652. }
  10653. };
  10654. static defaultRoutes = {
  10655. 'angleLines.color': 'borderColor',
  10656. 'pointLabels.color': 'color',
  10657. 'ticks.color': 'color'
  10658. };
  10659. static descriptors = {
  10660. angleLines: {
  10661. _fallback: 'grid'
  10662. }
  10663. };
  10664. constructor(cfg){
  10665. super(cfg);
  10666. this.xCenter = undefined;
  10667. this.yCenter = undefined;
  10668. this.drawingArea = undefined;
  10669. this._pointLabels = [];
  10670. this._pointLabelItems = [];
  10671. }
  10672. setDimensions() {
  10673. const padding = this._padding = helpers_segment.toPadding(getTickBackdropHeight(this.options) / 2);
  10674. const w = this.width = this.maxWidth - padding.width;
  10675. const h = this.height = this.maxHeight - padding.height;
  10676. this.xCenter = Math.floor(this.left + w / 2 + padding.left);
  10677. this.yCenter = Math.floor(this.top + h / 2 + padding.top);
  10678. this.drawingArea = Math.floor(Math.min(w, h) / 2);
  10679. }
  10680. determineDataLimits() {
  10681. const { min , max } = this.getMinMax(false);
  10682. this.min = helpers_segment.isNumberFinite(min) && !isNaN(min) ? min : 0;
  10683. this.max = helpers_segment.isNumberFinite(max) && !isNaN(max) ? max : 0;
  10684. this.handleTickRangeOptions();
  10685. }
  10686. computeTickLimit() {
  10687. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  10688. }
  10689. generateTickLabels(ticks) {
  10690. LinearScaleBase.prototype.generateTickLabels.call(this, ticks);
  10691. this._pointLabels = this.getLabels().map((value, index)=>{
  10692. const label = helpers_segment.callback(this.options.pointLabels.callback, [
  10693. value,
  10694. index
  10695. ], this);
  10696. return label || label === 0 ? label : '';
  10697. }).filter((v, i)=>this.chart.getDataVisibility(i));
  10698. }
  10699. fit() {
  10700. const opts = this.options;
  10701. if (opts.display && opts.pointLabels.display) {
  10702. fitWithPointLabels(this);
  10703. } else {
  10704. this.setCenterPoint(0, 0, 0, 0);
  10705. }
  10706. }
  10707. setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
  10708. this.xCenter += Math.floor((leftMovement - rightMovement) / 2);
  10709. this.yCenter += Math.floor((topMovement - bottomMovement) / 2);
  10710. this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement));
  10711. }
  10712. getIndexAngle(index) {
  10713. const angleMultiplier = helpers_segment.TAU / (this._pointLabels.length || 1);
  10714. const startAngle = this.options.startAngle || 0;
  10715. return helpers_segment._normalizeAngle(index * angleMultiplier + helpers_segment.toRadians(startAngle));
  10716. }
  10717. getDistanceFromCenterForValue(value) {
  10718. if (helpers_segment.isNullOrUndef(value)) {
  10719. return NaN;
  10720. }
  10721. const scalingFactor = this.drawingArea / (this.max - this.min);
  10722. if (this.options.reverse) {
  10723. return (this.max - value) * scalingFactor;
  10724. }
  10725. return (value - this.min) * scalingFactor;
  10726. }
  10727. getValueForDistanceFromCenter(distance) {
  10728. if (helpers_segment.isNullOrUndef(distance)) {
  10729. return NaN;
  10730. }
  10731. const scaledDistance = distance / (this.drawingArea / (this.max - this.min));
  10732. return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance;
  10733. }
  10734. getPointLabelContext(index) {
  10735. const pointLabels = this._pointLabels || [];
  10736. if (index >= 0 && index < pointLabels.length) {
  10737. const pointLabel = pointLabels[index];
  10738. return createPointLabelContext(this.getContext(), index, pointLabel);
  10739. }
  10740. }
  10741. getPointPosition(index, distanceFromCenter, additionalAngle = 0) {
  10742. const angle = this.getIndexAngle(index) - helpers_segment.HALF_PI + additionalAngle;
  10743. return {
  10744. x: Math.cos(angle) * distanceFromCenter + this.xCenter,
  10745. y: Math.sin(angle) * distanceFromCenter + this.yCenter,
  10746. angle
  10747. };
  10748. }
  10749. getPointPositionForValue(index, value) {
  10750. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  10751. }
  10752. getBasePosition(index) {
  10753. return this.getPointPositionForValue(index || 0, this.getBaseValue());
  10754. }
  10755. getPointLabelPosition(index) {
  10756. const { left , top , right , bottom } = this._pointLabelItems[index];
  10757. return {
  10758. left,
  10759. top,
  10760. right,
  10761. bottom
  10762. };
  10763. }
  10764. drawBackground() {
  10765. const { backgroundColor , grid: { circular } } = this.options;
  10766. if (backgroundColor) {
  10767. const ctx = this.ctx;
  10768. ctx.save();
  10769. ctx.beginPath();
  10770. pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length);
  10771. ctx.closePath();
  10772. ctx.fillStyle = backgroundColor;
  10773. ctx.fill();
  10774. ctx.restore();
  10775. }
  10776. }
  10777. drawGrid() {
  10778. const ctx = this.ctx;
  10779. const opts = this.options;
  10780. const { angleLines , grid , border } = opts;
  10781. const labelCount = this._pointLabels.length;
  10782. let i, offset, position;
  10783. if (opts.pointLabels.display) {
  10784. drawPointLabels(this, labelCount);
  10785. }
  10786. if (grid.display) {
  10787. this.ticks.forEach((tick, index)=>{
  10788. if (index !== 0 || index === 0 && this.min < 0) {
  10789. offset = this.getDistanceFromCenterForValue(tick.value);
  10790. const context = this.getContext(index);
  10791. const optsAtIndex = grid.setContext(context);
  10792. const optsAtIndexBorder = border.setContext(context);
  10793. drawRadiusLine(this, optsAtIndex, offset, labelCount, optsAtIndexBorder);
  10794. }
  10795. });
  10796. }
  10797. if (angleLines.display) {
  10798. ctx.save();
  10799. for(i = labelCount - 1; i >= 0; i--){
  10800. const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i));
  10801. const { color , lineWidth } = optsAtIndex;
  10802. if (!lineWidth || !color) {
  10803. continue;
  10804. }
  10805. ctx.lineWidth = lineWidth;
  10806. ctx.strokeStyle = color;
  10807. ctx.setLineDash(optsAtIndex.borderDash);
  10808. ctx.lineDashOffset = optsAtIndex.borderDashOffset;
  10809. offset = this.getDistanceFromCenterForValue(opts.ticks.reverse ? this.min : this.max);
  10810. position = this.getPointPosition(i, offset);
  10811. ctx.beginPath();
  10812. ctx.moveTo(this.xCenter, this.yCenter);
  10813. ctx.lineTo(position.x, position.y);
  10814. ctx.stroke();
  10815. }
  10816. ctx.restore();
  10817. }
  10818. }
  10819. drawBorder() {}
  10820. drawLabels() {
  10821. const ctx = this.ctx;
  10822. const opts = this.options;
  10823. const tickOpts = opts.ticks;
  10824. if (!tickOpts.display) {
  10825. return;
  10826. }
  10827. const startAngle = this.getIndexAngle(0);
  10828. let offset, width;
  10829. ctx.save();
  10830. ctx.translate(this.xCenter, this.yCenter);
  10831. ctx.rotate(startAngle);
  10832. ctx.textAlign = 'center';
  10833. ctx.textBaseline = 'middle';
  10834. this.ticks.forEach((tick, index)=>{
  10835. if (index === 0 && this.min >= 0 && !opts.reverse) {
  10836. return;
  10837. }
  10838. const optsAtIndex = tickOpts.setContext(this.getContext(index));
  10839. const tickFont = helpers_segment.toFont(optsAtIndex.font);
  10840. offset = this.getDistanceFromCenterForValue(this.ticks[index].value);
  10841. if (optsAtIndex.showLabelBackdrop) {
  10842. ctx.font = tickFont.string;
  10843. width = ctx.measureText(tick.label).width;
  10844. ctx.fillStyle = optsAtIndex.backdropColor;
  10845. const padding = helpers_segment.toPadding(optsAtIndex.backdropPadding);
  10846. ctx.fillRect(-width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height);
  10847. }
  10848. helpers_segment.renderText(ctx, tick.label, 0, -offset, tickFont, {
  10849. color: optsAtIndex.color,
  10850. strokeColor: optsAtIndex.textStrokeColor,
  10851. strokeWidth: optsAtIndex.textStrokeWidth
  10852. });
  10853. });
  10854. ctx.restore();
  10855. }
  10856. drawTitle() {}
  10857. }
  10858. const INTERVALS = {
  10859. millisecond: {
  10860. common: true,
  10861. size: 1,
  10862. steps: 1000
  10863. },
  10864. second: {
  10865. common: true,
  10866. size: 1000,
  10867. steps: 60
  10868. },
  10869. minute: {
  10870. common: true,
  10871. size: 60000,
  10872. steps: 60
  10873. },
  10874. hour: {
  10875. common: true,
  10876. size: 3600000,
  10877. steps: 24
  10878. },
  10879. day: {
  10880. common: true,
  10881. size: 86400000,
  10882. steps: 30
  10883. },
  10884. week: {
  10885. common: false,
  10886. size: 604800000,
  10887. steps: 4
  10888. },
  10889. month: {
  10890. common: true,
  10891. size: 2.628e9,
  10892. steps: 12
  10893. },
  10894. quarter: {
  10895. common: false,
  10896. size: 7.884e9,
  10897. steps: 4
  10898. },
  10899. year: {
  10900. common: true,
  10901. size: 3.154e10
  10902. }
  10903. };
  10904. const UNITS = /* #__PURE__ */ Object.keys(INTERVALS);
  10905. function sorter(a, b) {
  10906. return a - b;
  10907. }
  10908. function parse(scale, input) {
  10909. if (helpers_segment.isNullOrUndef(input)) {
  10910. return null;
  10911. }
  10912. const adapter = scale._adapter;
  10913. const { parser , round , isoWeekday } = scale._parseOpts;
  10914. let value = input;
  10915. if (typeof parser === 'function') {
  10916. value = parser(value);
  10917. }
  10918. if (!helpers_segment.isNumberFinite(value)) {
  10919. value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value);
  10920. }
  10921. if (value === null) {
  10922. return null;
  10923. }
  10924. if (round) {
  10925. value = round === 'week' && (helpers_segment.isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round);
  10926. }
  10927. return +value;
  10928. }
  10929. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  10930. const ilen = UNITS.length;
  10931. for(let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i){
  10932. const interval = INTERVALS[UNITS[i]];
  10933. const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
  10934. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  10935. return UNITS[i];
  10936. }
  10937. }
  10938. return UNITS[ilen - 1];
  10939. }
  10940. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  10941. for(let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--){
  10942. const unit = UNITS[i];
  10943. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  10944. return unit;
  10945. }
  10946. }
  10947. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  10948. }
  10949. function determineMajorUnit(unit) {
  10950. for(let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i){
  10951. if (INTERVALS[UNITS[i]].common) {
  10952. return UNITS[i];
  10953. }
  10954. }
  10955. }
  10956. function addTick(ticks, time, timestamps) {
  10957. if (!timestamps) {
  10958. ticks[time] = true;
  10959. } else if (timestamps.length) {
  10960. const { lo , hi } = helpers_segment._lookup(timestamps, time);
  10961. const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
  10962. ticks[timestamp] = true;
  10963. }
  10964. }
  10965. function setMajorTicks(scale, ticks, map, majorUnit) {
  10966. const adapter = scale._adapter;
  10967. const first = +adapter.startOf(ticks[0].value, majorUnit);
  10968. const last = ticks[ticks.length - 1].value;
  10969. let major, index;
  10970. for(major = first; major <= last; major = +adapter.add(major, 1, majorUnit)){
  10971. index = map[major];
  10972. if (index >= 0) {
  10973. ticks[index].major = true;
  10974. }
  10975. }
  10976. return ticks;
  10977. }
  10978. function ticksFromTimestamps(scale, values, majorUnit) {
  10979. const ticks = [];
  10980. const map = {};
  10981. const ilen = values.length;
  10982. let i, value;
  10983. for(i = 0; i < ilen; ++i){
  10984. value = values[i];
  10985. map[value] = i;
  10986. ticks.push({
  10987. value,
  10988. major: false
  10989. });
  10990. }
  10991. return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  10992. }
  10993. class TimeScale extends Scale {
  10994. static id = 'time';
  10995. static defaults = {
  10996. bounds: 'data',
  10997. adapters: {},
  10998. time: {
  10999. parser: false,
  11000. unit: false,
  11001. round: false,
  11002. isoWeekday: false,
  11003. minUnit: 'millisecond',
  11004. displayFormats: {}
  11005. },
  11006. ticks: {
  11007. source: 'auto',
  11008. callback: false,
  11009. major: {
  11010. enabled: false
  11011. }
  11012. }
  11013. };
  11014. constructor(props){
  11015. super(props);
  11016. this._cache = {
  11017. data: [],
  11018. labels: [],
  11019. all: []
  11020. };
  11021. this._unit = 'day';
  11022. this._majorUnit = undefined;
  11023. this._offsets = {};
  11024. this._normalized = false;
  11025. this._parseOpts = undefined;
  11026. }
  11027. init(scaleOpts, opts = {}) {
  11028. const time = scaleOpts.time || (scaleOpts.time = {});
  11029. const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
  11030. adapter.init(opts);
  11031. helpers_segment.mergeIf(time.displayFormats, adapter.formats());
  11032. this._parseOpts = {
  11033. parser: time.parser,
  11034. round: time.round,
  11035. isoWeekday: time.isoWeekday
  11036. };
  11037. super.init(scaleOpts);
  11038. this._normalized = opts.normalized;
  11039. }
  11040. parse(raw, index) {
  11041. if (raw === undefined) {
  11042. return null;
  11043. }
  11044. return parse(this, raw);
  11045. }
  11046. beforeLayout() {
  11047. super.beforeLayout();
  11048. this._cache = {
  11049. data: [],
  11050. labels: [],
  11051. all: []
  11052. };
  11053. }
  11054. determineDataLimits() {
  11055. const options = this.options;
  11056. const adapter = this._adapter;
  11057. const unit = options.time.unit || 'day';
  11058. let { min , max , minDefined , maxDefined } = this.getUserBounds();
  11059. function _applyBounds(bounds) {
  11060. if (!minDefined && !isNaN(bounds.min)) {
  11061. min = Math.min(min, bounds.min);
  11062. }
  11063. if (!maxDefined && !isNaN(bounds.max)) {
  11064. max = Math.max(max, bounds.max);
  11065. }
  11066. }
  11067. if (!minDefined || !maxDefined) {
  11068. _applyBounds(this._getLabelBounds());
  11069. if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
  11070. _applyBounds(this.getMinMax(false));
  11071. }
  11072. }
  11073. min = helpers_segment.isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
  11074. max = helpers_segment.isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
  11075. this.min = Math.min(min, max - 1);
  11076. this.max = Math.max(min + 1, max);
  11077. }
  11078. _getLabelBounds() {
  11079. const arr = this.getLabelTimestamps();
  11080. let min = Number.POSITIVE_INFINITY;
  11081. let max = Number.NEGATIVE_INFINITY;
  11082. if (arr.length) {
  11083. min = arr[0];
  11084. max = arr[arr.length - 1];
  11085. }
  11086. return {
  11087. min,
  11088. max
  11089. };
  11090. }
  11091. buildTicks() {
  11092. const options = this.options;
  11093. const timeOpts = options.time;
  11094. const tickOpts = options.ticks;
  11095. const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate();
  11096. if (options.bounds === 'ticks' && timestamps.length) {
  11097. this.min = this._userMin || timestamps[0];
  11098. this.max = this._userMax || timestamps[timestamps.length - 1];
  11099. }
  11100. const min = this.min;
  11101. const max = this.max;
  11102. const ticks = helpers_segment._filterBetween(timestamps, min, max);
  11103. 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));
  11104. this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined : determineMajorUnit(this._unit);
  11105. this.initOffsets(timestamps);
  11106. if (options.reverse) {
  11107. ticks.reverse();
  11108. }
  11109. return ticksFromTimestamps(this, ticks, this._majorUnit);
  11110. }
  11111. afterAutoSkip() {
  11112. if (this.options.offsetAfterAutoskip) {
  11113. this.initOffsets(this.ticks.map((tick)=>+tick.value));
  11114. }
  11115. }
  11116. initOffsets(timestamps = []) {
  11117. let start = 0;
  11118. let end = 0;
  11119. let first, last;
  11120. if (this.options.offset && timestamps.length) {
  11121. first = this.getDecimalForValue(timestamps[0]);
  11122. if (timestamps.length === 1) {
  11123. start = 1 - first;
  11124. } else {
  11125. start = (this.getDecimalForValue(timestamps[1]) - first) / 2;
  11126. }
  11127. last = this.getDecimalForValue(timestamps[timestamps.length - 1]);
  11128. if (timestamps.length === 1) {
  11129. end = last;
  11130. } else {
  11131. end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
  11132. }
  11133. }
  11134. const limit = timestamps.length < 3 ? 0.5 : 0.25;
  11135. start = helpers_segment._limitValue(start, 0, limit);
  11136. end = helpers_segment._limitValue(end, 0, limit);
  11137. this._offsets = {
  11138. start,
  11139. end,
  11140. factor: 1 / (start + 1 + end)
  11141. };
  11142. }
  11143. _generate() {
  11144. const adapter = this._adapter;
  11145. const min = this.min;
  11146. const max = this.max;
  11147. const options = this.options;
  11148. const timeOpts = options.time;
  11149. const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min));
  11150. const stepSize = helpers_segment.valueOrDefault(options.ticks.stepSize, 1);
  11151. const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  11152. const hasWeekday = helpers_segment.isNumber(weekday) || weekday === true;
  11153. const ticks = {};
  11154. let first = min;
  11155. let time, count;
  11156. if (hasWeekday) {
  11157. first = +adapter.startOf(first, 'isoWeek', weekday);
  11158. }
  11159. first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
  11160. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  11161. throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
  11162. }
  11163. const timestamps = options.ticks.source === 'data' && this.getDataTimestamps();
  11164. for(time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++){
  11165. addTick(ticks, time, timestamps);
  11166. }
  11167. if (time === max || options.bounds === 'ticks' || count === 1) {
  11168. addTick(ticks, time, timestamps);
  11169. }
  11170. return Object.keys(ticks).sort(sorter).map((x)=>+x);
  11171. }
  11172. getLabelForValue(value) {
  11173. const adapter = this._adapter;
  11174. const timeOpts = this.options.time;
  11175. if (timeOpts.tooltipFormat) {
  11176. return adapter.format(value, timeOpts.tooltipFormat);
  11177. }
  11178. return adapter.format(value, timeOpts.displayFormats.datetime);
  11179. }
  11180. format(value, format) {
  11181. const options = this.options;
  11182. const formats = options.time.displayFormats;
  11183. const unit = this._unit;
  11184. const fmt = format || formats[unit];
  11185. return this._adapter.format(value, fmt);
  11186. }
  11187. _tickFormatFunction(time, index, ticks, format) {
  11188. const options = this.options;
  11189. const formatter = options.ticks.callback;
  11190. if (formatter) {
  11191. return helpers_segment.callback(formatter, [
  11192. time,
  11193. index,
  11194. ticks
  11195. ], this);
  11196. }
  11197. const formats = options.time.displayFormats;
  11198. const unit = this._unit;
  11199. const majorUnit = this._majorUnit;
  11200. const minorFormat = unit && formats[unit];
  11201. const majorFormat = majorUnit && formats[majorUnit];
  11202. const tick = ticks[index];
  11203. const major = majorUnit && majorFormat && tick && tick.major;
  11204. return this._adapter.format(time, format || (major ? majorFormat : minorFormat));
  11205. }
  11206. generateTickLabels(ticks) {
  11207. let i, ilen, tick;
  11208. for(i = 0, ilen = ticks.length; i < ilen; ++i){
  11209. tick = ticks[i];
  11210. tick.label = this._tickFormatFunction(tick.value, i, ticks);
  11211. }
  11212. }
  11213. getDecimalForValue(value) {
  11214. return value === null ? NaN : (value - this.min) / (this.max - this.min);
  11215. }
  11216. getPixelForValue(value) {
  11217. const offsets = this._offsets;
  11218. const pos = this.getDecimalForValue(value);
  11219. return this.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  11220. }
  11221. getValueForPixel(pixel) {
  11222. const offsets = this._offsets;
  11223. const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  11224. return this.min + pos * (this.max - this.min);
  11225. }
  11226. _getLabelSize(label) {
  11227. const ticksOpts = this.options.ticks;
  11228. const tickLabelWidth = this.ctx.measureText(label).width;
  11229. const angle = helpers_segment.toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  11230. const cosRotation = Math.cos(angle);
  11231. const sinRotation = Math.sin(angle);
  11232. const tickFontSize = this._resolveTickFontOptions(0).size;
  11233. return {
  11234. w: tickLabelWidth * cosRotation + tickFontSize * sinRotation,
  11235. h: tickLabelWidth * sinRotation + tickFontSize * cosRotation
  11236. };
  11237. }
  11238. _getLabelCapacity(exampleTime) {
  11239. const timeOpts = this.options.time;
  11240. const displayFormats = timeOpts.displayFormats;
  11241. const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  11242. const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [
  11243. exampleTime
  11244. ], this._majorUnit), format);
  11245. const size = this._getLabelSize(exampleLabel);
  11246. const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1;
  11247. return capacity > 0 ? capacity : 1;
  11248. }
  11249. getDataTimestamps() {
  11250. let timestamps = this._cache.data || [];
  11251. let i, ilen;
  11252. if (timestamps.length) {
  11253. return timestamps;
  11254. }
  11255. const metas = this.getMatchingVisibleMetas();
  11256. if (this._normalized && metas.length) {
  11257. return this._cache.data = metas[0].controller.getAllParsedValues(this);
  11258. }
  11259. for(i = 0, ilen = metas.length; i < ilen; ++i){
  11260. timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this));
  11261. }
  11262. return this._cache.data = this.normalize(timestamps);
  11263. }
  11264. getLabelTimestamps() {
  11265. const timestamps = this._cache.labels || [];
  11266. let i, ilen;
  11267. if (timestamps.length) {
  11268. return timestamps;
  11269. }
  11270. const labels = this.getLabels();
  11271. for(i = 0, ilen = labels.length; i < ilen; ++i){
  11272. timestamps.push(parse(this, labels[i]));
  11273. }
  11274. return this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps);
  11275. }
  11276. normalize(values) {
  11277. return helpers_segment._arrayUnique(values.sort(sorter));
  11278. }
  11279. }
  11280. function interpolate(table, val, reverse) {
  11281. let lo = 0;
  11282. let hi = table.length - 1;
  11283. let prevSource, nextSource, prevTarget, nextTarget;
  11284. if (reverse) {
  11285. if (val >= table[lo].pos && val <= table[hi].pos) {
  11286. ({ lo , hi } = helpers_segment._lookupByKey(table, 'pos', val));
  11287. }
  11288. ({ pos: prevSource , time: prevTarget } = table[lo]);
  11289. ({ pos: nextSource , time: nextTarget } = table[hi]);
  11290. } else {
  11291. if (val >= table[lo].time && val <= table[hi].time) {
  11292. ({ lo , hi } = helpers_segment._lookupByKey(table, 'time', val));
  11293. }
  11294. ({ time: prevSource , pos: prevTarget } = table[lo]);
  11295. ({ time: nextSource , pos: nextTarget } = table[hi]);
  11296. }
  11297. const span = nextSource - prevSource;
  11298. return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
  11299. }
  11300. class TimeSeriesScale extends TimeScale {
  11301. static id = 'timeseries';
  11302. static defaults = TimeScale.defaults;
  11303. constructor(props){
  11304. super(props);
  11305. this._table = [];
  11306. this._minPos = undefined;
  11307. this._tableRange = undefined;
  11308. }
  11309. initOffsets() {
  11310. const timestamps = this._getTimestampsForTable();
  11311. const table = this._table = this.buildLookupTable(timestamps);
  11312. this._minPos = interpolate(table, this.min);
  11313. this._tableRange = interpolate(table, this.max) - this._minPos;
  11314. super.initOffsets(timestamps);
  11315. }
  11316. buildLookupTable(timestamps) {
  11317. const { min , max } = this;
  11318. const items = [];
  11319. const table = [];
  11320. let i, ilen, prev, curr, next;
  11321. for(i = 0, ilen = timestamps.length; i < ilen; ++i){
  11322. curr = timestamps[i];
  11323. if (curr >= min && curr <= max) {
  11324. items.push(curr);
  11325. }
  11326. }
  11327. if (items.length < 2) {
  11328. return [
  11329. {
  11330. time: min,
  11331. pos: 0
  11332. },
  11333. {
  11334. time: max,
  11335. pos: 1
  11336. }
  11337. ];
  11338. }
  11339. for(i = 0, ilen = items.length; i < ilen; ++i){
  11340. next = items[i + 1];
  11341. prev = items[i - 1];
  11342. curr = items[i];
  11343. if (Math.round((next + prev) / 2) !== curr) {
  11344. table.push({
  11345. time: curr,
  11346. pos: i / (ilen - 1)
  11347. });
  11348. }
  11349. }
  11350. return table;
  11351. }
  11352. _generate() {
  11353. const min = this.min;
  11354. const max = this.max;
  11355. let timestamps = super.getDataTimestamps();
  11356. if (!timestamps.includes(min) || !timestamps.length) {
  11357. timestamps.splice(0, 0, min);
  11358. }
  11359. if (!timestamps.includes(max) || timestamps.length === 1) {
  11360. timestamps.push(max);
  11361. }
  11362. return timestamps.sort((a, b)=>a - b);
  11363. }
  11364. _getTimestampsForTable() {
  11365. let timestamps = this._cache.all || [];
  11366. if (timestamps.length) {
  11367. return timestamps;
  11368. }
  11369. const data = this.getDataTimestamps();
  11370. const label = this.getLabelTimestamps();
  11371. if (data.length && label.length) {
  11372. timestamps = this.normalize(data.concat(label));
  11373. } else {
  11374. timestamps = data.length ? data : label;
  11375. }
  11376. timestamps = this._cache.all = timestamps;
  11377. return timestamps;
  11378. }
  11379. getDecimalForValue(value) {
  11380. return (interpolate(this._table, value) - this._minPos) / this._tableRange;
  11381. }
  11382. getValueForPixel(pixel) {
  11383. const offsets = this._offsets;
  11384. const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  11385. return interpolate(this._table, decimal * this._tableRange + this._minPos, true);
  11386. }
  11387. }
  11388. var scales = /*#__PURE__*/Object.freeze({
  11389. __proto__: null,
  11390. CategoryScale: CategoryScale,
  11391. LinearScale: LinearScale,
  11392. LogarithmicScale: LogarithmicScale,
  11393. RadialLinearScale: RadialLinearScale,
  11394. TimeScale: TimeScale,
  11395. TimeSeriesScale: TimeSeriesScale
  11396. });
  11397. const registerables = [
  11398. controllers,
  11399. elements,
  11400. plugins,
  11401. scales
  11402. ];
  11403. exports.Ticks = helpers_segment.Ticks;
  11404. exports.defaults = helpers_segment.defaults;
  11405. exports.Animation = Animation;
  11406. exports.Animations = Animations;
  11407. exports.ArcElement = ArcElement;
  11408. exports.BarController = BarController;
  11409. exports.BarElement = BarElement;
  11410. exports.BasePlatform = BasePlatform;
  11411. exports.BasicPlatform = BasicPlatform;
  11412. exports.BubbleController = BubbleController;
  11413. exports.CategoryScale = CategoryScale;
  11414. exports.Chart = Chart;
  11415. exports.Colors = plugin_colors;
  11416. exports.DatasetController = DatasetController;
  11417. exports.Decimation = plugin_decimation;
  11418. exports.DomPlatform = DomPlatform;
  11419. exports.DoughnutController = DoughnutController;
  11420. exports.Element = Element;
  11421. exports.Filler = index;
  11422. exports.Interaction = Interaction;
  11423. exports.Legend = plugin_legend;
  11424. exports.LineController = LineController;
  11425. exports.LineElement = LineElement;
  11426. exports.LinearScale = LinearScale;
  11427. exports.LogarithmicScale = LogarithmicScale;
  11428. exports.PieController = PieController;
  11429. exports.PointElement = PointElement;
  11430. exports.PolarAreaController = PolarAreaController;
  11431. exports.RadarController = RadarController;
  11432. exports.RadialLinearScale = RadialLinearScale;
  11433. exports.Scale = Scale;
  11434. exports.ScatterController = ScatterController;
  11435. exports.SubTitle = plugin_subtitle;
  11436. exports.TimeScale = TimeScale;
  11437. exports.TimeSeriesScale = TimeSeriesScale;
  11438. exports.Title = plugin_title;
  11439. exports.Tooltip = plugin_tooltip;
  11440. exports._adapters = adapters;
  11441. exports._detectPlatform = _detectPlatform;
  11442. exports.animator = animator;
  11443. exports.controllers = controllers;
  11444. exports.elements = elements;
  11445. exports.layouts = layouts;
  11446. exports.plugins = plugins;
  11447. exports.registerables = registerables;
  11448. exports.registry = registry;
  11449. exports.scales = scales;
  11450. //# sourceMappingURL=chart.cjs.map